project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
openvinotoolkit/training_extensions | torchvision2mmdet.py | ColorJitter.forward | forward | Forward function of ColorJitter. | [
"Forward",
"function",
"of",
"ColorJitter."
] | def forward(self, img):
outputs = img.copy()
for key_map in self.key_maps:
outputs[key_map[0]] = super().forward(img[key_map[1]])
return outputs | ['def', 'forward(self,', 'img):', 'outputs', '=', 'img.copy()', 'for', 'key_map', 'in', 'self.key_maps:', 'outputs[key_map[0]]', '=', 'super().forward(img[key_map[1]])', 'return', 'outputs'] | 918,076 |
openvinotoolkit/training_extensions | torchvision2mmdet.py | RandomGrayscale.forward | forward | Forward function of RandomGrayscale. | [
"Forward",
"function",
"of",
"RandomGrayscale."
] | def forward(self, img):
outputs = img.copy()
for key_map in self.key_maps:
outputs[key_map[0]] = super().forward(img[key_map[1]])
return outputs | ['def', 'forward(self,', 'img):', 'outputs', '=', 'img.copy()', 'for', 'key_map', 'in', 'self.key_maps:', 'outputs[key_map[0]]', '=', 'super().forward(img[key_map[1]])', 'return', 'outputs'] | 918,077 |
openvinotoolkit/training_extensions | evaluator.py | sanitize_coordinates | sanitize_coordinates | Sanitize coordinates of bounding boxes so that they fit within the image. | [
"Sanitize",
"coordinates",
"of",
"bounding",
"boxes",
"so",
"that",
"they",
"fit",
"within",
"the",
"image."
] | def sanitize_coordinates(bbox: np.ndarray, height: int, width: int, padding=1) -> np.ndarray:
(x1, y1, x2, y2) = bbox.astype(np.int)
x1 = max(0, x1 - padding)
y1 = max(0, y1 - padding)
x2 = min(width, x2 + padding)
y2 = min(height, y2 + padding)
return np.array([x1, y1, x2, y2]) | ['def', 'sanitize_coordinates(bbox:', 'np.ndarray,', 'height:', 'int,', 'width:', 'int,', 'padding=1)', '->', 'np.ndarray:', '(x1,', 'y1,', 'x2,', 'y2)', '=', 'bbox.astype(np.int)', 'x1', '=', 'max(0,', 'x1', '-', 'padding)', 'y1', '=', 'max(0,', 'y1', '-', 'padding)', 'x2', '=', 'min(width,', 'x2', '+', 'padding)', 'y... | 918,080 |
openvinotoolkit/training_extensions | evaluator.py | mask_iou | mask_iou | Compute the intersection over union between the detected masks and ground truth masks. | [
"Compute",
"the",
"intersection",
"over",
"union",
"between",
"the",
"detected",
"masks",
"and",
"ground",
"truth",
"masks."
] | def mask_iou(det: Tuple[np.ndarray, BitmapMasks], gt_masks: PolygonMasks, iou_thr: float) -> np.ndarray:
(det_bboxes, det_masks) = det
gt_bboxes = gt_masks.get_bboxes()
(img_h, img_w) = (gt_masks.height, gt_masks.width)
ious = bbox_overlaps(det_bboxes, gt_bboxes, mode='iou')
ious[ious < iou_thr] = 0... | ['def', 'mask_iou(det:', 'Tuple[np.ndarray,', 'BitmapMasks],', 'gt_masks:', 'PolygonMasks,', 'iou_thr:', 'float)', '->', 'np.ndarray:', '(det_bboxes,', 'det_masks)', '=', 'det', 'gt_bboxes', '=', 'gt_masks.get_bboxes()', '(img_h,', 'img_w)', '=', '(gt_masks.height,', 'gt_masks.width)', 'ious', '=', 'bbox_overlaps(det_b... | 918,081 |
openvinotoolkit/training_extensions | evaluator.py | tpfpmiou_func | tpfpmiou_func | Compute tp, fp, miou for each image. | [
"Compute",
"tp,",
"fp,",
"miou",
"for",
"each",
"image."
] | def tpfpmiou_func(det: Tuple[np.ndarray, Union[BitmapMasks, List]], gt_masks: PolygonMasks, cls_scores, iou_thr=0.5):
num_dets = len(det[0])
num_gts = len(gt_masks)
tp = np.zeros(num_dets, dtype=np.float32)
fp = np.zeros(num_dets, dtype=np.float32)
gt_covered_iou = np.zeros(num_gts, dtype=np.float32... | ['def', 'tpfpmiou_func(det:', 'Tuple[np.ndarray,', 'Union[BitmapMasks,', 'List]],', 'gt_masks:', 'PolygonMasks,', 'cls_scores,', 'iou_thr=0.5):', 'num_dets', '=', 'len(det[0])', 'num_gts', '=', 'len(gt_masks)', 'tp', '=', 'np.zeros(num_dets,', 'dtype=np.float32)', 'fp', '=', 'np.zeros(num_dets,', 'dtype=np.float32)', '... | 918,082 |
openvinotoolkit/training_extensions | evaluator.py | Evaluator.get_gt_instance_masks | get_gt_instance_masks | Format ground truth instance mask annotation. | [
"Format",
"ground",
"truth",
"instance",
"mask",
"annotation."
] | def get_gt_instance_masks(self, annotation: List[Dict]):
cls_anno_list: List[List] = [[] for _ in range(self.num_classes)]
for class_id in range(self.num_classes):
for ann in annotation:
gt_inds = ann['labels'] == class_id
polygon_masks = []
if gt_inds.any():
... | ['def', 'get_gt_instance_masks(self,', 'annotation:', 'List[Dict]):', 'cls_anno_list:', 'List[List]', '=', '[[]', 'for', '_', 'in', 'range(self.num_classes)]', 'for', 'class_id', 'in', 'range(self.num_classes):', 'for', 'ann', 'in', 'annotation:', 'gt_inds', '=', "ann['labels']", '==', 'class_id', 'polygon_masks', '=',... | 918,083 |
openvinotoolkit/training_extensions | evaluator.py | Evaluator.get_mask_det_results | get_mask_det_results | Get mask detection results for a specific class. | [
"Get",
"mask",
"detection",
"results",
"for",
"a",
"specific",
"class."
] | def get_mask_det_results(self, det_results: List[Tuple], class_id: int) -> Tuple[List, List]:
cls_scores = [img_res[0][class_id][..., -1] for img_res in det_results]
cls_dets: List[Tuple] = []
for det in det_results:
det_bboxes = det[0][class_id][:, :4]
det_masks = det[1][class_id]
i... | ['def', 'get_mask_det_results(self,', 'det_results:', 'List[Tuple],', 'class_id:', 'int)', '->', 'Tuple[List,', 'List]:', 'cls_scores', '=', '[img_res[0][class_id][...,', '-1]', 'for', 'img_res', 'in', 'det_results]', 'cls_dets:', 'List[Tuple]', '=', '[]', 'for', 'det', 'in', 'det_results:', 'det_bboxes', '=', 'det[0][... | 918,084 |
openvinotoolkit/training_extensions | loss_dyns.py | LossAccumulator.add | add | Add loss value to itself. | [
"Add",
"loss",
"value",
"to",
"itself."
] | def add(self, value):
if isinstance(value, float):
self.sum += value
self.cnt += 1
elif isinstance(value, LossAccumulator):
self.sum += value.sum
self.cnt += value.cnt
else:
raise NotImplementedError() | ['def', 'add(self,', 'value):', 'if', 'isinstance(value,', 'float):', 'self.sum', '+=', 'value', 'self.cnt', '+=', '1', 'elif', 'isinstance(value,', 'LossAccumulator):', 'self.sum', '+=', 'value.sum', 'self.cnt', '+=', 'value.cnt', 'else:', 'raise', 'NotImplementedError()'] | 918,088 |
openvinotoolkit/training_extensions | loss_dyns.py | LossAccumulator.mean | mean | Obtain mean from the accumulated values. | [
"Obtain",
"mean",
"from",
"the",
"accumulated",
"values."
] | def mean(self):
if self.cnt == 0:
return 0.0
return self.sum / self.cnt | ['def', 'mean(self):', 'if', 'self.cnt', '==', '0:', 'return', '0.0', 'return', 'self.sum', '/', 'self.cnt'] | 918,089 |
openvinotoolkit/training_extensions | mmov_backbone.py | MMOVBackbone.forward | forward | Forward function of MMOVBackbone. | [
"Forward",
"function",
"of",
"MMOVBackbone."
] | def forward(self, *args, **kwargs):
outputs = super().forward(*args, **kwargs)
if not isinstance(outputs, tuple):
outputs = (outputs,)
return outputs | ['def', 'forward(self,', '*args,', '**kwargs):', 'outputs', '=', 'super().forward(*args,', '**kwargs)', 'if', 'not', 'isinstance(outputs,', 'tuple):', 'outputs', '=', '(outputs,)', 'return', 'outputs'] | 918,095 |
openvinotoolkit/training_extensions | mmov_backbone.py | MMOVBackbone.init_weights | init_weights | Initial weights function of MMOVBackbone. | [
"Initial",
"weights",
"function",
"of",
"MMOVBackbone."
] | def init_weights(self, pretrained=None):
return | ['def', 'init_weights(self,', 'pretrained=None):', 'return'] | 918,096 |
openvinotoolkit/training_extensions | mmov_rpn_head.py | MMOVRPNHead.init_weights | init_weights | Initial weight function of MMOVRPNHead. | [
"Initial",
"weight",
"function",
"of",
"MMOVRPNHead."
] | def init_weights(self):
return | ['def', 'init_weights(self):', 'return'] | 918,097 |
openvinotoolkit/training_extensions | mmov_rpn_head.py | MMOVRPNHead.forward_single | forward_single | Forward funtion for MMOVRPNHead. | [
"Forward",
"funtion",
"for",
"MMOVRPNHead."
] | def forward_single(self, x):
(rpn_cls_score, rpn_bbox_pred) = self.model(x)
if self._transpose_reg:
shape = rpn_bbox_pred.shape
rpn_bbox_pred = rpn_bbox_pred.reshape(shape[0], 4, -1, *shape[2:]).transpose(1, 2).reshape(shape)
if self._transpose_cls:
shape = rpn_cls_score.shape
... | ['def', 'forward_single(self,', 'x):', '(rpn_cls_score,', 'rpn_bbox_pred)', '=', 'self.model(x)', 'if', 'self._transpose_reg:', 'shape', '=', 'rpn_bbox_pred.shape', 'rpn_bbox_pred', '=', 'rpn_bbox_pred.reshape(shape[0],', '4,', '-1,', '*shape[2:]).transpose(1,', '2).reshape(shape)', 'if', 'self._transpose_cls:', 'shape... | 918,098 |
openvinotoolkit/training_extensions | mmov_yolov3_head.py | MMOVYOLOV3Head.init_weights | init_weights | Initialize weights of MMOVYOLOV3Head. | [
"Initialize",
"weights",
"of",
"MMOVYOLOV3Head."
] | def init_weights(self):
return | ['def', 'init_weights(self):', 'return'] | 918,101 |
openvinotoolkit/training_extensions | custom_atss_detector.py | custom_atss__forward | custom_atss__forward | Internal Function for __forward for CustomATSS. | [
"Internal",
"Function",
"for",
"__forward",
"for",
"CustomATSS."
] | def custom_atss__forward(ctx, self, img, img_metas=None, return_loss=False, **kwargs):
if img_metas is None:
img_metas = [{}]
else:
assert len(img_metas) == 1, 'do not support aug_test'
img_metas = img_metas[0]
if isinstance(img, list):
img = img[0]
return __forward_impl(... | ['def', 'custom_atss__forward(ctx,', 'self,', 'img,', 'img_metas=None,', 'return_loss=False,', '**kwargs):', 'if', 'img_metas', 'is', 'None:', 'img_metas', '=', '[{}]', 'else:', 'assert', 'len(img_metas)', '==', '1,', "'do", 'not', 'support', "aug_test'", 'img_metas', '=', 'img_metas[0]', 'if', 'isinstance(img,', 'list... | 918,102 |
openvinotoolkit/training_extensions | custom_atss_detector.py | CustomATSS.load_state_dict_pre_hook | load_state_dict_pre_hook | Modify input state_dict according to class name matching before weight loading. | [
"Modify",
"input",
"state_dict",
"according",
"to",
"class",
"name",
"matching",
"before",
"weight",
"loading."
] | def load_state_dict_pre_hook(model, model_classes, chkpt_classes, chkpt_dict, prefix, *args, **kwargs):
logger.info(f'----------------- CustomATSS.load_state_dict_pre_hook() called w/ prefix: {prefix}')
model_classes = list(model_classes)
chkpt_classes = list(chkpt_classes)
model2chkpt = map_class_names... | ['def', 'load_state_dict_pre_hook(model,', 'model_classes,', 'chkpt_classes,', 'chkpt_dict,', 'prefix,', '*args,', '**kwargs):', "logger.info(f'-----------------", 'CustomATSS.load_state_dict_pre_hook()', 'called', 'w/', 'prefix:', "{prefix}')", 'model_classes', '=', 'list(model_classes)', 'chkpt_classes', '=', 'list(c... | 918,103 |
openvinotoolkit/training_extensions | custom_single_stage_detector.py | CustomSingleStageDetector.forward_train | forward_train | Forward function for CustomSSD. | [
"Forward",
"function",
"for",
"CustomSSD."
] | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, **kwargs):
batch_input_shape = tuple(img[0].size()[-2:])
for img_meta in img_metas:
img_meta['batch_input_shape'] = batch_input_shape
x = self.extract_feat(img)
losses = self.bbox_head.forward_train(x, img_metas... | ['def', 'forward_train(self,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=None,', '**kwargs):', 'batch_input_shape', '=', 'tuple(img[0].size()[-2:])', 'for', 'img_meta', 'in', 'img_metas:', "img_meta['batch_input_shape']", '=', 'batch_input_shape', 'x', '=', 'self.extract_feat(img)', 'losses', ... | 918,117 |
openvinotoolkit/training_extensions | custom_two_stage_detector.py | CustomTwoStageDetector.forward_train | forward_train | Forward function for CustomTwoStageDetector. | [
"Forward",
"function",
"for",
"CustomTwoStageDetector."
] | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, **kwargs):
return super().forward_train(img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=gt_bboxes_ignore) | ['def', 'forward_train(self,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=None,', '**kwargs):', 'return', 'super().forward_train(img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=gt_bboxes_ignore)'] | 918,119 |
openvinotoolkit/training_extensions | custom_yolox_detector.py | CustomYOLOX.forward_train | forward_train | Forward function for CustomYOLOX. | [
"Forward",
"function",
"for",
"CustomYOLOX."
] | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, **kwargs):
return super().forward_train(img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=gt_bboxes_ignore) | ['def', 'forward_train(self,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=None,', '**kwargs):', 'return', 'super().forward_train(img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=gt_bboxes_ignore)'] | 918,124 |
openvinotoolkit/training_extensions | l2sp_detector_mixin.py | L2SPDetectorMixin.forward_train | forward_train | Forward function for L2SPDetectorMixin. | [
"Forward",
"function",
"for",
"L2SPDetectorMixin."
] | def forward_train(self, *args, **kwargs):
losses = super().forward_train(*args, **kwargs)
if self.l2sp:
losses.update(dict(loss_l2sp=self.l2sp()))
return losses | ['def', 'forward_train(self,', '*args,', '**kwargs):', 'losses', '=', 'super().forward_train(*args,', '**kwargs)', 'if', 'self.l2sp:', 'losses.update(dict(loss_l2sp=self.l2sp()))', 'return', 'losses'] | 918,127 |
openvinotoolkit/training_extensions | loss_dynamics_mixin.py | DetLossDynamicsTracker.init_with_otx_dataset | init_with_otx_dataset | DatasetEntity should be injected to the tracker for the initialization. | [
"DatasetEntity",
"should",
"be",
"injected",
"to",
"the",
"tracker",
"for",
"the",
"initialization."
] | def init_with_otx_dataset(self, otx_dataset: DatasetEntity[DatasetItemEntityWithID]) -> None:
self.otx_ann_id_to_dm_ann_map: Dict[Tuple[str, str], dm.Bbox] = {}
super().init_with_otx_dataset(otx_dataset) | ['def', 'init_with_otx_dataset(self,', 'otx_dataset:', 'DatasetEntity[DatasetItemEntityWithID])', '->', 'None:', 'self.otx_ann_id_to_dm_ann_map:', 'Dict[Tuple[str,', 'str],', 'dm.Bbox]', '=', '{}', 'super().init_with_otx_dataset(otx_dataset)'] | 918,128 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.extract_feat | extract_feat | Extract features for UnbiasedTeacher. | [
"Extract",
"features",
"for",
"UnbiasedTeacher."
] | def extract_feat(self, imgs):
return self.model_s.extract_feat(imgs) | ['def', 'extract_feat(self,', 'imgs):', 'return', 'self.model_s.extract_feat(imgs)'] | 918,132 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.simple_test | simple_test | Test from img with UnbiasedTeacher. | [
"Test",
"from",
"img",
"with",
"UnbiasedTeacher."
] | def simple_test(self, img, img_metas, **kwargs):
return self.model_s.simple_test(img, img_metas, **kwargs) | ['def', 'simple_test(self,', 'img,', 'img_metas,', '**kwargs):', 'return', 'self.model_s.simple_test(img,', 'img_metas,', '**kwargs)'] | 918,133 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.aug_test | aug_test | Aug Test from img with UnbiasedTeacher. | [
"Aug",
"Test",
"from",
"img",
"with",
"UnbiasedTeacher."
] | def aug_test(self, imgs, img_metas, **kwargs):
return self.model_s.aug_test(imgs, img_metas, **kwargs) | ['def', 'aug_test(self,', 'imgs,', 'img_metas,', '**kwargs):', 'return', 'self.model_s.aug_test(imgs,', 'img_metas,', '**kwargs)'] | 918,134 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.enable_unlabeled_loss | enable_unlabeled_loss | Enable function for UnbiasedTeacher unlabeled loss. | [
"Enable",
"function",
"for",
"UnbiasedTeacher",
"unlabeled",
"loss."
] | def enable_unlabeled_loss(self, mode=True):
self.unlabeled_loss_enabled = mode | ['def', 'enable_unlabeled_loss(self,', 'mode=True):', 'self.unlabeled_loss_enabled', '=', 'mode'] | 918,136 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.forward_teacher | forward_teacher | Method to extract predictions (pseudo labeles) from teacher. | [
"Method",
"to",
"extract",
"predictions",
"(pseudo",
"labeles)",
"from",
"teacher."
] | def forward_teacher(self, img, img_metas):
x = self.model_t.extract_feat(img)
proposal_list = self.model_t.rpn_head.simple_test_rpn(x, img_metas)
(det_bboxes, det_labels) = self.model_t.roi_head.simple_test_bboxes(x, img_metas, proposal_list, self.model_t.test_cfg.rcnn, rescale=False)
bbox_results = [bb... | ['def', 'forward_teacher(self,', 'img,', 'img_metas):', 'x', '=', 'self.model_t.extract_feat(img)', 'proposal_list', '=', 'self.model_t.rpn_head.simple_test_rpn(x,', 'img_metas)', '(det_bboxes,', 'det_labels)', '=', 'self.model_t.roi_head.simple_test_bboxes(x,', 'img_metas,', 'proposal_list,', 'self.model_t.test_cfg.rc... | 918,137 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.forward_train | forward_train | Forward function for UnbiasedTeacher. | [
"Forward",
"function",
"for",
"UnbiasedTeacher."
] | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_masks=None, gt_bboxes_ignore=None, **kwargs):
losses = {}
forward_train = functools.partial(self.model_s.forward_train, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=gt_bboxes_ignore if gt_bboxes_ignore else None)
if self.model_s.with... | ['def', 'forward_train(self,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_masks=None,', 'gt_bboxes_ignore=None,', '**kwargs):', 'losses', '=', '{}', 'forward_train', '=', 'functools.partial(self.model_s.forward_train,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=gt_bboxes_ignore', 'i... | 918,138 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.generate_pseudo_labels | generate_pseudo_labels | Generate pseudo label for UnbiasedTeacher. | [
"Generate",
"pseudo",
"label",
"for",
"UnbiasedTeacher."
] | def generate_pseudo_labels(self, teacher_outputs, img_meta, **kwargs):
device = kwargs.pop('device')
all_pseudo_bboxes = []
all_pseudo_labels = []
all_pseudo_masks = []
num_all_bboxes = 0
num_all_pseudo = 0
for (i, teacher_bboxes_labels) in enumerate(teacher_outputs):
image_shape = i... | ['def', 'generate_pseudo_labels(self,', 'teacher_outputs,', 'img_meta,', '**kwargs):', 'device', '=', "kwargs.pop('device')", 'all_pseudo_bboxes', '=', '[]', 'all_pseudo_labels', '=', '[]', 'all_pseudo_masks', '=', '[]', 'num_all_bboxes', '=', '0', 'num_all_pseudo', '=', '0', 'for', '(i,', 'teacher_bboxes_labels)', 'in... | 918,139 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.state_dict_hook | state_dict_hook | Redirect student model as output state_dict (teacher as auxilliary). | [
"Redirect",
"student",
"model",
"as",
"output",
"state_dict",
"(teacher",
"as",
"auxilliary)."
] | def state_dict_hook(module, state_dict, prefix, *args, **kwargs):
logger.info('----------------- MeanTeacherSegmentor.state_dict_hook() called')
for key in list(state_dict.keys()):
value = state_dict.pop(key)
if not prefix or key.startswith(prefix):
key = key.replace(prefix, '', 1)
... | ['def', 'state_dict_hook(module,', 'state_dict,', 'prefix,', '*args,', '**kwargs):', "logger.info('-----------------", 'MeanTeacherSegmentor.state_dict_hook()', "called')", 'for', 'key', 'in', 'list(state_dict.keys()):', 'value', '=', 'state_dict.pop(key)', 'if', 'not', 'prefix', 'or', 'key.startswith(prefix):', 'key',... | 918,140 |
openvinotoolkit/training_extensions | mean_teacher.py | MeanTeacher.load_state_dict_pre_hook | load_state_dict_pre_hook | Redirect input state_dict to teacher model. | [
"Redirect",
"input",
"state_dict",
"to",
"teacher",
"model."
] | def load_state_dict_pre_hook(module, state_dict, *args, **kwargs):
logger.info('----------------- MeanTeacherSegmentor.load_state_dict_pre_hook() called')
for key in list(state_dict.keys()):
value = state_dict.pop(key)
state_dict['model_s.' + key] = value
state_dict['model_t.' + key] = v... | ['def', 'load_state_dict_pre_hook(module,', 'state_dict,', '*args,', '**kwargs):', "logger.info('-----------------", 'MeanTeacherSegmentor.load_state_dict_pre_hook()', "called')", 'for', 'key', 'in', 'list(state_dict.keys()):', 'value', '=', 'state_dict.pop(key)', "state_dict['model_s.'", '+', 'key]', '=', 'value', "st... | 918,141 |
openvinotoolkit/training_extensions | custom_anchor_generator.py | SSDAnchorGeneratorClustered.gen_base_anchors | gen_base_anchors | Generate base anchor for SSD. | [
"Generate",
"base",
"anchor",
"for",
"SSD."
] | def gen_base_anchors(self):
multi_level_base_anchors = []
for (widths, heights, centers) in zip(self.widths, self.heights, self.centers):
base_anchors = self.gen_single_level_base_anchors(ws=torch.Tensor(widths), hs=torch.Tensor(heights), center=torch.Tensor(centers))
multi_level_base_anchors.ap... | ['def', 'gen_base_anchors(self):', 'multi_level_base_anchors', '=', '[]', 'for', '(widths,', 'heights,', 'centers)', 'in', 'zip(self.widths,', 'self.heights,', 'self.centers):', 'base_anchors', '=', 'self.gen_single_level_base_anchors(ws=torch.Tensor(widths),', 'hs=torch.Tensor(heights),', 'center=torch.Tensor(centers)... | 918,146 |
openvinotoolkit/training_extensions | custom_anchor_generator.py | SSDAnchorGeneratorClustered.gen_single_level_base_anchors | gen_single_level_base_anchors | Generate single_level_base_anchors for SSD. | [
"Generate",
"single_level_base_anchors",
"for",
"SSD."
] | def gen_single_level_base_anchors(self, ws, hs, center):
(x_center, y_center) = center
base_anchors = [x_center - 0.5 * ws, y_center - 0.5 * hs, x_center + 0.5 * ws, y_center + 0.5 * hs]
base_anchors = torch.stack(base_anchors, dim=-1)
return base_anchors | ['def', 'gen_single_level_base_anchors(self,', 'ws,', 'hs,', 'center):', '(x_center,', 'y_center)', '=', 'center', 'base_anchors', '=', '[x_center', '-', '0.5', '*', 'ws,', 'y_center', '-', '0.5', '*', 'hs,', 'x_center', '+', '0.5', '*', 'ws,', 'y_center', '+', '0.5', '*', 'hs]', 'base_anchors', '=', 'torch.stack(base_... | 918,147 |
openvinotoolkit/training_extensions | custom_atss_head.py | CustomATSSHeadTrackingLossDynamics.get_targets | get_targets | Get targets for Detection head. | [
"Get",
"targets",
"for",
"Detection",
"head."
] | def get_targets(self, anchor_list, valid_flag_list, gt_bboxes_list, img_metas, gt_bboxes_ignore_list=None, gt_labels_list=None, label_channels=1, unmap_outputs=True):
return super().get_targets(anchor_list, valid_flag_list, gt_bboxes_list, img_metas, gt_bboxes_ignore_list, gt_labels_list, label_channels, unmap_outp... | ['def', 'get_targets(self,', 'anchor_list,', 'valid_flag_list,', 'gt_bboxes_list,', 'img_metas,', 'gt_bboxes_ignore_list=None,', 'gt_labels_list=None,', 'label_channels=1,', 'unmap_outputs=True):', 'return', 'super().get_targets(anchor_list,', 'valid_flag_list,', 'gt_bboxes_list,', 'img_metas,', 'gt_bboxes_ignore_list,... | 918,153 |
openvinotoolkit/training_extensions | detr_head.py | DETRHeadExtension.loss_by_feat_single | loss_by_feat_single | Loss function for outputs from a single decoder layer of a single feature level. | [
"Loss",
"function",
"for",
"outputs",
"from",
"a",
"single",
"decoder",
"layer",
"of",
"a",
"single",
"feature",
"level."
] | def loss_by_feat_single(self, cls_scores: Tensor, bbox_preds: Tensor, batch_gt_instances: List[Config], batch_img_metas: List[dict]) -> Tuple[Tensor, Tensor, Tensor]:
num_imgs = cls_scores.size(0)
cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
bbox_preds_list = [bbox_preds[i] for i in range(num_... | ['def', 'loss_by_feat_single(self,', 'cls_scores:', 'Tensor,', 'bbox_preds:', 'Tensor,', 'batch_gt_instances:', 'List[Config],', 'batch_img_metas:', 'List[dict])', '->', 'Tuple[Tensor,', 'Tensor,', 'Tensor]:', 'num_imgs', '=', 'cls_scores.size(0)', 'cls_scores_list', '=', '[cls_scores[i]', 'for', 'i', 'in', 'range(num_... | 918,178 |
openvinotoolkit/training_extensions | lite_detr_layers.py | SmallExpandFFN.forward_ffn | forward_ffn | Forward Feed Forward Network given layers. | [
"Forward",
"Feed",
"Forward",
"Network",
"given",
"layers."
] | def forward_ffn(self, layers, norm, x, identity=None):
out = layers(x)
if not self.add_identity:
return self.dropout_layer(out)
if identity is None:
identity = x
return norm(identity + self.dropout_layer(out)) | ['def', 'forward_ffn(self,', 'layers,', 'norm,', 'x,', 'identity=None):', 'out', '=', 'layers(x)', 'if', 'not', 'self.add_identity:', 'return', 'self.dropout_layer(out)', 'if', 'identity', 'is', 'None:', 'identity', '=', 'x', 'return', 'norm(identity', '+', 'self.dropout_layer(out))'] | 918,188 |
openvinotoolkit/training_extensions | cross_focal_loss.py | CrossSigmoidFocalLoss.forward | forward | Forward funtion of CrossSigmoidFocalLoss. | [
"Forward",
"funtion",
"of",
"CrossSigmoidFocalLoss."
] | def forward(self, pred, targets, weight=None, reduction_override=None, avg_factor=None, use_vfl=False, valid_label_mask=None, **kwargs):
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = reduction_override if reduction_override else self.reduction
loss_cls = self.loss_weight * self.cls_... | ['def', 'forward(self,', 'pred,', 'targets,', 'weight=None,', 'reduction_override=None,', 'avg_factor=None,', 'use_vfl=False,', 'valid_label_mask=None,', '**kwargs):', 'assert', 'reduction_override', 'in', '(None,', "'none',", "'mean',", "'sum')", 'reduction', '=', 'reduction_override', 'if', 'reduction_override', 'els... | 918,192 |
openvinotoolkit/training_extensions | mmov_fpn.py | MMOVFPN.init_weights | init_weights | Initial weights function of MMOVFPN. | [
"Initial",
"weights",
"function",
"of",
"MMOVFPN."
] | def init_weights(self, pretrained=None):
return | ['def', 'init_weights(self,', 'pretrained=None):', 'return'] | 918,195 |
openvinotoolkit/training_extensions | mmov_ssd_neck.py | MMOVSSDNeck.init_weights | init_weights | Initial weights of MMOVSSDNeck. | [
"Initial",
"weights",
"of",
"MMOVSSDNeck."
] | def init_weights(self, pretrained=None):
return | ['def', 'init_weights(self,', 'pretrained=None):', 'return'] | 918,196 |
openvinotoolkit/training_extensions | mmov_yolov3_neck.py | MMOVYOLOV3Neck.init_weights | init_weights | Initial weights of MMOVYOLOV3Neck. | [
"Initial",
"weights",
"of",
"MMOVYOLOV3Neck."
] | def init_weights(self, pretrained=None):
return | ['def', 'init_weights(self,', 'pretrained=None):', 'return'] | 918,197 |
openvinotoolkit/training_extensions | mmov_bbox_head.py | MMOVBBoxHead.init_weights | init_weights | Initialize weights of MMOVBBoxHead. | [
"Initialize",
"weights",
"of",
"MMOVBBoxHead."
] | def init_weights(self):
return | ['def', 'init_weights(self):', 'return'] | 918,198 |
openvinotoolkit/training_extensions | mmov_bbox_head.py | MMOVBBoxHead.forward | forward | Forward function of MMOVBBoxHead. | [
"Forward",
"function",
"of",
"MMOVBBoxHead."
] | def forward(self, x):
if getattr(self, 'extractor'):
x = self.extractor(x)
cls_score = self.fc_cls(x) if self.with_cls else None
bbox_pred = self.fc_reg(x) if self.with_reg else None
if self._background_index is not None and cls_score is not None and (self._background_index != cls_score.shape(-1... | ['def', 'forward(self,', 'x):', 'if', 'getattr(self,', "'extractor'):", 'x', '=', 'self.extractor(x)', 'cls_score', '=', 'self.fc_cls(x)', 'if', 'self.with_cls', 'else', 'None', 'bbox_pred', '=', 'self.fc_reg(x)', 'if', 'self.with_reg', 'else', 'None', 'if', 'self._background_index', 'is', 'not', 'None', 'and', 'cls_sc... | 918,199 |
openvinotoolkit/training_extensions | mmov_mask_head.py | MMOVMaskHead.init_weights | init_weights | Initial weights of MMOVMaskHead. | [
"Initial",
"weights",
"of",
"MMOVMaskHead."
] | def init_weights(self):
return | ['def', 'init_weights(self):', 'return'] | 918,200 |
openvinotoolkit/training_extensions | builder.py | build_nncf_detector | build_nncf_detector | A function to build NNCF wrapped mmdet model. | [
"A",
"function",
"to",
"build",
"NNCF",
"wrapped",
"mmdet",
"model."
] | def build_nncf_detector(config: Config, train_cfg: Optional[Union[Config, ConfigDict]]=None, test_cfg: Optional[Union[Config, ConfigDict]]=None, checkpoint: Optional[str]=None, device: Union[str, torch.device]='cpu', cfg_options: Optional[Union[Config, ConfigDict]]=None, distributed=False):
from mmdet.apis import m... | ['def', 'build_nncf_detector(config:', 'Config,', 'train_cfg:', 'Optional[Union[Config,', 'ConfigDict]]=None,', 'test_cfg:', 'Optional[Union[Config,', 'ConfigDict]]=None,', 'checkpoint:', 'Optional[str]=None,', 'device:', 'Union[str,', "torch.device]='cpu',", 'cfg_options:', 'Optional[Union[Config,', 'ConfigDict]]=None... | 918,203 |
openvinotoolkit/training_extensions | task.py | DetectionNNCFTask.configure | configure | Configure configs for nncf task. | [
"Configure",
"configs",
"for",
"nncf",
"task."
] | def configure(self, training=True, ir_options=None, train_dataset=None, export=False):
super(NNCFBaseTask, self).configure(training, ir_options, train_dataset, export)
self._prepare_optimize(export)
return self._config | ['def', 'configure(self,', 'training=True,', 'ir_options=None,', 'train_dataset=None,', 'export=False):', 'super(NNCFBaseTask,', 'self).configure(training,', 'ir_options,', 'train_dataset,', 'export)', 'self._prepare_optimize(export)', 'return', 'self._config'] | 918,204 |
openvinotoolkit/training_extensions | config_utils.py | should_cluster_anchors | should_cluster_anchors | Check whether cluster anchors or not. | [
"Check",
"whether",
"cluster",
"anchors",
"or",
"not."
] | def should_cluster_anchors(model_cfg: Config):
if hasattr(model_cfg.model, 'bbox_head') and hasattr(model_cfg.model.bbox_head, 'anchor_generator') and getattr(model_cfg.model.bbox_head.anchor_generator, 'reclustering_anchors', False):
return True
return False | ['def', 'should_cluster_anchors(model_cfg:', 'Config):', 'if', 'hasattr(model_cfg.model,', "'bbox_head')", 'and', 'hasattr(model_cfg.model.bbox_head,', "'anchor_generator')", 'and', 'getattr(model_cfg.model.bbox_head.anchor_generator,', "'reclustering_anchors',", 'False):', 'return', 'True', 'return', 'False'] | 918,206 |
openvinotoolkit/training_extensions | config_utils.py | cluster_anchors | cluster_anchors | Update configs for cluster_anchors. | [
"Update",
"configs",
"for",
"cluster_anchors."
] | def cluster_anchors(recipe_config: Config, dataset: DatasetEntity):
if not KMEANS_IMPORT:
raise ImportError('Sklearn package is not installed. To enable anchor boxes clustering, please install packages from requirements/optional.txt or just scikit-learn package.')
logger.info('Collecting statistics from... | ['def', 'cluster_anchors(recipe_config:', 'Config,', 'dataset:', 'DatasetEntity):', 'if', 'not', 'KMEANS_IMPORT:', 'raise', "ImportError('Sklearn", 'package', 'is', 'not', 'installed.', 'To', 'enable', 'anchor', 'boxes', 'clustering,', 'please', 'install', 'packages', 'from', 'requirements/optional.txt', 'or', 'just', ... | 918,207 |
openvinotoolkit/training_extensions | config_utils.py | patch_ir_scale_factor | patch_ir_scale_factor | Patch IR scale factor inplace from hyper parameters to deploy config. | [
"Patch",
"IR",
"scale",
"factor",
"inplace",
"from",
"hyper",
"parameters",
"to",
"deploy",
"config."
] | def patch_ir_scale_factor(deploy_cfg: ConfigDict, hyper_parameters: DetectionConfig):
if hyper_parameters.tiling_parameters.enable_tiling:
scale_ir_input = deploy_cfg.get('scale_ir_input', False)
if scale_ir_input:
tile_ir_scale_factor = hyper_parameters.tiling_parameters.tile_ir_scale_f... | ['def', 'patch_ir_scale_factor(deploy_cfg:', 'ConfigDict,', 'hyper_parameters:', 'DetectionConfig):', 'if', 'hyper_parameters.tiling_parameters.enable_tiling:', 'scale_ir_input', '=', "deploy_cfg.get('scale_ir_input',", 'False)', 'if', 'scale_ir_input:', 'tile_ir_scale_factor', '=', 'hyper_parameters.tiling_parameters.... | 918,211 |
openvinotoolkit/training_extensions | task.py | BaseInferencerWithConverter.pre_process | pre_process | Pre-process function of OpenVINO Detection Inferencer. | [
"Pre-process",
"function",
"of",
"OpenVINO",
"Detection",
"Inferencer."
] | def pre_process(self, image: np.ndarray) -> Tuple[Dict[str, np.ndarray], Dict[str, Any]]:
return self.model.preprocess(image) | ['def', 'pre_process(self,', 'image:', 'np.ndarray)', '->', 'Tuple[Dict[str,', 'np.ndarray],', 'Dict[str,', 'Any]]:', 'return', 'self.model.preprocess(image)'] | 918,213 |
openvinotoolkit/training_extensions | task.py | BaseInferencerWithConverter.get_saliency_map | get_saliency_map | Saliency map function of OpenVINO Detection Inferencer. | [
"Saliency",
"map",
"function",
"of",
"OpenVINO",
"Detection",
"Inferencer."
] | def get_saliency_map(self, prediction: Any):
if isinstance(prediction.saliency_map, list):
return prediction.saliency_map
if prediction.saliency_map.shape[0] == 1:
return prediction.saliency_map[0]
return prediction.saliency_map | ['def', 'get_saliency_map(self,', 'prediction:', 'Any):', 'if', 'isinstance(prediction.saliency_map,', 'list):', 'return', 'prediction.saliency_map', 'if', 'prediction.saliency_map.shape[0]', '==', '1:', 'return', 'prediction.saliency_map[0]', 'return', 'prediction.saliency_map'] | 918,214 |
openvinotoolkit/training_extensions | task.py | BaseInferencerWithConverter.predict | predict | Predict function of OpenVINO Detection Inferencer. | [
"Predict",
"function",
"of",
"OpenVINO",
"Detection",
"Inferencer."
] | def predict(self, image: np.ndarray):
(image, metadata) = self.pre_process(image)
raw_predictions = self.forward(image)
detections = self.model.postprocess(raw_predictions, metadata)
predictions = self.converter.convert_to_annotation(detections, metadata)
if 'feature_vector' not in raw_predictions o... | ['def', 'predict(self,', 'image:', 'np.ndarray):', '(image,', 'metadata)', '=', 'self.pre_process(image)', 'raw_predictions', '=', 'self.forward(image)', 'detections', '=', 'self.model.postprocess(raw_predictions,', 'metadata)', 'predictions', '=', 'self.converter.convert_to_annotation(detections,', 'metadata)', 'if', ... | 918,215 |
openvinotoolkit/training_extensions | task.py | BaseInferencerWithConverter.forward | forward | Forward function of OpenVINO Detection Inferencer. | [
"Forward",
"function",
"of",
"OpenVINO",
"Detection",
"Inferencer."
] | def forward(self, image: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
return self.model.infer_sync(image) | ['def', 'forward(self,', 'image:', 'Dict[str,', 'np.ndarray])', '->', 'Dict[str,', 'np.ndarray]:', 'return', 'self.model.infer_sync(image)'] | 918,216 |
openvinotoolkit/training_extensions | task.py | OpenVINOTileClassifierWrapper.predict | predict | Run prediction by tiling image to small patches. | [
"Run",
"prediction",
"by",
"tiling",
"image",
"to",
"small",
"patches."
] | def predict(self, image: np.ndarray) -> Tuple[AnnotationSceneEntity, Tuple[np.ndarray, np.ndarray]]:
detections = self.tiler(image)
annotations = self.converter.convert_to_annotation(detections, metadata={'original_shape': image.shape})
features = (detections.feature_vector.reshape(-1), self.get_saliency_ma... | ['def', 'predict(self,', 'image:', 'np.ndarray)', '->', 'Tuple[AnnotationSceneEntity,', 'Tuple[np.ndarray,', 'np.ndarray]]:', 'detections', '=', 'self.tiler(image)', 'annotations', '=', 'self.converter.convert_to_annotation(detections,', "metadata={'original_shape':", 'image.shape})', 'features', '=', '(detections.feat... | 918,218 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.hparams | hparams | Hparams of OpenVINO Detection Task. | [
"Hparams",
"of",
"OpenVINO",
"Detection",
"Task."
] | def hparams(self):
return self.task_environment.get_hyper_parameters(DetectionConfig) | ['def', 'hparams(self):', 'return', 'self.task_environment.get_hyper_parameters(DetectionConfig)'] | 918,219 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.load_inferencer | load_inferencer | load_inferencer function of OpenVINO Detection Task. | [
"load_inferencer",
"function",
"of",
"OpenVINO",
"Detection",
"Task."
] | def load_inferencer(self) -> Union[OpenVINODetectionInferencer, OpenVINOMaskInferencer, OpenVINORotatedRectInferencer, OpenVINOTileClassifierWrapper]:
if self.model is None:
raise RuntimeError('load_inferencer failed, model is None')
_hparams = copy.deepcopy(self.hparams)
if _hparams.postprocessing.... | ['def', 'load_inferencer(self)', '->', 'Union[OpenVINODetectionInferencer,', 'OpenVINOMaskInferencer,', 'OpenVINORotatedRectInferencer,', 'OpenVINOTileClassifierWrapper]:', 'if', 'self.model', 'is', 'None:', 'raise', "RuntimeError('load_inferencer", 'failed,', 'model', 'is', "None')", '_hparams', '=', 'copy.deepcopy(se... | 918,221 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.infer | infer | Infer function of OpenVINODetectionTask. | [
"Infer",
"function",
"of",
"OpenVINODetectionTask."
] | def infer(self, dataset: DatasetEntity, inference_parameters: Optional[InferenceParameters]=None) -> DatasetEntity:
logger.info('Start OpenVINO inference')
if inference_parameters is not None:
update_progress_callback = inference_parameters.update_progress
add_saliency_map = not inference_parame... | ['def', 'infer(self,', 'dataset:', 'DatasetEntity,', 'inference_parameters:', 'Optional[InferenceParameters]=None)', '->', 'DatasetEntity:', "logger.info('Start", 'OpenVINO', "inference')", 'if', 'inference_parameters', 'is', 'not', 'None:', 'update_progress_callback', '=', 'inference_parameters.update_progress', 'add_... | 918,222 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.explain | explain | Explain function of OpenVINODetectionTask. | [
"Explain",
"function",
"of",
"OpenVINODetectionTask."
] | def explain(self, dataset: DatasetEntity, explain_parameters: Optional[ExplainParameters]=None) -> DatasetEntity:
logger.info('Start OpenVINO explain')
update_progress_callback = default_progress_callback
process_saliency_maps = False
explain_predicted_classes = True
if explain_parameters is not Non... | ['def', 'explain(self,', 'dataset:', 'DatasetEntity,', 'explain_parameters:', 'Optional[ExplainParameters]=None)', '->', 'DatasetEntity:', "logger.info('Start", 'OpenVINO', "explain')", 'update_progress_callback', '=', 'default_progress_callback', 'process_saliency_maps', '=', 'False', 'explain_predicted_classes', '=',... | 918,223 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.evaluate | evaluate | Evaluate function of OpenVINODetectionTask. | [
"Evaluate",
"function",
"of",
"OpenVINODetectionTask."
] | def evaluate(self, output_resultset: ResultSetEntity, evaluation_metric: Optional[str]=None):
logger.info('Start OpenVINO metric evaluation')
if evaluation_metric is not None:
logger.warning(f'Requested to use {evaluation_metric} metric, but parameter is ignored. Use F-measure instead.')
output_resu... | ['def', 'evaluate(self,', 'output_resultset:', 'ResultSetEntity,', 'evaluation_metric:', 'Optional[str]=None):', "logger.info('Start", 'OpenVINO', 'metric', "evaluation')", 'if', 'evaluation_metric', 'is', 'not', 'None:', "logger.warning(f'Requested", 'to', 'use', '{evaluation_metric}', 'metric,', 'but', 'parameter', '... | 918,224 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.deploy | deploy | Deploy function of OpenVINODetectionTask. | [
"Deploy",
"function",
"of",
"OpenVINODetectionTask."
] | def deploy(self, output_model: ModelEntity) -> None:
logger.info('Deploying the model')
work_dir = os.path.dirname(demo.__file__)
parameters = {}
parameters['type_of_model'] = self.inferencer.model.__model__
parameters['converter_type'] = str(self.task_type)
parameters['model_parameters'] = self... | ['def', 'deploy(self,', 'output_model:', 'ModelEntity)', '->', 'None:', "logger.info('Deploying", 'the', "model')", 'work_dir', '=', 'os.path.dirname(demo.__file__)', 'parameters', '=', '{}', "parameters['type_of_model']", '=', 'self.inferencer.model.__model__', "parameters['converter_type']", '=', 'str(self.task_type)... | 918,225 |
openvinotoolkit/training_extensions | task.py | OpenVINODetectionTask.optimize | optimize | Optimize function of OpenVINODetectionTask. | [
"Optimize",
"function",
"of",
"OpenVINODetectionTask."
] | def optimize(self, optimization_type: OptimizationType, dataset: DatasetEntity, output_model: ModelEntity, optimization_parameters: Optional[OptimizationParameters]=None):
logger.info('Start PTQ optimization')
if optimization_type is not OptimizationType.POT:
raise ValueError('PTQ is the only supported ... | ['def', 'optimize(self,', 'optimization_type:', 'OptimizationType,', 'dataset:', 'DatasetEntity,', 'output_model:', 'ModelEntity,', 'optimization_parameters:', 'Optional[OptimizationParameters]=None):', "logger.info('Start", 'PTQ', "optimization')", 'if', 'optimization_type', 'is', 'not', 'OptimizationType.POT:', 'rais... | 918,226 |
openvinotoolkit/training_extensions | instance_segmentation_sample.py | load_test_dataset | load_test_dataset | Load Sample dataset for Instance_segmentation. | [
"Load",
"Sample",
"dataset",
"for",
"Instance_segmentation."
] | def load_test_dataset(data_type, task_type=Domain.INSTANCE_SEGMENTATION):
def gen_circle_image(resolution):
(width, height) = resolution
image = np.full([height, width, 3], fill_value=255, dtype=np.uint8)
gt_label = np.full([height, width, 1], fill_value=0, dtype=np.uint8)
cv2.circl... | ['def', 'load_test_dataset(data_type,', 'task_type=Domain.INSTANCE_SEGMENTATION):', 'def', 'gen_circle_image(resolution):', '(width,', 'height)', '=', 'resolution', 'image', '=', 'np.full([height,', 'width,', '3],', 'fill_value=255,', 'dtype=np.uint8)', 'gt_label', '=', 'np.full([height,', 'width,', '1],', 'fill_value=... | 918,232 |
openvinotoolkit/training_extensions | data.py | load_dataset_items_coco_format | load_dataset_items_coco_format | Load dataset from CocoDataset. | [
"Load",
"dataset",
"from",
"CocoDataset."
] | def load_dataset_items_coco_format(ann_file_path: str, data_root_dir: str, domain: Domain, subset: Subset=Subset.NONE, labels_list: Optional[List[LabelEntity]]=None, with_mask: bool=False):
test_mode = subset in {Subset.VALIDATION, Subset.TESTING}
coco_dataset = CocoDataset(ann_file=ann_file_path, data_root=dat... | ['def', 'load_dataset_items_coco_format(ann_file_path:', 'str,', 'data_root_dir:', 'str,', 'domain:', 'Domain,', 'subset:', 'Subset=Subset.NONE,', 'labels_list:', 'Optional[List[LabelEntity]]=None,', 'with_mask:', 'bool=False):', 'test_mode', '=', 'subset', 'in', '{Subset.VALIDATION,', 'Subset.TESTING}', 'coco_dataset'... | 918,235 |
openvinotoolkit/training_extensions | data.py | CocoDataset.prepare_img | prepare_img | Load Annotations function with images. | [
"Load",
"Annotations",
"function",
"with",
"images."
] | def prepare_img(self, idx: int):
img_info = self.data_infos[idx]
ann_info = self.get_ann_info(idx)
results = dict(img_info=img_info, ann_info=ann_info)
self.pre_pipeline(results)
return LoadAnnotations(with_mask=self.with_mask)(results) | ['def', 'prepare_img(self,', 'idx:', 'int):', 'img_info', '=', 'self.data_infos[idx]', 'ann_info', '=', 'self.get_ann_info(idx)', 'results', '=', 'dict(img_info=img_info,', 'ann_info=ann_info)', 'self.pre_pipeline(results)', 'return', 'LoadAnnotations(with_mask=self.with_mask)(results)'] | 918,240 |
openvinotoolkit/training_extensions | utils.py | mask_resize | mask_resize | Resize mask to the size of the bounding box. | [
"Resize",
"mask",
"to",
"the",
"size",
"of",
"the",
"bounding",
"box."
] | def mask_resize(box: np.ndarray, mask: np.ndarray, img_height: int, img_width: int):
mask = np.pad(mask, ((1, 1), (1, 1)), 'constant', constant_values=0)
scale_h = mask.shape[0] / (mask.shape[0] - 2.0)
scale_w = mask.shape[1] / (mask.shape[1] - 2.0)
extended_box = expand_box(box, scale_h=scale_h, scale_... | ['def', 'mask_resize(box:', 'np.ndarray,', 'mask:', 'np.ndarray,', 'img_height:', 'int,', 'img_width:', 'int):', 'mask', '=', 'np.pad(mask,', '((1,', '1),', '(1,', '1)),', "'constant',", 'constant_values=0)', 'scale_h', '=', 'mask.shape[0]', '/', '(mask.shape[0]', '-', '2.0)', 'scale_w', '=', 'mask.shape[1]', '/', '(ma... | 918,242 |
openvinotoolkit/training_extensions | utils.py | create_detection_shapes | create_detection_shapes | Create prediction detection shapes. | [
"Create",
"prediction",
"detection",
"shapes."
] | def create_detection_shapes(pred_results: List[np.ndarray], width: int, height: int, confidence_threshold: float, use_ellipse_shapes: bool, labels: List):
shapes = []
for (label_idx, detections) in enumerate(pred_results):
for det in detections:
probability = float(det[4])
coords... | ['def', 'create_detection_shapes(pred_results:', 'List[np.ndarray],', 'width:', 'int,', 'height:', 'int,', 'confidence_threshold:', 'float,', 'use_ellipse_shapes:', 'bool,', 'labels:', 'List):', 'shapes', '=', '[]', 'for', '(label_idx,', 'detections)', 'in', 'enumerate(pred_results):', 'for', 'det', 'in', 'detections:'... | 918,243 |
openvinotoolkit/training_extensions | task.py | OTXSegmentationTask.evaluate | evaluate | Evaluate function of OTX Segmentation Task. | [
"Evaluate",
"function",
"of",
"OTX",
"Segmentation",
"Task."
] | def evaluate(self, output_resultset: ResultSetEntity, evaluation_metric: Optional[str]=None):
logger.info('called evaluate()')
if evaluation_metric is not None:
logger.warning(f'Requested to use {evaluation_metric} metric, but parameter is ignored. Use mDice instead.')
metric = MetricsHelper.compute... | ['def', 'evaluate(self,', 'output_resultset:', 'ResultSetEntity,', 'evaluation_metric:', 'Optional[str]=None):', "logger.info('called", "evaluate()')", 'if', 'evaluation_metric', 'is', 'not', 'None:', "logger.warning(f'Requested", 'to', 'use', '{evaluation_metric}', 'metric,', 'but', 'parameter', 'is', 'ignored.', 'Use... | 918,248 |
openvinotoolkit/training_extensions | task.py | OTXSegmentationTask.save_model | save_model | Save best model weights in SegmentationTrainTask. | [
"Save",
"best",
"model",
"weights",
"in",
"SegmentationTrainTask."
] | def save_model(self, output_model: ModelEntity):
if is_multigpu_child_process():
return
logger.info('called save_model')
buffer = io.BytesIO()
hyperparams_str = ids_to_strings(cfg_helper.convert(self._hyperparams, dict, enum_to_str=True))
labels = {label.name: label.color.rgb_tuple for label... | ['def', 'save_model(self,', 'output_model:', 'ModelEntity):', 'if', 'is_multigpu_child_process():', 'return', "logger.info('called", "save_model')", 'buffer', '=', 'io.BytesIO()', 'hyperparams_str', '=', 'ids_to_strings(cfg_helper.convert(self._hyperparams,', 'dict,', 'enum_to_str=True))', 'labels', '=', '{label.name:'... | 918,249 |
openvinotoolkit/training_extensions | configurer.py | SegmentationConfigurer.configure_decode_head | configure_decode_head | Change to incremental loss (ignore mode) and substitute head with otx universal head. | [
"Change",
"to",
"incremental",
"loss",
"(ignore",
"mode)",
"and",
"substitute",
"head",
"with",
"otx",
"universal",
"head."
] | def configure_decode_head(self, cfg: Config) -> None:
ignore = cfg.get('ignore', False)
for head in ('decode_head', 'auxiliary_head'):
decode_head = cfg.model.get(head, None)
if decode_head is not None:
decode_head.base_type = decode_head.type
decode_head.type = otx_head_... | ['def', 'configure_decode_head(self,', 'cfg:', 'Config)', '->', 'None:', 'ignore', '=', "cfg.get('ignore',", 'False)', 'for', 'head', 'in', "('decode_head',", "'auxiliary_head'):", 'decode_head', '=', 'cfg.model.get(head,', 'None)', 'if', 'decode_head', 'is', 'not', 'None:', 'decode_head.base_type', '=', 'decode_head.t... | 918,252 |
openvinotoolkit/training_extensions | configurer.py | SegmentationConfigurer.patch_chkpt | patch_chkpt | Modify state dict for pretrained weights to match model state dict. | [
"Modify",
"state",
"dict",
"for",
"pretrained",
"weights",
"to",
"match",
"model",
"state",
"dict."
] | def patch_chkpt(ckpt_path: str, new_path: Optional[str]=None) -> str:
ckpt = CheckpointLoader.load_checkpoint(ckpt_path, map_location='cpu')
local_torch_hub_folder = torch.hub.get_dir()
if 'state_dict' in ckpt:
ckpt = ckpt['state_dict']
new_ckpt = OrderedDict()
modified = False
... | ['def', 'patch_chkpt(ckpt_path:', 'str,', 'new_path:', 'Optional[str]=None)', '->', 'str:', 'ckpt', '=', 'CheckpointLoader.load_checkpoint(ckpt_path,', "map_location='cpu')", 'local_torch_hub_folder', '=', 'torch.hub.get_dir()', 'if', "'state_dict'", 'in', 'ckpt:', 'ckpt', '=', "ckpt['state_dict']", 'new_ckpt', '=', 'O... | 918,254 |
openvinotoolkit/training_extensions | configurer.py | SemiSLSegmentationConfigurer.configure_task | configure_task | Adjust settings for task adaptation. | [
"Adjust",
"settings",
"for",
"task",
"adaptation."
] | def configure_task(self, cfg: ConfigDict, **kwargs: Any) -> None:
super().configure_task(cfg, **kwargs)
remove_custom_hook(cfg, 'TaskAdaptHook') | ['def', 'configure_task(self,', 'cfg:', 'ConfigDict,', '**kwargs:', 'Any)', '->', 'None:', 'super().configure_task(cfg,', '**kwargs)', 'remove_custom_hook(cfg,', "'TaskAdaptHook')"] | 918,257 |
openvinotoolkit/training_extensions | task.py | MMSegmentationTask.configure | configure | Patch mmcv configs for OTX segmentation settings. | [
"Patch",
"mmcv",
"configs",
"for",
"OTX",
"segmentation",
"settings."
] | def configure(self, training=True, ir_options=None, export=False):
recipe_cfg = deepcopy(self._recipe_cfg)
assert recipe_cfg is not None, "'recipe_cfg' is not initialized."
if self._data_cfg is not None:
data_classes = [label.name for label in self._labels]
else:
data_classes = None
... | ['def', 'configure(self,', 'training=True,', 'ir_options=None,', 'export=False):', 'recipe_cfg', '=', 'deepcopy(self._recipe_cfg)', 'assert', 'recipe_cfg', 'is', 'not', 'None,', '"\'recipe_cfg\'', 'is', 'not', 'initialized."', 'if', 'self._data_cfg', 'is', 'not', 'None:', 'data_classes', '=', '[label.name', 'for', 'lab... | 918,258 |
openvinotoolkit/training_extensions | detcon_loss.py | manual_cross_entropy | manual_cross_entropy | Manually calculate weighted cross entropy. | [
"Manually",
"calculate",
"weighted",
"cross",
"entropy."
] | def manual_cross_entropy(logits, labels, weight):
cross_entropy = -weight * torch.sum(labels * F.log_softmax(logits, dim=-1), dim=-1)
return torch.mean(cross_entropy) | ['def', 'manual_cross_entropy(logits,', 'labels,', 'weight):', 'cross_entropy', '=', '-weight', '*', 'torch.sum(labels', '*', 'F.log_softmax(logits,', 'dim=-1),', 'dim=-1)', 'return', 'torch.mean(cross_entropy)'] | 918,276 |
openvinotoolkit/training_extensions | detcon.py | MaskPooling.pool_masks | pool_masks | Perform mask pooling and create binary masks. | [
"Perform",
"mask",
"pooling",
"and",
"create",
"binary",
"masks."
] | def pool_masks(self, masks: torch.Tensor):
if masks.ndim < 4:
masks = masks.unsqueeze(dim=1)
masks = masks == self.mask_ids[None, :, None, None].to(masks.device)
masks = self.pool(masks.to(torch.float))
(b, c, h, w) = masks.shape
masks = torch.reshape(masks, (b, c, h * w))
masks = torch.... | ['def', 'pool_masks(self,', 'masks:', 'torch.Tensor):', 'if', 'masks.ndim', '<', '4:', 'masks', '=', 'masks.unsqueeze(dim=1)', 'masks', '=', 'masks', '==', 'self.mask_ids[None,', ':,', 'None,', 'None].to(masks.device)', 'masks', '=', 'self.pool(masks.to(torch.float))', '(b,', 'c,', 'h,', 'w)', '=', 'masks.shape', 'mask... | 918,279 |
openvinotoolkit/training_extensions | detcon.py | MaskPooling.forward | forward | Forward function for mask pooling. | [
"Forward",
"function",
"for",
"mask",
"pooling."
] | def forward(self, masks: torch.Tensor):
binary_masks = self.pool_masks(masks)
(sampled_masks, sampled_mask_ids) = self.sample_masks(binary_masks)
areas = sampled_masks.sum(dim=-1, keepdim=True)
sampled_masks = sampled_masks / torch.maximum(areas, torch.tensor(1.0, device=areas.device))
return (sampl... | ['def', 'forward(self,', 'masks:', 'torch.Tensor):', 'binary_masks', '=', 'self.pool_masks(masks)', '(sampled_masks,', 'sampled_mask_ids)', '=', 'self.sample_masks(binary_masks)', 'areas', '=', 'sampled_masks.sum(dim=-1,', 'keepdim=True)', 'sampled_masks', '=', 'sampled_masks', '/', 'torch.maximum(areas,', 'torch.tenso... | 918,281 |
openvinotoolkit/training_extensions | detcon.py | DetConB.init_weights | init_weights | Initialize the weights of model. | [
"Initialize",
"the",
"weights",
"of",
"model."
] | def init_weights(self, pretrained: Optional[str]=None):
if pretrained is not None:
logger.info(f'load model from: {pretrained}')
load_checkpoint(self.online_backbone, pretrained, strict=False, map_location=None, logger=logger, revise_keys=[('^backbone\\.', '')])
for (param_ol, param_tgt) in zip(... | ['def', 'init_weights(self,', 'pretrained:', 'Optional[str]=None):', 'if', 'pretrained', 'is', 'not', 'None:', "logger.info(f'load", 'model', 'from:', "{pretrained}')", 'load_checkpoint(self.online_backbone,', 'pretrained,', 'strict=False,', 'map_location=None,', 'logger=logger,', "revise_keys=[('^backbone\\\\.',", "''... | 918,282 |
openvinotoolkit/training_extensions | detcon.py | DetConB.transform_inputs | transform_inputs | Transform inputs for decoder. | [
"Transform",
"inputs",
"for",
"decoder."
] | def transform_inputs(self, inputs: Union[List, Tuple]):
if self.input_transform == 'resize_concat' and isinstance(self.in_index, (list, tuple)):
inputs = [inputs[i] for i in self.in_index]
upsampled_inputs = [resize(input=x, size=inputs[0].shape[2:], mode='bilinear', align_corners=self.align_corners... | ['def', 'transform_inputs(self,', 'inputs:', 'Union[List,', 'Tuple]):', 'if', 'self.input_transform', '==', "'resize_concat'", 'and', 'isinstance(self.in_index,', '(list,', 'tuple)):', 'inputs', '=', '[inputs[i]', 'for', 'i', 'in', 'self.in_index]', 'upsampled_inputs', '=', '[resize(input=x,', 'size=inputs[0].shape[2:]... | 918,283 |
openvinotoolkit/training_extensions | detcon.py | DetConB.sample_masked_feats | sample_masked_feats | Sampled features from mask. | [
"Sampled",
"features",
"from",
"mask."
] | def sample_masked_feats(self, feats: Union[torch.Tensor, List, Tuple], masks: torch.Tensor, projector: nn.Module):
if isinstance(feats, (list, tuple)) and len(feats) > 1:
feats = self.transform_inputs(feats)
(sampled_masks, sampled_mask_ids) = self.mask_pool(masks)
(b, c, h, w) = feats.shape
fea... | ['def', 'sample_masked_feats(self,', 'feats:', 'Union[torch.Tensor,', 'List,', 'Tuple],', 'masks:', 'torch.Tensor,', 'projector:', 'nn.Module):', 'if', 'isinstance(feats,', '(list,', 'tuple))', 'and', 'len(feats)', '>', '1:', 'feats', '=', 'self.transform_inputs(feats)', '(sampled_masks,', 'sampled_mask_ids)', '=', 'se... | 918,285 |
openvinotoolkit/training_extensions | mean_teacher_segmentor.py | MeanTeacherSegmentor.encode_decode | encode_decode | Encode and decode images. | [
"Encode",
"and",
"decode",
"images."
] | def encode_decode(self, img, img_metas):
return self.model_s.encode_decode(img, img_metas) | ['def', 'encode_decode(self,', 'img,', 'img_metas):', 'return', 'self.model_s.encode_decode(img,', 'img_metas)'] | 918,293 |
openvinotoolkit/training_extensions | mean_teacher_segmentor.py | MeanTeacherSegmentor.generate_pseudo_labels | generate_pseudo_labels | Generate pseudo labels from teacher model, apply filter loss method. | [
"Generate",
"pseudo",
"labels",
"from",
"teacher",
"model,",
"apply",
"filter",
"loss",
"method."
] | def generate_pseudo_labels(self, ul_w_img, ul_img_metas):
with torch.no_grad():
teacher_feat = self.model_t.extract_feat(ul_w_img)
teacher_out = self.model_t._decode_head_forward_test(teacher_feat, ul_img_metas)
teacher_out = resize(input=teacher_out, size=ul_w_img.shape[2:], mode='bilinear'... | ['def', 'generate_pseudo_labels(self,', 'ul_w_img,', 'ul_img_metas):', 'with', 'torch.no_grad():', 'teacher_feat', '=', 'self.model_t.extract_feat(ul_w_img)', 'teacher_out', '=', 'self.model_t._decode_head_forward_test(teacher_feat,', 'ul_img_metas)', 'teacher_out', '=', 'resize(input=teacher_out,', 'size=ul_w_img.shap... | 918,295 |
openvinotoolkit/training_extensions | data_utils.py | get_classes_from_annotation | get_classes_from_annotation | Getter function of classes from annotation. | [
"Getter",
"function",
"of",
"classes",
"from",
"annotation."
] | def get_classes_from_annotation(annot_path):
with open(annot_path, encoding='UTF-8') as input_stream:
content = json.load(input_stream)
labels_map = content['labels_map']
categories = [(v['name'], v['id']) for v in sorted(labels_map, key=lambda tup: int(tup['id']))]
return categories | ['def', 'get_classes_from_annotation(annot_path):', 'with', 'open(annot_path,', "encoding='UTF-8')", 'as', 'input_stream:', 'content', '=', 'json.load(input_stream)', 'labels_map', '=', "content['labels_map']", 'categories', '=', "[(v['name'],", "v['id'])", 'for', 'v', 'in', 'sorted(labels_map,', 'key=lambda', 'tup:', ... | 918,305 |
openvinotoolkit/training_extensions | data_utils.py | abs_path_if_valid | abs_path_if_valid | Valid function of abs_path. | [
"Valid",
"function",
"of",
"abs_path."
] | def abs_path_if_valid(value):
if value:
return os.path.abspath(value)
return None | ['def', 'abs_path_if_valid(value):', 'if', 'value:', 'return', 'os.path.abspath(value)', 'return', 'None'] | 918,306 |
openvinotoolkit/training_extensions | data_utils.py | create_annotation_from_hard_seg_map | create_annotation_from_hard_seg_map | Creation function from hard seg_map. | [
"Creation",
"function",
"from",
"hard",
"seg_map."
] | def create_annotation_from_hard_seg_map(hard_seg_map: np.ndarray, labels: List[LabelEntity]):
(height, width) = hard_seg_map.shape[:2]
unique_labels = np.unique(hard_seg_map)
annotations: List[Annotation] = []
for label_id in unique_labels:
label_id_entity = ID(f'{label_id:08}')
matches ... | ['def', 'create_annotation_from_hard_seg_map(hard_seg_map:', 'np.ndarray,', 'labels:', 'List[LabelEntity]):', '(height,', 'width)', '=', 'hard_seg_map.shape[:2]', 'unique_labels', '=', 'np.unique(hard_seg_map)', 'annotations:', 'List[Annotation]', '=', '[]', 'for', 'label_id', 'in', 'unique_labels:', 'label_id_entity',... | 918,307 |
openvinotoolkit/training_extensions | data_utils.py | get_valid_label_mask_per_batch | get_valid_label_mask_per_batch | Get valid label mask removing ignored classes to zero mask in a batch. | [
"Get",
"valid",
"label",
"mask",
"removing",
"ignored",
"classes",
"to",
"zero",
"mask",
"in",
"a",
"batch."
] | def get_valid_label_mask_per_batch(img_metas, num_classes):
valid_label_mask_per_batch = []
for (_, meta) in enumerate(img_metas):
valid_label_mask = torch.Tensor([1 for _ in range(num_classes)])
if 'ignored_labels' in meta and meta['ignored_labels']:
valid_label_mask[meta['ignored_l... | ['def', 'get_valid_label_mask_per_batch(img_metas,', 'num_classes):', 'valid_label_mask_per_batch', '=', '[]', 'for', '(_,', 'meta)', 'in', 'enumerate(img_metas):', 'valid_label_mask', '=', 'torch.Tensor([1', 'for', '_', 'in', 'range(num_classes)])', 'if', "'ignored_labels'", 'in', 'meta', 'and', "meta['ignored_labels'... | 918,310 |
openvinotoolkit/training_extensions | data_utils.py | create_pseudo_masks | create_pseudo_masks | Create pseudo masks for Self-SL using DetCon. | [
"Create",
"pseudo",
"masks",
"for",
"Self-SL",
"using",
"DetCon."
] | def create_pseudo_masks(ann_file_path: str, data_root_dir: str, mode='FH'):
if not os.path.isdir(ann_file_path):
logger.info(f'Creating pseudo masks with mode={mode} is required. It may take some time. Once this process has been performed, there is no need to proceed again with ann_file_path={ann_file_path}... | ['def', 'create_pseudo_masks(ann_file_path:', 'str,', 'data_root_dir:', 'str,', "mode='FH'):", 'if', 'not', 'os.path.isdir(ann_file_path):', "logger.info(f'Creating", 'pseudo', 'masks', 'with', 'mode={mode}', 'is', 'required.', 'It', 'may', 'take', 'some', 'time.', 'Once', 'this', 'process', 'has', 'been', 'performed,'... | 918,311 |
openvinotoolkit/training_extensions | task.py | OpenVINOSegmentationTask.hparams | hparams | Hparams of OpenVINO Segmentation Task. | [
"Hparams",
"of",
"OpenVINO",
"Segmentation",
"Task."
] | def hparams(self):
return self.task_environment.get_hyper_parameters(SegmentationConfig) | ['def', 'hparams(self):', 'return', 'self.task_environment.get_hyper_parameters(SegmentationConfig)'] | 918,315 |
openvinotoolkit/training_extensions | task.py | OpenVINOSegmentationTask.infer | infer | Infer function of OpenVINOSegmentationTask. | [
"Infer",
"function",
"of",
"OpenVINOSegmentationTask."
] | def infer(self, dataset: DatasetEntity, inference_parameters: Optional[InferenceParameters]=None) -> DatasetEntity:
if inference_parameters is not None:
update_progress_callback = inference_parameters.update_progress
dump_soft_prediction = not inference_parameters.is_evaluation
process_soft_... | ['def', 'infer(self,', 'dataset:', 'DatasetEntity,', 'inference_parameters:', 'Optional[InferenceParameters]=None)', '->', 'DatasetEntity:', 'if', 'inference_parameters', 'is', 'not', 'None:', 'update_progress_callback', '=', 'inference_parameters.update_progress', 'dump_soft_prediction', '=', 'not', 'inference_paramet... | 918,317 |
openvinotoolkit/training_extensions | task.py | OpenVINOSegmentationTask.deploy | deploy | Deploy function of OpenVINOSegmentationTask. | [
"Deploy",
"function",
"of",
"OpenVINOSegmentationTask."
] | def deploy(self, output_model: ModelEntity) -> None:
logger.info('Deploying the model')
if self.model is None:
raise RuntimeError('deploy failed, model is None')
work_dir = os.path.dirname(demo.__file__)
parameters: Dict[str, Any] = {}
parameters['type_of_model'] = 'Segmentation'
paramet... | ['def', 'deploy(self,', 'output_model:', 'ModelEntity)', '->', 'None:', "logger.info('Deploying", 'the', "model')", 'if', 'self.model', 'is', 'None:', 'raise', "RuntimeError('deploy", 'failed,', 'model', 'is', "None')", 'work_dir', '=', 'os.path.dirname(demo.__file__)', 'parameters:', 'Dict[str,', 'Any]', '=', '{}', "p... | 918,319 |
openvinotoolkit/training_extensions | task.py | OpenVINOSegmentationTask.optimize | optimize | Optimize function of OpenVINOSegmentationTask. | [
"Optimize",
"function",
"of",
"OpenVINOSegmentationTask."
] | def optimize(self, optimization_type: OptimizationType, dataset: DatasetEntity, output_model: ModelEntity, optimization_parameters: Optional[OptimizationParameters]=None):
logger.info('Start PTQ optimization')
if self.model is None:
raise RuntimeError('PTQ optimize failed, model is None')
if optimiz... | ['def', 'optimize(self,', 'optimization_type:', 'OptimizationType,', 'dataset:', 'DatasetEntity,', 'output_model:', 'ModelEntity,', 'optimization_parameters:', 'Optional[OptimizationParameters]=None):', "logger.info('Start", 'PTQ', "optimization')", 'if', 'self.model', 'is', 'None:', 'raise', "RuntimeError('PTQ", 'opti... | 918,320 |
openvinotoolkit/training_extensions | openvino_models.py | ImageEncoder.preprocess | preprocess | Update meta for image encoder. | [
"Update",
"meta",
"for",
"image",
"encoder."
] | def preprocess(self, inputs: np.ndarray, extra_processing: bool=False) -> Tuple[Dict[str, np.ndarray], Dict[str, Any]]:
(dict_inputs, meta) = super().preprocess(inputs)
if extra_processing:
dict_inputs['images'] = ResizeLongestSide.apply_image(dict_inputs['images'][0], self.image_size).transpose(2, 0, 1... | ['def', 'preprocess(self,', 'inputs:', 'np.ndarray,', 'extra_processing:', 'bool=False)', '->', 'Tuple[Dict[str,', 'np.ndarray],', 'Dict[str,', 'Any]]:', '(dict_inputs,', 'meta)', '=', 'super().preprocess(inputs)', 'if', 'extra_processing:', "dict_inputs['images']", '=', "ResizeLongestSide.apply_image(dict_inputs['imag... | 918,323 |
openvinotoolkit/training_extensions | openvino_models.py | Decoder.postprocess | postprocess | Postprocess to convert soft prediction to hard prediction. | [
"Postprocess",
"to",
"convert",
"soft",
"prediction",
"to",
"hard",
"prediction."
] | def postprocess(self, outputs: Dict[str, np.ndarray], meta: Dict[str, Any]) -> Tuple[np.ndarray, np.ndarray]:
def sigmoid(x):
return np.tanh(x * 0.5) * 0.5 + 0.5
soft_prediction = outputs[self.output_blob_name].squeeze()
soft_prediction = self.resize_and_crop(soft_prediction, meta['original_size'][... | ['def', 'postprocess(self,', 'outputs:', 'Dict[str,', 'np.ndarray],', 'meta:', 'Dict[str,', 'Any])', '->', 'Tuple[np.ndarray,', 'np.ndarray]:', 'def', 'sigmoid(x):', 'return', 'np.tanh(x', '*', '0.5)', '*', '0.5', '+', '0.5', 'soft_prediction', '=', 'outputs[self.output_blob_name].squeeze()', 'soft_prediction', '=', 's... | 918,324 |
openvinotoolkit/training_extensions | openvino_models.py | Decoder.resize_and_crop | resize_and_crop | Resize and crop soft prediction. | [
"Resize",
"and",
"crop",
"soft",
"prediction."
] | def resize_and_crop(self, soft_prediction: np.ndarray, original_size: np.ndarray) -> np.ndarray:
resized_soft_prediction = cv2.resize(soft_prediction, (self.image_size, self.image_size), 0, 0, interpolation=cv2.INTER_LINEAR)
prepadded_size = self.get_padded_size(original_size, self.image_size).astype(np.int64)
... | ['def', 'resize_and_crop(self,', 'soft_prediction:', 'np.ndarray,', 'original_size:', 'np.ndarray)', '->', 'np.ndarray:', 'resized_soft_prediction', '=', 'cv2.resize(soft_prediction,', '(self.image_size,', 'self.image_size),', '0,', '0,', 'interpolation=cv2.INTER_LINEAR)', 'prepadded_size', '=', 'self.get_padded_size(o... | 918,325 |
openvinotoolkit/training_extensions | inference.py | InferenceCallback.on_predict_epoch_end | on_predict_epoch_end | Call when the predict epoch ends. | [
"Call",
"when",
"the",
"predict",
"epoch",
"ends."
] | def on_predict_epoch_end(self, _trainer: Trainer, _pl_module: LightningModule, outputs: List[Any]) -> None:
pred_masks: List = []
iou_predictions: List = []
pred_labels: List = []
for output in outputs[0]:
pred_masks.append(output['masks'][0])
iou_predictions.append(output['iou_predictio... | ['def', 'on_predict_epoch_end(self,', '_trainer:', 'Trainer,', '_pl_module:', 'LightningModule,', 'outputs:', 'List[Any])', '->', 'None:', 'pred_masks:', 'List', '=', '[]', 'iou_predictions:', 'List', '=', '[]', 'pred_labels:', 'List', '=', '[]', 'for', 'output', 'in', 'outputs[0]:', "pred_masks.append(output['masks'][... | 918,327 |
openvinotoolkit/training_extensions | dataset.py | convert_polygon_to_mask | convert_polygon_to_mask | Convert polygon to mask. | [
"Convert",
"polygon",
"to",
"mask."
] | def convert_polygon_to_mask(shape: Polygon, width: int, height: int) -> np.ndarray:
polygon = ShapeFactory.shape_as_polygon(shape)
contour = [[int(point.x * width), int(point.y * height)] for point in polygon.points]
gt_mask = np.zeros(shape=(height, width), dtype=np.uint8)
gt_mask = cv2.drawContours(gt... | ['def', 'convert_polygon_to_mask(shape:', 'Polygon,', 'width:', 'int,', 'height:', 'int)', '->', 'np.ndarray:', 'polygon', '=', 'ShapeFactory.shape_as_polygon(shape)', 'contour', '=', '[[int(point.x', '*', 'width),', 'int(point.y', '*', 'height)]', 'for', 'point', 'in', 'polygon.points]', 'gt_mask', '=', 'np.zeros(shap... | 918,330 |
openvinotoolkit/training_extensions | dataset.py | OTXVisualPromptingDataModule.setup | setup | Setup Visual Prompting Data Module. | [
"Setup",
"Visual",
"Prompting",
"Data",
"Module."
] | def setup(self, stage: Optional[str]=None) -> None:
if not stage == 'predict':
self.summary()
image_size = self.config.image_size
mean = self.config.normalize.mean
std = self.config.normalize.std
if stage == 'fit' or stage is None:
train_otx_dataset = self.dataset.get_subset(Subset.T... | ['def', 'setup(self,', 'stage:', 'Optional[str]=None)', '->', 'None:', 'if', 'not', 'stage', '==', "'predict':", 'self.summary()', 'image_size', '=', 'self.config.image_size', 'mean', '=', 'self.config.normalize.mean', 'std', '=', 'self.config.normalize.std', 'if', 'stage', '==', "'fit'", 'or', 'stage', 'is', 'None:', ... | 918,333 |
openvinotoolkit/training_extensions | transforms.py | collate_fn | collate_fn | Collate function for dataloader. | [
"Collate",
"function",
"for",
"dataloader."
] | def collate_fn(batch: List[Any]) -> Dict:
def _convert_empty_to_none(x: str) -> List:
func = torch.stack if x == 'gt_masks' else torch.tensor
items = [func(item[x]) for item in batch if item[x] is not None]
return None if len(items) == 0 else items
index = [item['index'] for item in bat... | ['def', 'collate_fn(batch:', 'List[Any])', '->', 'Dict:', 'def', '_convert_empty_to_none(x:', 'str)', '->', 'List:', 'func', '=', 'torch.stack', 'if', 'x', '==', "'gt_masks'", 'else', 'torch.tensor', 'items', '=', '[func(item[x])', 'for', 'item', 'in', 'batch', 'if', 'item[x]', 'is', 'not', 'None]', 'return', 'None', '... | 918,343 |
openvinotoolkit/training_extensions | sam_mask_decoder.py | TwoWayAttentionBlock.forward | forward | Apply the transformer block to the queries and keys. | [
"Apply",
"the",
"transformer",
"block",
"to",
"the",
"queries",
"and",
"keys."
] | def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:
if self.skip_first_layer_pe:
queries = self.self_attn(q=queries, k=queries, v=queries)
else:
q = queries + query_pe
attn_out = self.self_attn(q=q, k=q, v=queries)
queries ... | ['def', 'forward(self,', 'queries:', 'Tensor,', 'keys:', 'Tensor,', 'query_pe:', 'Tensor,', 'key_pe:', 'Tensor)', '->', 'Tuple[Tensor,', 'Tensor]:', 'if', 'self.skip_first_layer_pe:', 'queries', '=', 'self.self_attn(q=queries,', 'k=queries,', 'v=queries)', 'else:', 'q', '=', 'queries', '+', 'query_pe', 'attn_out', '=',... | 918,351 |
openvinotoolkit/training_extensions | sam_mask_decoder.py | Attention.forward | forward | Apply the attention layer to the queries, keys, and values. | [
"Apply",
"the",
"attention",
"layer",
"to",
"the",
"queries,",
"keys,",
"and",
"values."
] | def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
q = self.q_proj(q)
k = self.k_proj(k)
v = self.v_proj(v)
q = self._separate_heads(q, self.num_heads)
k = self._separate_heads(k, self.num_heads)
v = self._separate_heads(v, self.num_heads)
(_, _, _, c_per_head) = q.shape
attn ... | ['def', 'forward(self,', 'q:', 'Tensor,', 'k:', 'Tensor,', 'v:', 'Tensor)', '->', 'Tensor:', 'q', '=', 'self.q_proj(q)', 'k', '=', 'self.k_proj(k)', 'v', '=', 'self.v_proj(v)', 'q', '=', 'self._separate_heads(q,', 'self.num_heads)', 'k', '=', 'self._separate_heads(k,', 'self.num_heads)', 'v', '=', 'self._separate_heads... | 918,352 |
openvinotoolkit/training_extensions | sam_image_encoder.py | SAMImageEncoder.forward | forward | Forward function of image encoder. | [
"Forward",
"function",
"of",
"image",
"encoder."
] | def forward(self, images: Tensor) -> Tensor:
image_embeddings = self.backbone(images)
return image_embeddings | ['def', 'forward(self,', 'images:', 'Tensor)', '->', 'Tensor:', 'image_embeddings', '=', 'self.backbone(images)', 'return', 'image_embeddings'] | 918,353 |
openvinotoolkit/training_extensions | layer_norm.py | LayerNorm2d.forward | forward | Forward function of LayerNorm2d. | [
"Forward",
"function",
"of",
"LayerNorm2d."
] | def forward(self, x: Tensor) -> Tensor:
u = x.mean(1, keepdim=True)
s = (x - u).pow(2).mean(1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.eps)
x = self.weight[:, None, None] * x + self.bias[:, None, None]
return x | ['def', 'forward(self,', 'x:', 'Tensor)', '->', 'Tensor:', 'u', '=', 'x.mean(1,', 'keepdim=True)', 's', '=', '(x', '-', 'u).pow(2).mean(1,', 'keepdim=True)', 'x', '=', '(x', '-', 'u)', '/', 'torch.sqrt(s', '+', 'self.eps)', 'x', '=', 'self.weight[:,', 'None,', 'None]', '*', 'x', '+', 'self.bias[:,', 'None,', 'None]', '... | 918,358 |
openvinotoolkit/training_extensions | segment_anything.py | SegmentAnything.freeze_networks | freeze_networks | Freeze networks depending on config. | [
"Freeze",
"networks",
"depending",
"on",
"config."
] | def freeze_networks(self) -> None:
if self.config.model.freeze_image_encoder:
for param in self.image_encoder.parameters():
param.requires_grad = False
if self.config.model.freeze_prompt_encoder:
for param in self.prompt_encoder.parameters():
param.requires_grad = False
... | ['def', 'freeze_networks(self)', '->', 'None:', 'if', 'self.config.model.freeze_image_encoder:', 'for', 'param', 'in', 'self.image_encoder.parameters():', 'param.requires_grad', '=', 'False', 'if', 'self.config.model.freeze_prompt_encoder:', 'for', 'param', 'in', 'self.prompt_encoder.parameters():', 'param.requires_gra... | 918,361 |
openvinotoolkit/training_extensions | segment_anything.py | SegmentAnything.set_metrics | set_metrics | Set metrics for SAM. | [
"Set",
"metrics",
"for",
"SAM."
] | def set_metrics(self) -> None:
assert self.config.model.loss_type.lower() in ['sam', 'medsam'], ValueError(f"{self.config.model.loss_type} is not supported. Please use 'sam' or 'medsam'.")
self.train_metrics = MetricCollection(dict(train_IoU=BinaryJaccardIndex(), train_F1=BinaryF1Score(), train_Dice=Dice(), tra... | ['def', 'set_metrics(self)', '->', 'None:', 'assert', 'self.config.model.loss_type.lower()', 'in', "['sam',", "'medsam'],", 'ValueError(f"{self.config.model.loss_type}', 'is', 'not', 'supported.', 'Please', 'use', "'sam'", 'or', '\'medsam\'.")', 'self.train_metrics', '=', 'MetricCollection(dict(train_IoU=BinaryJaccardI... | 918,362 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.