def lovasz_grad(gt_sorted):
    """
    Computes gradient of the Lovasz extension w.r.t sorted errors.
    See Alg. 1 in paper.
    """
    gts = paddle.sum(gt_sorted)
    p = len(gt_sorted)

    intersection = gts - paddle.cumsum(gt_sorted, axis=0)
    union = gts + paddle.cumsum(1 - gt_sorted, axis=0)
    jaccard = 1.0 - intersection.cast('float32') / union.cast('float32')

    if p > 1:  # cover 1-pixel case
        jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
    return jaccard

    Computes gradient of the Lovasz extension w.r.t sorted errors.
    See Alg. 1 in paper.
    
paddleseg/models/losses/lovasz_loss.py