【Darknet】yolo层forward_yolo_layer函数详解

最近在研究Darknet源码,这篇主要分享一下yolo层中forward_yolo_layer函数的源码。

前言

神经网络是由很多层叠加起来的,Darknet也不例外。Darknet中的每一层都有make_xxx_layer,forward_xxx_layer和backward_xxx_layer,分别表示构建这一层,这一层的正向传播和反向传播(对于有可学参数的层,还有update_xxx_layer,表示更新权重)。对于yolo层来说,make_yolo_layer就是分配空间,参数赋值等,而backward_yolo_layer就是把当前层产生的delta复制一下,都比较简单。最复杂的还是forward_yolo_layer。这里我参考了解析1解析2两篇关于forward_yolo_layer的解析,讲解的都很棒,通俗易懂,大家也可以参考来看看。但由于时间比较久远了,yolo层iou_thresh这个参数又有一些新东西,所以这篇文章说一下自己的理解。

forward_yolo_layer

进入forward_yolo_layer函数,一上来先对x,y,obj进行LOGISTIC激活

for (b = 0; b < l.batch; ++b)
{
    for (n = 0; n < l.n; ++n)
    {
        int bbox_index = entry_index(l, b, n*l.w*l.h, 0);
        if (l.new_coords)
        {
        }
        else //除了w,h都用LOGISTIC激活
        {
            activate_array(l.output + bbox_index, 2 * l.w*l.h, LOGISTIC);        // x,y,
            int obj_index = entry_index(l, b, n*l.w*l.h, 4);
            activate_array(l.output + obj_index, (1 + l.classes)*l.w*l.h, LOGISTIC); //obj class
        }
        scal_add_cpu(2 * l.w*l.h, l.scale_x_y, -0.5*(l.scale_x_y - 1), l.output + bbox_index, 1);    // scale x,y
    }
}

这里new_coords是一个比较新的参数,用于yolov4csp、yolov4xmish等比较新的网络(详情),据说是在conv层激活了,所以这里什么都不做。
scale_x_y表示中心点预测的范围扩大倍数(详情),扩大后有利于预测中心处于网格边界上的目标。

和老版Darknet不同的是,forward_yolo_layer里没有直接处理,而是调用了process_batch进行处理,不过意思是一样的,下面重点分析一下process_batch的实现。

process_batch

第一部分:处理每个bbox位置上的各种loss和delta

//第一部分:处理每个bbox位置上的各种loss和delta
//这一部分是遍历所有bbox,把每一个bbox与所有gt匹配,找到iou最大的,是由bbox出发找gt的过程
for (j = 0; j < l.h; ++j)
{
    for (i = 0; i < l.w; ++i)
    {
        for (n = 0; n < l.n; ++n)
        {
            const int class_index = entry_index(l, b, n * l.w * l.h + j * l.w + i, 5);
            const int obj_index = entry_index(l, b, n * l.w * l.h + j * l.w + i, 4);
            const int box_index = entry_index(l, b, n * l.w * l.h + j * l.w + i, 0);
            const int stride = l.w * l.h;
            box pred = get_yolo_box(l.output, l.biases, l.mask[n], box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.w * l.h, l.new_coords);
            float best_match_iou = 0;
            int best_match_t = 0;
            float best_iou = 0;
            int best_t = 0;
            for (t = 0; t < l.max_boxes; ++t)//遍历所有gt,无论中心是不是在这个gird
            {
                box truth = float_to_box_stride(state.truth + t * l.truth_size + b * l.truths, 1);
                if (!truth.x) break;  //无gt
                int class_id = state.truth[t * l.truth_size + b * l.truths + 4];//gt的类别
                if (class_id >= l.classes || class_id < 0)
                {
                    printf("\n Warning: in txt-labels class_id=%d >= classes=%d in cfg-file. In txt-labels class_id should be [from 0 to %d] \n", class_id, l.classes, l.classes - 1);
                    printf("\n truth.x = %f, truth.y = %f, truth.w = %f, truth.h = %f, class_id = %d \n", truth.x, truth.y, truth.w, truth.h, class_id);
                    if (check_mistakes) getchar();
                    continue; // if label contains class_id more than number of classes in the cfg-file and class_id check garbage value
                }
                float objectness = l.output[obj_index];
                if (isnan(objectness) || isinf(objectness)) l.output[obj_index] = 0;
                int class_id_match = compare_yolo_class(l.output, l.classes, class_index, l.w * l.h, objectness, class_id, 0.25f);
                float iou = box_iou(pred, truth);
                if (iou > best_match_iou && class_id_match == 1)
                {
                    best_match_iou = iou; //best_match_iou是与gt最大的iou且认为这个bbox至少有一个类
                    best_match_t = t;
                }
                if (iou > best_iou)
                {
                    best_iou = iou;//best_iou只是与gt最大的iou
                    best_t = t;
                }
            }
            
			//下面开始计算delta
            avg_anyobj += l.output[obj_index];
            l.delta[obj_index] = l.obj_normalizer * (0 - l.output[obj_index]);
            //如果没有gt,上面循环不执行,best_match_iou和best_iou为0,下面也不执行,视为负样本,只产生objloss
            if (best_match_iou > l.ignore_thresh)//如果iou超过ignore_thresh且对应一个类,delta清零,认为这是一个合法的目标
            {
                if (l.objectness_smooth)
                {                                                                                                                                                                            
                    const float delta_obj = l.obj_normalizer * (best_match_iou - l.output[obj_index]);
                    if (delta_obj > l.delta[obj_index]) l.delta[obj_index] = delta_obj;
                }
                else l.delta[obj_index] = 0;
            }
            //adversarial相关代码省略
            
            //一般cfg里truth_thresh为1,也就是说这里的delta_yolo_class和delta_yolo_box没调用过
            //如果这里小于1,相当于即使中心点没有落在gt所在gird但只要iou超过truth_thresh,那这个bbox也负责预测gt
            //结果是gt所在grid附近的gird都会预测这个gt,容易产生多重预测,但似乎也会被nms掉,所以感觉没啥用
            if (best_iou > l.truth_thresh)
            {
                const float iou_multiplier = best_iou * best_iou;// (best_iou - l.truth_thresh) / (1.0 - l.truth_thresh);
                if (l.objectness_smooth) l.delta[obj_index] = l.obj_normalizer * (iou_multiplier - l.output[obj_index]);
                else l.delta[obj_index] = l.obj_normalizer * (1 - l.output[obj_index]);
                int class_id = state.truth[best_t * l.truth_size + b * l.truths + 4];
                if (l.map) class_id = l.map[class_id];
                delta_yolo_class(l.output, l.delta, class_index, class_id, l.classes, l.w * l.h, 0, l.focal_loss, l.label_smooth_eps, l.classes_multipliers, l.cls_normalizer);
                const float class_multiplier = (l.classes_multipliers) ? l.classes_multipliers[class_id] : 1.0f;
                if (l.objectness_smooth) l.delta[class_index + stride * class_id] = class_multiplier * (iou_multiplier - l.output[class_index + stride * class_id]);
                box truth = float_to_box_stride(state.truth + best_t * l.truth_size + b * l.truths, 1);
                delta_yolo_box(truth, l.output, l.biases, l.mask[n], box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.delta, (2 - truth.w * truth.h), l.w * l.h, l.iou_normalizer * class_multiplier, l.iou_loss, 1, l.max_delta, state.net.rewritten_bbox, l.new_coords);
                (*state.net.total_bbox)++;
            }
        }
    }
}
//第一部分结束,至此只产生了obj delta(假设truth_thresh=1)
//对于无gt的bbox,这里的delta已经是最终delta了,而对于有gt的grid或bbox,到这里计算的delta没用,因为第二部分会用新值覆盖

对于长w宽h的yolo层,一共w*h个grid,每个grid预测n个bbox。对于每一个bbox,先取出其class_index、obj_index、box_index(这些index的取法与yolo层output的格式有关,详情见上面解析1,非常详细)。然后遍历所有gt(最大gt数为max_boxes,但一般都没有这么多,读到truth.x==0说明没有gt了),找到与bbox iou最大的gt best_t 和iou最大且类别匹配的gt best_match_t。到这里准备工作完成,下面开始计算delta了。
先把delta赋值为obj_normalizer * (0 - output[obj_index]),obj_normalizer为obj delta的系数,0为gt(这里先默认gt的obj为0,即没有目标),output[obj_index]为对应bbox的obj。这里细心的朋友应该能发现,正确的delta应该是预测-真值,这里正好相反。因为Darknet中的delta存的都是-delta,update存的也是相反数,而更新权重时是加上学习率×update。根据iou大小分三种情况讨论:
1.iou很小或为0
当做负样本,后面两个if不执行,只有obj delta,就是上面计算得到的(objectness_smooth忽略)。
2.iou>ignore_thresh
当做可行目标,不产生delta。当然其实只有这个bbox不负责预测gt,或者说gt中心点没有落在这个bbox时才是真正的obj delta=0,否则第二部分中会重新对该bbox的obj delta赋值。
3.iou>truth_thresh
当做正样本,产生三种delta,注意这里不需要类别相同,反正要去学习真正的类别(yolov3、yolov4等网络中truth_thresh为1,即没用这块代码)。
 
 
第二部分:处理每一个gt,分配最佳anchor,更新loss和delta

//第二部分:处理每一个gt,分配最佳anchor,更新loss和delta
//这部分是从gt出发,找到gt所在grid的几个bbox,并把gt分配给最大iou的bbox,如果开启了iou_thresh(<1),那么这个grid中所有bbox都预测gt
for (t = 0; t < l.max_boxes; ++t)
{
    box truth = float_to_box_stride(state.truth + t * l.truth_size + b * l.truths, 1);
    if (!truth.x) break;  // continue;
    if (truth.x < 0 || truth.y < 0 || truth.x > 1 || truth.y > 1 || truth.w < 0 || truth.h < 0)
    {
        char buff[256];
        printf(" Wrong label: truth.x = %f, truth.y = %f, truth.w = %f, truth.h = %f \n", truth.x, truth.y, truth.w, truth.h);
        sprintf(buff, "echo \"Wrong label: truth.x = %f, truth.y = %f, truth.w = %f, truth.h = %f\" >> bad_label.list",
            truth.x, truth.y, truth.w, truth.h);
        system(buff);
    }
    int class_id = state.truth[t * l.truth_size + b * l.truths + 4];
    if (class_id >= l.classes || class_id < 0) continue; // if label contains class_id more than number of classes in the cfg-file and class_id check garbage value
    float best_iou = 0;
    int best_n = 0;
    i = (truth.x * l.w);
    j = (truth.y * l.h);
    box truth_shift = truth;
    truth_shift.x = truth_shift.y = 0;
    for (n = 0; n < l.total; ++n)
    {
        box pred = { 0 };
        pred.w = l.biases[2 * n] / state.net.w;
        pred.h = l.biases[2 * n + 1] / state.net.h;
        float iou = box_iou(pred, truth_shift);
        if (iou > best_iou)
        {
            best_iou = iou;
            best_n = n;//第best_n个anchor iou最大
        }
    }
    int mask_n = int_index(l.mask, best_n, l.n);
    if (mask_n >= 0)//如果best_n这个anchor不在这个yolo层,不处理
    {
        int class_id = state.truth[t * l.truth_size + b * l.truths + 4];
        if (l.map) class_id = l.map[class_id];
        int box_index = entry_index(l, b, mask_n * l.w * l.h + j * l.w + i, 0);
        const float class_multiplier = (l.classes_multipliers) ? l.classes_multipliers[class_id] : 1.0f;
        //坐标delta
        ious all_ious = delta_yolo_box(truth, l.output, l.biases, best_n, box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.delta, (2 - truth.w * truth.h), l.w * l.h, l.iou_normalizer * class_multiplier, l.iou_loss, 1, l.max_delta, state.net.rewritten_bbox, l.new_coords);
        (*state.net.total_bbox)++;
        const int truth_in_index = t * l.truth_size + b * l.truths + 5;
        const int track_id = state.truth[truth_in_index];
        const int truth_out_index = b * l.n * l.w * l.h + mask_n * l.w * l.h + j * l.w + i;
        l.labels[truth_out_index] = track_id;
        l.class_ids[truth_out_index] = class_id;              
        // range is 0 <= 1
        args->tot_iou += all_ious.iou;
        args->tot_iou_loss += 1 - all_ious.iou;
        // range is -1 <= giou <= 1
        tot_giou += all_ious.giou;
        args->tot_giou_loss += 1 - all_ious.giou;
        tot_diou += all_ious.diou;
        tot_diou_loss += 1 - all_ious.diou;
        tot_ciou += all_ious.ciou;
        tot_ciou_loss += 1 - all_ious.ciou;
        int obj_index = entry_index(l, b, mask_n * l.w * l.h + j * l.w + i, 4);
        avg_obj += l.output[obj_index];
        //重新计算obj delta,覆盖第一部分
        if (l.objectness_smooth)
        {
            float delta_obj = class_multiplier * l.obj_normalizer * (1 - l.output[obj_index]);
            if (l.delta[obj_index] == 0) l.delta[obj_index] = delta_obj;
        }
        else l.delta[obj_index] = class_multiplier * l.obj_normalizer * (1 - l.output[obj_index]);
        //class delta
        int class_index = entry_index(l, b, mask_n * l.w * l.h + j * l.w + i, 4 + 1);
        delta_yolo_class(l.output, l.delta, class_index, class_id, l.classes, l.w * l.h, &avg_cat, l.focal_loss, l.label_smooth_eps, l.classes_multipliers, l.cls_normalizer);
        ++(args->count);
        ++(args->class_count);
        if (all_ious.iou > .5) recall += 1;
        if (all_ious.iou > .75) recall75 += 1;
    }
    
    //处理iou_thresh,使多个anchor同时预测一个gt
    for (n = 0; n < l.total; ++n)
    {
        int mask_n = int_index(l.mask, n, l.n);
        //这个mask_n指这个yolo层能取到的mask,假设这个yolo层的mask为0,1,2,那么外循环中n=0,1,2时mask_n=0,1,2,n>=3时mask_n=-1
        if (mask_n >= 0 && n != best_n && l.iou_thresh < 1.0f)
        //best_n对应的anchor已经处理过了,这里处理另外几个,iou>iou_thresh时,处理方式和上面相同,否则不处理
        //iou_thresh=1时这里不执行,parser.c中默认yolo层iou_thresh为1,即一个gt只分配给一个anchor检测
        {
            box pred = { 0 };
            pred.w = l.biases[2 * n] / state.net.w;
            pred.h = l.biases[2 * n + 1] / state.net.h;
            float iou = box_iou_kind(pred, truth_shift, l.iou_thresh_kind); // IOU, GIOU, MSE, DIOU, CIOU
            if (iou > l.iou_thresh)
            {
                int class_id = state.truth[t * l.truth_size + b * l.truths + 4];
                if (l.map) class_id = l.map[class_id];
                int box_index = entry_index(l, b, mask_n * l.w * l.h + j * l.w + i, 0);
                const float class_multiplier = (l.classes_multipliers) ? l.classes_multipliers[class_id] : 1.0f;
                ious all_ious = delta_yolo_box(truth, l.output, l.biases, n, box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.delta, (2 - truth.w * truth.h), l.w * l.h, l.iou_normalizer * class_multiplier, l.iou_loss, 1, l.max_delta, state.net.rewritten_bbox, l.new_coords);
                (*state.net.total_bbox)++;
                // range is 0 <= 1
                args->tot_iou += all_ious.iou;
                args->tot_iou_loss += 1 - all_ious.iou;
                // range is -1 <= giou <= 1
                tot_giou += all_ious.giou;
                args->tot_giou_loss += 1 - all_ious.giou;
                tot_diou += all_ious.diou;
                tot_diou_loss += 1 - all_ious.diou;
                tot_ciou += all_ious.ciou;
                tot_ciou_loss += 1 - all_ious.ciou;
                int obj_index = entry_index(l, b, mask_n * l.w * l.h + j * l.w + i, 4);
                avg_obj += l.output[obj_index];
                if (l.objectness_smooth)
                {
                    float delta_obj = class_multiplier * l.obj_normalizer * (1 - l.output[obj_index]);
                    if (l.delta[obj_index] == 0) l.delta[obj_index] = delta_obj;
                }
                else l.delta[obj_index] = class_multiplier * l.obj_normalizer * (1 - l.output[obj_index]);
                int class_index = entry_index(l, b, mask_n * l.w * l.h + j * l.w + i, 4 + 1);
                delta_yolo_class(l.output, l.delta, class_index, class_id, l.classes, l.w * l.h, &avg_cat, l.focal_loss, l.label_smooth_eps, l.classes_multipliers, l.cls_normalizer);
                ++(args->count);
                ++(args->class_count);
                if (all_ious.iou > .5) recall += 1;
                if (all_ious.iou > .75) recall75 += 1;
            }
        }
    }
}

这部分是从gt出发,先将gt的中心点移到0,寻找与之iou最大的anchor best_n,再看这个anchor在不在mask_n里。如果不在,说明这个gt不归这个yolo层检测(多尺度检测嘛,一般三个yolo层,每个yolo层只负责一部分gt),进入下一步。如果在,则依次产生坐标delta(根据用的iou loss类型做了各种判断),obj delta(覆盖掉第一部分的delta值),class delta,完成forward过程。
如果开启了iou_thresh(<1),那么这个yolo层的这个grid中所有bbox都预测gt,只要bbox与gt的iou超过iou_thresh。产生delta的过程则和上面类似。
 
 
第三部分:如果开启了iou_thresh,将坐标delta平均

//第三部分:如果开启了iou_thresh,将坐标delta平均
if (l.iou_thresh < 1.0f)
{
    // averages the deltas obtained by the function: delta_yolo_box()_accumulate
    for (j = 0; j < l.h; ++j)
    {
        for (i = 0; i < l.w; ++i)
        {
            for (n = 0; n < l.n; ++n)
            {
                int obj_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4);
                int box_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 0);
                int class_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4 + 1);
                const int stride = l.w*l.h;
                if (l.delta[obj_index] != 0)
                    averages_yolo_deltas(class_index, box_index, stride, l.classes, l.delta);
            }
        }
    }
}

作者对这部分逻辑做了说明(详情),可以参考着理解一下,其实就是一个bbox预测了不同gt,坐标delta就会被平均。

GPU版本

Darknet中一般每一层的forward和backward函数都有GPU版本。forward_yolo_layer的GPU版本和CPU版差不多,除了LOGISTIC激活是在GPU上做的,其实后面又调用了CPU版本,比较简单。
 
 
 
以上就是个人对forward_yolo_layer函数的一些理解,欢迎交流讨论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值