Args:
        mask_logits: #fg x #category xhxw
        fg_labels: #fg, in 1~#class, int64
        fg_target_masks: #fgxhxw, float32
164878
def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks):
    
    num_fg = tf.size(fg_labels, out_type=tf.int64)
    indices = tf.stack([tf.range(num_fg), fg_labels - 1], axis=1)  # #fgx2
    mask_logits = tf.gather_nd(mask_logits, indices)  # #fgxhxw
    mask_probs = tf.sigmoid(mask_logits)

    # add some training visualizations to tensorboard
    with tf.name_scope('mask_viz'):
        viz = tf.concat([fg_target_masks, mask_probs], axis=1)
        viz = tf.expand_dims(viz, 3)
        viz = tf.cast(viz * 255, tf.uint8, name='viz')
        tf.summary.image('mask_truth|pred', viz, max_outputs=10)

    loss = tf.nn.sigmoid_cross_entropy_with_logits(
        labels=fg_target_masks, logits=mask_logits)
    loss = tf.reduce_mean(loss, name='maskrcnn_loss')

    pred_label = mask_probs > 0.5
    truth_label = fg_target_masks > 0.5
    accuracy = tf.reduce_mean(
        tf.cast(tf.equal(pred_label, truth_label), tf.float32),
        name='accuracy')
    pos_accuracy = tf.logical_and(
        tf.equal(pred_label, truth_label),
        tf.equal(truth_label, True))
    pos_accuracy = tf.reduce_mean(tf.cast(pos_accuracy, tf.float32), name='pos_accuracy')
    fg_pixel_ratio = tf.reduce_mean(tf.cast(truth_label, tf.float32), name='fg_pixel_ratio')

    add_moving_summary(loss, accuracy, fg_pixel_ratio, pos_accuracy)
    return loss
387196
def iMath_propagate_labels_through_mask(image, labels, stopping_value=100, propagation_method=0):
    
    return iMath(image, 'PropagateLabelsThroughMask', labels, stopping_value, propagation_method)
1208581
def label_for_lm(self, **kwargs):
        ""
        self.__class__ = LMTextList
        kwargs['label_cls'] = LMLabelList
        return self.label_const(0, **kwargs)
1331395
def getMaskArray(self, signature):
        
        if signature in self.masklist:
            mask =  self.masklist[signature]
        else:
            mask = None
        return mask
740592
function(mask) {
        var borders = ['border-top','border-right', 'border-bottom', 'border-left'];
        var res = {};
        for (var i = 0; i < 4; i++) {
            if (!(mask & bin(i))) res[borders[i]] = 'none';
        }
        return res;
    }
1289590
def pad_with_zeros(logits, labels):
  """"""
  with tf.name_scope("pad_with_zeros", values=[logits, labels]):
    logits, labels = pad_to_same_length(logits, labels)
    if len(labels.shape) == 3:  # 2-d labels.
      logits, labels = pad_to_same_length(logits, labels, axis=2)
    return logits, labels
248270
def ConvBPDNMaskOptionsDefaults(method='admm'):
    

    dflt = copy.deepcopy(cbpdnmsk_class_label_lookup(method).Options.defaults)
    if method == 'admm':
        dflt.update({'MaxMainIter': 1, 'AutoRho':
                     {'Period': 10, 'AutoScaling': False,
                      'RsdlRatio': 10.0, 'Scaling': 2.0,
                      'RsdlTarget': 1.0}})
    else:
        dflt.update({'MaxMainIter': 1, 'BackTrack':
                     {'gamma_u': 1.2, 'MaxIter': 50}})
    return dflt
911155
def _apply_mask(
    data: np.ndarray,
    encoded_fill_values: list,
    decoded_fill_value: Any,
    dtype: Any,
) -> np.ndarray:
    """"""
    data = np.asarray(data, dtype=dtype)
    condition = False
    for fv in encoded_fill_values:
        condition |= data == fv
    return np.where(condition, decoded_fill_value, data)
932156
def set_to_numa_nodemask(mask):
    
    result = nodemask_t()
    __nodemask_zero(result)

    for i in range(0, get_max_node() + 1):
        if i in mask:
            __nodemask_set(result, i)

    return result
574854
def create_masked_lm_predictions(tokens, masked_lm_prob,
                                 max_predictions_per_seq, vocab_words, rng):
    """"""

    cand_indexes = []
    for (i, token) in enumerate(tokens):
        if token in ['[CLS]', '[SEP]']:
            continue
        cand_indexes.append(i)

    rng.shuffle(cand_indexes)

    output_tokens = list(tokens)

    num_to_predict = min(max_predictions_per_seq,
                         max(1, int(round(len(tokens) * masked_lm_prob))))

    masked_lms = []
    covered_indexes = set()
    for index in cand_indexes:
        if len(masked_lms) >= num_to_predict:
            break
        if index in covered_indexes:
            continue
        covered_indexes.add(index)

        masked_token = None
        # 80% of the time, replace with [MASK]
        if rng.random() < 0.8:
            masked_token = '[MASK]'
        else:
            # 10% of the time, keep original
            if rng.random() < 0.5:
                masked_token = tokens[index]
            # 10% of the time, replace with random word
            else:
                masked_token = vocab_words[rng.randint(0,
                                                       len(vocab_words) - 1)]

        output_tokens[index] = masked_token

        masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))

    masked_lms = sorted(masked_lms, key=lambda x: x.index)

    masked_lm_positions = []
    masked_lm_labels = []
    for p in masked_lms:
        masked_lm_positions.append(p.index)
        masked_lm_labels.append(p.label)

    return (output_tokens, masked_lm_positions, masked_lm_labels)
789787
def do_kpl_set_on_mask(self, args):
        
        params = args.split()
        address = None
        group = None
        mask_string = None
        mask = None

        try:
            address = params[0]
            group = int(params[1])
            mask_string = params[2]
            if mask_string[0:2].lower() == '0x':
                mask = binascii.unhexlify(mask_string[2:])
            else:
                mask = int(mask_string)
        except IndexError:
            _LOGGING.error("Address, group and mask are regquired")
            self.do_help('kpl_status')
        except TypeError:
            _LOGGING.error("Group must be an integer")
            self.do_help('kpl_status')

        if address and group and mask:
            self.tools.kpl_set_on_mask(address, group, mask)
573226
def same_label_mask(y, y2):
    
    return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32)
717866
def class_logit(layer, label):
  
  def inner(T):
    if isinstance(label, int):
      class_n = label
    else:
      class_n = T("labels").index(label)
    logits = T(layer)
    logit = tf.reduce_sum(logits[:, class_n])
    return logit
  return inner
114218
def set_on_mask(self, mask):
        """"""
        set_cmd = self._create_set_property_msg('_on_mask', 0x02, mask)
        self._send_method(set_cmd, self._property_set)
229504
def keep_negative_mask(X, y, model_generator, method_name, num_fcounts=11):
    
    return __run_measure(measures.keep_mask, X, y, model_generator, method_name, -1, num_fcounts, __mean_pred)
469460
def xloss(logits, labels, ignore=None):
    
    return F.cross_entropy(logits, Variable(labels), ignore_index=255)
178857
def lovasz_hinge_flat(logits, labels):
    
    if len(labels) == 0:
        # only void pixels, the gradients should be 0
        return logits.sum() * 0.
    signs = 2. * labels.float() - 1.
    errors = (1. - logits * Variable(signs))
    errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
    perm = perm.data
    gt_sorted = labels[perm]
    grad = lovasz_grad(gt_sorted)
    loss = torch.dot(F.elu(errors_sorted)+1, Variable(grad))
    #loss = torch.dot(F.relu(errors_sorted), Variable(grad))
    
    return loss