def nms(input_scores, input_boxes, threshold=0.7, numDetections=300, score_threshold=None, debugContext=''): load_lib() input_scores = input_scores.cast('FLOAT') input_boxes = input_boxes.cast('FLOAT') valid_area_mask = bF.transpose(get_valid_area_mask(input_boxes), [1, 0]) # 1,n input_scores = input_scores + 1e-6 # if score==0, proposals will be ignored local_input_scores = bF.identity(input_scores * valid_area_mask, debugContext=debugContext).detach() local_input_boxes = bF.identity(input_boxes, debugContext=debugContext).detach() if local_input_scores.shape.ndims == 1: local_input_scores = local_input_scores.unsqueeze(0) if local_input_boxes.shape.ndims == 2: local_input_boxes = local_input_boxes.unsqueeze(0) assert local_input_boxes.pureShape[0] == 1, 'only implemented batch=1' if score_threshold is not None: assert isinstance(score_threshold, float) local_mask = bF.greater( local_input_scores, bF.to_tensor(score_threshold, dtype=local_input_scores.dtype)) local_mask = bF.cast(local_mask, target_type=local_input_scores.dtype) local_input_scores = local_input_scores * local_mask with bF.name_scope("nms"): out = bF.get_builder().customOp(opName="nms", opVersion=1, domain="ai.graphcore", inputs=[ local_input_scores.getIpuIndex(), local_input_boxes.getIpuIndex() ], attributes={ "threshold": threshold, "numDetections": numDetections }, numOutputs=3, name="nmsCustomOp") # _, output_boxes, output_keep = out[0], bF.TTensor(out[1]), bF.TTensor( out[2]) targetType = input_scores.dtype roiKeeps_flag = bF.cast(bF.greater( output_keep, bF.constant(np.asarray(-1, dtype=np.int32))), target_type='INT32') num_valids = bF.reduceSum(roiKeeps_flag, axes=[1]) roiKeeps_flag = bF.cast(roiKeeps_flag, target_type=targetType) roiKeeps_flag = bF.unsqueeze(roiKeeps_flag, [-1]) output_boxes = bF.mul([output_boxes, roiKeeps_flag]) return output_boxes, output_keep, num_valids
def roi_align(bottom_data, bottom_rois, spatial_scale=1 / 16.0, num_rois=300, aligned_height=7, aligned_width=7, fp16_on=None): """roi_align implements.""" load_lib() assert isinstance(aligned_height, int) and isinstance( aligned_width, int), 'they should be int or IndexError: map::at will raised' cast_flag, bottom_data, fp16_on = bF.deduce_half(bottom_data, fp16_on) if fp16_on: bottom_rois = bottom_rois.cast('FLOAT16') else: bottom_rois = bottom_rois.cast('FLOAT') if fp16_on: raise NotImplementedError('maybe not implemented') # same as detectron2 roi_align version2(aligned=True and sampling_ratio=1) batch_size, channels, height, width = bottom_data.pureShape with bF.name_scope("roiAlign"): out = bF.get_builder().customOp( opName="roiAlign", opVersion=1, domain="ai.graphcore", inputs=[bottom_data.getIpuIndex(), bottom_rois.getIpuIndex()], attributes={ "spatial_scale": spatial_scale, "batch_size": batch_size, "num_rois": num_rois, "height": height, "width": width, "channels": channels, "aligned_height": aligned_height, "aligned_width": aligned_width }, numOutputs=1) result = bF.TTensor(out[0]) if cast_flag: result = result.cast(cast_flag) return result
def random_shuffle(x, seed=None, debugPrefix=""): if seed is not None: raise RuntimeError( 'random seed is globally set by session.setRandomSeed') with bF.name_scope(debugPrefix): x = bF.cast(x, 'FLOAT') seeds = bF.randomuniformlike(x, high=6.0, low=-6.0) flatten_seeds = bF.flatten(seeds) flatten_seeds_shape = flatten_seeds.pureShape _K = bF.constant(np.asarray([flatten_seeds_shape[0]]).astype(np.int64)) _, shuffle_indices = bF.topk(flatten_seeds, _K, dim=0) flatten_x = bF.flatten(x) shuffle_indices = bF.cast(shuffle_indices, 'INT32') shuffled_flatten_x = bF.gather( flatten_x, shuffle_indices, dim=0, ) x_shape = x.pureShape target_shape = bF.constant(np.asarray(x_shape).astype(np.int64)) shuffled_x = bF.reshape(shuffled_flatten_x, target_shape) return shuffled_x
def batch_norm(x, train=False, fp16_on=None, weights={ 'mean': None, 'var': None, 'scale': None, 'bias': None }, momentum=0.9, epsilon=1e-5, debugPrefix="bn"): cast_flag, x, fp16_on = bF.deduce_half(x, fp16_on) batch, c_in, height, width = x.pureShape dst_type = bF.mappin_gc2npy[x.dtype] mean = np.zeros(c_in).astype( dst_type) if weights['mean'] is None else weights['mean'] var = np.ones(c_in).astype( dst_type) if weights['var'] is None else weights['var'] scale = np.ones(c_in).astype( dst_type) if weights['scale'] is None else weights['scale'] bias = np.zeros(c_in).astype( dst_type) if weights['bias'] is None else weights['bias'] with bF.name_scope(debugPrefix): mean = temporary_init_weights(mean, "running_mean", train, fp16_on=fp16_on) var = temporary_init_weights(var, "running_var", train, fp16_on=fp16_on) scale = temporary_init_weights(scale, "weight", train, fp16_on=fp16_on) bias = temporary_init_weights(bias, "bias", train, fp16_on=fp16_on) if train: result = bF._batchNorm(x, scale, bias, mean, var, 5 if train else 1, momentum=momentum, epsilon=epsilon, debugContext='') else: mean = mean.unsqueeze(-1).unsqueeze(-1).unsqueeze(0) var = var.unsqueeze(-1).unsqueeze(-1).unsqueeze(0) scale = scale.unsqueeze(-1).unsqueeze(-1).unsqueeze(0) bias = bias.unsqueeze(-1).unsqueeze(-1).unsqueeze(0) eps = np.asarray(1e-6).astype( np.float16 if fp16_on else np.float32) result = (x - mean) / bF.sqrt(var + eps) * scale + bias results = [result, mean, var, mean, var] if cast_flag: results = [result.cast(cast_flag) for result in results] return results
def name_scope(scope_name): return bF.name_scope(scope_name)