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 | argument_checks.py | check_directory_path | check_directory_path | Function to check directory path string objects. | [
"Function",
"to",
"check",
"directory",
"path",
"string",
"objects."
] | def check_directory_path(parameter, parameter_name):
raise_value_error_if_parameter_has_unexpected_type(parameter=parameter, parameter_name=parameter_name, expected_type=str)
check_that_parameter_is_not_empty(parameter=parameter, parameter_name=parameter_name)
check_that_null_character_absents_in_string(par... | ['def', 'check_directory_path(parameter,', 'parameter_name):', 'raise_value_error_if_parameter_has_unexpected_type(parameter=parameter,', 'parameter_name=parameter_name,', 'expected_type=str)', 'check_that_parameter_is_not_empty(parameter=parameter,', 'parameter_name=parameter_name)', 'check_that_null_character_absents... | 918,856 |
openvinotoolkit/training_extensions | argument_checks.py | BaseInputArgumentChecker.check | check | Abstract method to check input arguments. | [
"Abstract",
"method",
"to",
"check",
"input",
"arguments."
] | def check(self):
raise NotImplementedError('The check is not implemented') | ['def', 'check(self):', 'raise', "NotImplementedError('The", 'check', 'is', 'not', "implemented')"] | 918,857 |
openvinotoolkit/training_extensions | argument_checks.py | InputConfigCheck.check | check | Method raises ValueError exception if "input_config" parameter is not equal to expected. | [
"Method",
"raises",
"ValueError",
"exception",
"if",
"\"input_config\"",
"parameter",
"is",
"not",
"equal",
"to",
"expected."
] | def check(self):
raise_value_error_if_parameter_has_unexpected_type(parameter=self.parameter, parameter_name=self.parameter_name, expected_type=(str, DictConfig, dict))
check_that_parameter_is_not_empty(parameter=self.parameter, parameter_name=self.parameter_name)
if isinstance(self.parameter, str):
... | ['def', 'check(self):', 'raise_value_error_if_parameter_has_unexpected_type(parameter=self.parameter,', 'parameter_name=self.parameter_name,', 'expected_type=(str,', 'DictConfig,', 'dict))', 'check_that_parameter_is_not_empty(parameter=self.parameter,', 'parameter_name=self.parameter_name)', 'if', 'isinstance(self.para... | 918,858 |
openvinotoolkit/training_extensions | argument_checks.py | FilePathCheck.check | check | Method raises ValueError exception if file path parameter is not equal to expected. | [
"Method",
"raises",
"ValueError",
"exception",
"if",
"file",
"path",
"parameter",
"is",
"not",
"equal",
"to",
"expected."
] | def check(self):
check_file_path(self.parameter, self.parameter_name, self.expected_file_extensions) | ['def', 'check(self):', 'check_file_path(self.parameter,', 'self.parameter_name,', 'self.expected_file_extensions)'] | 918,859 |
openvinotoolkit/training_extensions | argument_checks.py | DatasetParamTypeCheck.check | check | Method raises ValueError exception if parameter is not equal to Dataset. | [
"Method",
"raises",
"ValueError",
"exception",
"if",
"parameter",
"is",
"not",
"equal",
"to",
"Dataset."
] | def check(self):
check_is_parameter_like_dataset(parameter=self.parameter, parameter_name=self.parameter_name) | ['def', 'check(self):', 'check_is_parameter_like_dataset(parameter=self.parameter,', 'parameter_name=self.parameter_name)'] | 918,861 |
openvinotoolkit/training_extensions | argument_checks.py | DirectoryPathCheck.check | check | Method raises ValueError exception if directory path parameter is not equal to expected. | [
"Method",
"raises",
"ValueError",
"exception",
"if",
"directory",
"path",
"parameter",
"is",
"not",
"equal",
"to",
"expected."
] | def check(self):
check_directory_path(parameter=self.parameter, parameter_name=self.parameter_name) | ['def', 'check(self):', 'check_directory_path(parameter=self.parameter,', 'parameter_name=self.parameter_name)'] | 918,862 |
openvinotoolkit/training_extensions | async_pipeline.py | OTXDetectionAsyncPipeline.get_result | get_result | Get result of inference by index. | [
"Get",
"result",
"of",
"inference",
"by",
"index."
] | def get_result(self, id):
result = self.get_raw_result(id)
if result:
(raw_result, meta, preprocess_meta, infer_start_time) = result
self.inference_metrics.update(infer_start_time)
postprocessing_start_time = perf_counter()
result = (self.model.postprocess(raw_result, preprocess_... | ['def', 'get_result(self,', 'id):', 'result', '=', 'self.get_raw_result(id)', 'if', 'result:', '(raw_result,', 'meta,', 'preprocess_meta,', 'infer_start_time)', '=', 'result', 'self.inference_metrics.update(infer_start_time)', 'postprocessing_start_time', '=', 'perf_counter()', 'result', '=', '(self.model.postprocess(r... | 918,864 |
openvinotoolkit/training_extensions | dataset_utils.py | get_local_subset | get_local_subset | Extract a subset that contains only those dataset items that have local annotations. | [
"Extract",
"a",
"subset",
"that",
"contains",
"only",
"those",
"dataset",
"items",
"that",
"have",
"local",
"annotations."
] | def get_local_subset(dataset: DatasetEntity, fully_annotated_idx: Optional[List[int]]=None, include_normal: bool=True) -> DatasetEntity:
local_items = []
if fully_annotated_idx is None:
fully_annotated_idx = get_fully_annotated_idx(dataset)
for idx in fully_annotated_idx:
item = dataset[idx]... | ['def', 'get_local_subset(dataset:', 'DatasetEntity,', 'fully_annotated_idx:', 'Optional[List[int]]=None,', 'include_normal:', 'bool=True)', '->', 'DatasetEntity:', 'local_items', '=', '[]', 'if', 'fully_annotated_idx', 'is', 'None:', 'fully_annotated_idx', '=', 'get_fully_annotated_idx(dataset)', 'for', 'idx', 'in', '... | 918,866 |
openvinotoolkit/training_extensions | dataset_utils.py | split_local_global_dataset | split_local_global_dataset | Split a dataset into the globally and locally annotated subsets. | [
"Split",
"a",
"dataset",
"into",
"the",
"globally",
"and",
"locally",
"annotated",
"subsets."
] | def split_local_global_dataset(dataset: DatasetEntity) -> Tuple[DatasetEntity, DatasetEntity]:
global_dataset = get_global_subset(dataset)
local_dataset = get_local_subset(dataset)
return (global_dataset, local_dataset) | ['def', 'split_local_global_dataset(dataset:', 'DatasetEntity)', '->', 'Tuple[DatasetEntity,', 'DatasetEntity]:', 'global_dataset', '=', 'get_global_subset(dataset)', 'local_dataset', '=', 'get_local_subset(dataset)', 'return', '(global_dataset,', 'local_dataset)'] | 918,868 |
openvinotoolkit/training_extensions | dataset_utils.py | split_local_global_resultset | split_local_global_resultset | Split a resultset into the globally and locally annotated resultsets. | [
"Split",
"a",
"resultset",
"into",
"the",
"globally",
"and",
"locally",
"annotated",
"resultsets."
] | def split_local_global_resultset(resultset: ResultSetEntity) -> Tuple[ResultSetEntity, ResultSetEntity]:
global_gt_dataset = get_global_subset(resultset.ground_truth_dataset)
local_gt_dataset = get_local_subset(resultset.ground_truth_dataset, include_normal=False)
local_idx = get_fully_annotated_idx(results... | ['def', 'split_local_global_resultset(resultset:', 'ResultSetEntity)', '->', 'Tuple[ResultSetEntity,', 'ResultSetEntity]:', 'global_gt_dataset', '=', 'get_global_subset(resultset.ground_truth_dataset)', 'local_gt_dataset', '=', 'get_local_subset(resultset.ground_truth_dataset,', 'include_normal=False)', 'local_idx', '=... | 918,869 |
openvinotoolkit/training_extensions | dataset_utils.py | contains_anomalous_images | contains_anomalous_images | Check if a dataset contains any items with the anomalous label. | [
"Check",
"if",
"a",
"dataset",
"contains",
"any",
"items",
"with",
"the",
"anomalous",
"label."
] | def contains_anomalous_images(dataset: DatasetEntity) -> bool:
for item in dataset:
labels = item.get_shapes_labels()
if any((label.is_anomalous for label in labels)):
return True
return False | ['def', 'contains_anomalous_images(dataset:', 'DatasetEntity)', '->', 'bool:', 'for', 'item', 'in', 'dataset:', 'labels', '=', 'item.get_shapes_labels()', 'if', 'any((label.is_anomalous', 'for', 'label', 'in', 'labels)):', 'return', 'True', 'return', 'False'] | 918,870 |
openvinotoolkit/training_extensions | dataset_utils.py | add_saliency_maps_to_dataset_item | add_saliency_maps_to_dataset_item | Add saliency maps (2D array for class-agnostic saliency map, 3D array or list or 2D arrays for class-wise saliency maps) to a single dataset item. | [
"Add",
"saliency",
"maps",
"(2D",
"array",
"for",
"class-agnostic",
"saliency",
"map,",
"3D",
"array",
"or",
"list",
"or",
"2D",
"arrays",
"for",
"class-wise",
"saliency",
"maps)",
"to",
"a",
"single",
"dataset",
"item."
] | def add_saliency_maps_to_dataset_item(dataset_item: DatasetItemEntity, saliency_map: Union[List[Optional[np.ndarray]], np.ndarray], model: Optional[ModelEntity], labels: List[LabelEntity], predicted_scored_labels: Optional[List[ScoredLabel]]=None, explain_predicted_classes: bool=True, process_saliency_maps: bool=False)... | ['def', 'add_saliency_maps_to_dataset_item(dataset_item:', 'DatasetItemEntity,', 'saliency_map:', 'Union[List[Optional[np.ndarray]],', 'np.ndarray],', 'model:', 'Optional[ModelEntity],', 'labels:', 'List[LabelEntity],', 'predicted_scored_labels:', 'Optional[List[ScoredLabel]]=None,', 'explain_predicted_classes:', 'bool... | 918,871 |
openvinotoolkit/training_extensions | detection_utils.py | detection2array | detection2array | Convert list of OpenVINO Detection to a numpy array. | [
"Convert",
"list",
"of",
"OpenVINO",
"Detection",
"to",
"a",
"numpy",
"array."
] | def detection2array(detections: List) -> np.ndarray:
scores = np.empty((0, 1), dtype=np.float32)
labels = np.empty((0, 1), dtype=np.uint32)
boxes = np.empty((0, 4), dtype=np.float32)
for det in detections:
if (det.xmax - det.xmin) * (det.ymax - det.ymin) < 1.0:
continue
score... | ['def', 'detection2array(detections:', 'List)', '->', 'np.ndarray:', 'scores', '=', 'np.empty((0,', '1),', 'dtype=np.float32)', 'labels', '=', 'np.empty((0,', '1),', 'dtype=np.uint32)', 'boxes', '=', 'np.empty((0,', '4),', 'dtype=np.float32)', 'for', 'det', 'in', 'detections:', 'if', '(det.xmax', '-', 'det.xmin)', '*',... | 918,873 |
openvinotoolkit/training_extensions | labels_utils.py | get_empty_label | get_empty_label | Get first empty label from label_schema. | [
"Get",
"first",
"empty",
"label",
"from",
"label_schema."
] | def get_empty_label(label_schema: LabelSchemaEntity) -> Optional[LabelEntity]:
empty_candidates = list(set(label_schema.get_labels(include_empty=True)) - set(label_schema.get_labels(include_empty=False)))
if empty_candidates:
return empty_candidates[0]
return None | ['def', 'get_empty_label(label_schema:', 'LabelSchemaEntity)', '->', 'Optional[LabelEntity]:', 'empty_candidates', '=', 'list(set(label_schema.get_labels(include_empty=True))', '-', 'set(label_schema.get_labels(include_empty=False)))', 'if', 'empty_candidates:', 'return', 'empty_candidates[0]', 'return', 'None'] | 918,875 |
openvinotoolkit/training_extensions | segmentation_utils.py | create_hard_prediction_from_soft_prediction | create_hard_prediction_from_soft_prediction | Creates a hard prediction containing the final label index per pixel. | [
"Creates",
"a",
"hard",
"prediction",
"containing",
"the",
"final",
"label",
"index",
"per",
"pixel."
] | def create_hard_prediction_from_soft_prediction(soft_prediction: np.ndarray, soft_threshold: float, blur_strength: int=5) -> np.ndarray:
soft_prediction_blurred = cv2.blur(soft_prediction, (blur_strength, blur_strength))
if len(soft_prediction.shape) == 3:
soft_prediction_blurred[soft_prediction_blurred... | ['def', 'create_hard_prediction_from_soft_prediction(soft_prediction:', 'np.ndarray,', 'soft_threshold:', 'float,', 'blur_strength:', 'int=5)', '->', 'np.ndarray:', 'soft_prediction_blurred', '=', 'cv2.blur(soft_prediction,', '(blur_strength,', 'blur_strength))', 'if', 'len(soft_prediction.shape)', '==', '3:', 'soft_pr... | 918,881 |
openvinotoolkit/training_extensions | segmentation_utils.py | get_subcontours | get_subcontours | Splits contour into subcontours that do not have self intersections. | [
"Splits",
"contour",
"into",
"subcontours",
"that",
"do",
"not",
"have",
"self",
"intersections."
] | def get_subcontours(contour: Contour) -> List[Contour]:
ContourInternal = List[Optional[Tuple[float, float]]]
def find_loops(points: ContourInternal) -> List[Sequence[int]]:
(_, inverse, count) = np.unique(points, axis=0, return_inverse=True, return_counts=True)
duplicates = np.where(count > 1)... | ['def', 'get_subcontours(contour:', 'Contour)', '->', 'List[Contour]:', 'ContourInternal', '=', 'List[Optional[Tuple[float,', 'float]]]', 'def', 'find_loops(points:', 'ContourInternal)', '->', 'List[Sequence[int]]:', '(_,', 'inverse,', 'count)', '=', 'np.unique(points,', 'axis=0,', 'return_inverse=True,', 'return_count... | 918,882 |
openvinotoolkit/training_extensions | shape_drawer.py | DrawerEntity.draw | draw | Draw an entity to a given frame. | [
"Draw",
"an",
"entity",
"to",
"a",
"given",
"frame."
] | def draw(self, image: np.ndarray, entity: _Any, labels: List[ScoredLabel]) -> np.ndarray:
raise NotImplementedError | ['def', 'draw(self,', 'image:', 'np.ndarray,', 'entity:', '_Any,', 'labels:', 'List[ScoredLabel])', '->', 'np.ndarray:', 'raise', 'NotImplementedError'] | 918,884 |
openvinotoolkit/training_extensions | shape_drawer.py | Helpers.draw_transparent_rectangle | draw_transparent_rectangle | Draw a rectangle on an image. | [
"Draw",
"a",
"rectangle",
"on",
"an",
"image."
] | def draw_transparent_rectangle(img: np.ndarray, x1: int, y1: int, x2: int, y2: int, color: Tuple[int, int, int], alpha: float) -> np.ndarray:
x1 = np.clip(x1, 0, img.shape[1] - 1)
y1 = np.clip(y1, 0, img.shape[0] - 1)
x2 = np.clip(x2 + 1, 0, img.shape[1] - 1)
y2 = np.clip(y2 + 1, 0, img.shape[0] - 1)
... | ['def', 'draw_transparent_rectangle(img:', 'np.ndarray,', 'x1:', 'int,', 'y1:', 'int,', 'x2:', 'int,', 'y2:', 'int,', 'color:', 'Tuple[int,', 'int,', 'int],', 'alpha:', 'float)', '->', 'np.ndarray:', 'x1', '=', 'np.clip(x1,', '0,', 'img.shape[1]', '-', '1)', 'y1', '=', 'np.clip(y1,', '0,', 'img.shape[0]', '-', '1)', 'x... | 918,885 |
openvinotoolkit/training_extensions | shape_drawer.py | Helpers.generate_text_scale | generate_text_scale | Calculates the scale of the text. | [
"Calculates",
"the",
"scale",
"of",
"the",
"text."
] | def generate_text_scale(self, image: np.ndarray) -> float:
return round(image.shape[1] / self.assumed_image_width_for_text_scale, 1) | ['def', 'generate_text_scale(self,', 'image:', 'np.ndarray)', '->', 'float:', 'return', 'round(image.shape[1]', '/', 'self.assumed_image_width_for_text_scale,', '1)'] | 918,886 |
openvinotoolkit/training_extensions | shape_drawer.py | Helpers.draw_flagpole | draw_flagpole | Draw a small flagpole between two points. | [
"Draw",
"a",
"small",
"flagpole",
"between",
"two",
"points."
] | def draw_flagpole(image: np.ndarray, flagpole_start_point: Coordinate, flagpole_end_point: Coordinate):
return cv2.line(image, flagpole_start_point.as_int_tuple(), flagpole_end_point.as_int_tuple(), color=[0, 0, 0], thickness=2) | ['def', 'draw_flagpole(image:', 'np.ndarray,', 'flagpole_start_point:', 'Coordinate,', 'flagpole_end_point:', 'Coordinate):', 'return', 'cv2.line(image,', 'flagpole_start_point.as_int_tuple(),', 'flagpole_end_point.as_int_tuple(),', 'color=[0,', '0,', '0],', 'thickness=2)'] | 918,890 |
openvinotoolkit/training_extensions | shape_drawer.py | ShapeDrawer.TopLeftDrawer.draw | draw | Draw the labels of a shape in the image top left corner. | [
"Draw",
"the",
"labels",
"of",
"a",
"shape",
"in",
"the",
"image",
"top",
"left",
"corner."
] | def draw(self, image: np.ndarray, entity: Annotation, labels: List[ScoredLabel]) -> np.ndarray:
return self.draw_labels(image, entity.get_labels()) | ['def', 'draw(self,', 'image:', 'np.ndarray,', 'entity:', 'Annotation,', 'labels:', 'List[ScoredLabel])', '->', 'np.ndarray:', 'return', 'self.draw_labels(image,', 'entity.get_labels())'] | 918,893 |
openvinotoolkit/training_extensions | shape_drawer.py | ShapeDrawer.TopLeftDrawer.draw_labels | draw_labels | Draw the labels in the image top left corner. | [
"Draw",
"the",
"labels",
"in",
"the",
"image",
"top",
"left",
"corner."
] | def draw_labels(self, image: np.ndarray, labels: Sequence[Union[LabelEntity, ScoredLabel]]) -> np.ndarray:
show_confidence = self.show_confidence if not self.is_one_label else False
(draw_command, _, _) = self.generate_draw_command_for_labels(labels, image, self.show_labels, show_confidence)
image = draw_co... | ['def', 'draw_labels(self,', 'image:', 'np.ndarray,', 'labels:', 'Sequence[Union[LabelEntity,', 'ScoredLabel]])', '->', 'np.ndarray:', 'show_confidence', '=', 'self.show_confidence', 'if', 'not', 'self.is_one_label', 'else', 'False', '(draw_command,', '_,', '_)', '=', 'self.generate_draw_command_for_labels(labels,', 'i... | 918,894 |
openvinotoolkit/training_extensions | shape_drawer.py | ShapeDrawer.RectangleDrawer.draw | draw | Draws a rectangle on the image along with labels. | [
"Draws",
"a",
"rectangle",
"on",
"the",
"image",
"along",
"with",
"labels."
] | def draw(self, image: np.ndarray, entity: Rectangle, labels: List[ScoredLabel]) -> np.ndarray:
base_color = labels[0].color.bgr_tuple
(x1, y1) = (int(entity.x1 * image.shape[1]), int(entity.y1 * image.shape[0]))
(x2, y2) = (int(entity.x2 * image.shape[1]), int(entity.y2 * image.shape[0]))
image = self.d... | ['def', 'draw(self,', 'image:', 'np.ndarray,', 'entity:', 'Rectangle,', 'labels:', 'List[ScoredLabel])', '->', 'np.ndarray:', 'base_color', '=', 'labels[0].color.bgr_tuple', '(x1,', 'y1)', '=', '(int(entity.x1', '*', 'image.shape[1]),', 'int(entity.y1', '*', 'image.shape[0]))', '(x2,', 'y2)', '=', '(int(entity.x2', '*'... | 918,896 |
openvinotoolkit/training_extensions | shape_drawer.py | ShapeDrawer.PolygonDrawer.draw | draw | Draw polygon and labels on image. | [
"Draw",
"polygon",
"and",
"labels",
"on",
"image."
] | def draw(self, image: np.ndarray, entity: Polygon, labels: List[ScoredLabel]) -> np.ndarray:
base_color = labels[0].color.bgr_tuple
alpha = self.alpha_shape
contours = np.array([[point.x * image.shape[1], point.y * image.shape[0]] for point in entity.points], dtype=np.int32)
overlay = cv2.drawContours(i... | ['def', 'draw(self,', 'image:', 'np.ndarray,', 'entity:', 'Polygon,', 'labels:', 'List[ScoredLabel])', '->', 'np.ndarray:', 'base_color', '=', 'labels[0].color.bgr_tuple', 'alpha', '=', 'self.alpha_shape', 'contours', '=', 'np.array([[point.x', '*', 'image.shape[1],', 'point.y', '*', 'image.shape[0]]', 'for', 'point', ... | 918,898 |
openvinotoolkit/training_extensions | time_utils.py | TimeEstimator.time_remaining_from_progress | time_remaining_from_progress | Updates the current progress, and returns the estimated remaining time in seconds (float). | [
"Updates",
"the",
"current",
"progress,",
"and",
"returns",
"the",
"estimated",
"remaining",
"time",
"in",
"seconds",
"(float)."
] | def time_remaining_from_progress(self, progress: float) -> float:
estimation = -1.0
if progress is not None and progress > 0:
self.update(progress)
estimation = self.get_time_remaining()
return estimation | ['def', 'time_remaining_from_progress(self,', 'progress:', 'float)', '->', 'float:', 'estimation', '=', '-1.0', 'if', 'progress', 'is', 'not', 'None', 'and', 'progress', '>', '0:', 'self.update(progress)', 'estimation', '=', 'self.get_time_remaining()', 'return', 'estimation'] | 918,905 |
openvinotoolkit/training_extensions | vis_utils.py | dump_frames | dump_frames | Saves images/videos with predictions from saved_frames to output folder with proper names. | [
"Saves",
"images/videos",
"with",
"predictions",
"from",
"saved_frames",
"to",
"output",
"folder",
"with",
"proper",
"names."
] | def dump_frames(saved_frames: list, output: str, input_path: Union[str, int], capture):
if not saved_frames:
return
output_path = Path(output)
if not output_path.exists():
output_path.mkdir(parents=True)
filenames = get_input_names_list(input_path, capture)
if 'VIDEO' in str(capture.... | ['def', 'dump_frames(saved_frames:', 'list,', 'output:', 'str,', 'input_path:', 'Union[str,', 'int],', 'capture):', 'if', 'not', 'saved_frames:', 'return', 'output_path', '=', 'Path(output)', 'if', 'not', 'output_path.exists():', 'output_path.mkdir(parents=True)', 'filenames', '=', 'get_input_names_list(input_path,', '... | 918,910 |
openvinotoolkit/training_extensions | builder.py | get_backbone_out_channels | get_backbone_out_channels | Get output channels of backbone using fake data. | [
"Get",
"output",
"channels",
"of",
"backbone",
"using",
"fake",
"data."
] | def get_backbone_out_channels(backbone: nn.Module):
out_channels = []
input_size = backbone.input_size if hasattr(backbone, 'input_size') else 64
fake_data = torch.rand(2, 3, input_size, input_size)
outputs = backbone(fake_data)
for out in outputs:
out_channels.append(out.shape[1])
retur... | ['def', 'get_backbone_out_channels(backbone:', 'nn.Module):', 'out_channels', '=', '[]', 'input_size', '=', 'backbone.input_size', 'if', 'hasattr(backbone,', "'input_size')", 'else', '64', 'fake_data', '=', 'torch.rand(2,', '3,', 'input_size,', 'input_size)', 'outputs', '=', 'backbone(fake_data)', 'for', 'out', 'in', '... | 918,911 |
openvinotoolkit/training_extensions | builder.py | update_channels | update_channels | Update in_channel of head or neck. | [
"Update",
"in_channel",
"of",
"head",
"or",
"neck."
] | def update_channels(model_config: OTXConfig, out_channels: Any):
if hasattr(model_config.model, 'neck') and model_config.model.neck:
if model_config.model.neck.get('type', None) == 'GlobalAveragePooling':
model_config.model.neck.pop('in_channels', None)
else:
print(f'\tUpdate... | ['def', 'update_channels(model_config:', 'OTXConfig,', 'out_channels:', 'Any):', 'if', 'hasattr(model_config.model,', "'neck')", 'and', 'model_config.model.neck:', 'if', "model_config.model.neck.get('type',", 'None)', '==', "'GlobalAveragePooling':", "model_config.model.neck.pop('in_channels',", 'None)', 'else:', "prin... | 918,913 |
openvinotoolkit/training_extensions | config_manager.py | ConfigManager.configure_template | configure_template | Update the template appropriate for the situation. | [
"Update",
"the",
"template",
"appropriate",
"for",
"the",
"situation."
] | def configure_template(self, model: str=None) -> None:
if self.check_workspace():
self.template = parse_model_template(str(self.workspace_root / 'template.yaml'))
if self.mode == 'build' and self._check_rebuild():
self.rebuild = True
model = model if model else self.template.... | ['def', 'configure_template(self,', 'model:', 'str=None)', '->', 'None:', 'if', 'self.check_workspace():', 'self.template', '=', 'parse_model_template(str(self.workspace_root', '/', "'template.yaml'))", 'if', 'self.mode', '==', "'build'", 'and', 'self._check_rebuild():', 'self.rebuild', '=', 'True', 'model', '=', 'mode... | 918,920 |
openvinotoolkit/training_extensions | config_manager.py | ConfigManager.auto_task_detection | auto_task_detection | Detect task type automatically. | [
"Detect",
"task",
"type",
"automatically."
] | def auto_task_detection(self, data_roots: str) -> str:
if not data_roots:
raise CliException('Workspace must already exist or one of {task or model or train-data-roots} must exist.')
self.data_format = self.dataset_manager.get_data_format(data_roots)
return self._get_task_type_from_data_format(self.... | ['def', 'auto_task_detection(self,', 'data_roots:', 'str)', '->', 'str:', 'if', 'not', 'data_roots:', 'raise', "CliException('Workspace", 'must', 'already', 'exist', 'or', 'one', 'of', '{task', 'or', 'model', 'or', 'train-data-roots}', 'must', "exist.')", 'self.data_format', '=', 'self.dataset_manager.get_data_format(d... | 918,922 |
openvinotoolkit/training_extensions | config_manager.py | ConfigManager.auto_split_data | auto_split_data | Automatically Split train data --> train/val dataset. | [
"Automatically",
"Split",
"train",
"data",
"-->",
"train/val",
"dataset."
] | def auto_split_data(self, data_roots: str, task: str, ann_file: Optional[str]=None):
self.data_format = self.dataset_manager.get_data_format(data_roots)
dataset = self.dataset_manager.import_dataset(data_root=data_roots, data_format=self.data_format)
train_dataset = self.dataset_manager.get_train_dataset(da... | ['def', 'auto_split_data(self,', 'data_roots:', 'str,', 'task:', 'str,', 'ann_file:', 'Optional[str]=None):', 'self.data_format', '=', 'self.dataset_manager.get_data_format(data_roots)', 'dataset', '=', 'self.dataset_manager.import_dataset(data_root=data_roots,', 'data_format=self.data_format)', 'train_dataset', '=', '... | 918,923 |
openvinotoolkit/training_extensions | config_manager.py | ConfigManager.get_dataset_config | get_dataset_config | Returns dataset_config in a format suitable for each subset. | [
"Returns",
"dataset_config",
"in",
"a",
"format",
"suitable",
"for",
"each",
"subset."
] | def get_dataset_config(self, subsets: List[str], hyper_parameters: Optional[ConfigurableParameters]=None) -> dict:
if str(self.train_type).upper() == 'INCREMENTAL' and 'unlabeled' in subsets:
subsets.remove('unlabeled')
dataset_config: Dict[str, Any] = {'task_type': self.task_type, 'train_type': self.tr... | ['def', 'get_dataset_config(self,', 'subsets:', 'List[str],', 'hyper_parameters:', 'Optional[ConfigurableParameters]=None)', '->', 'dict:', 'if', 'str(self.train_type).upper()', '==', "'INCREMENTAL'", 'and', "'unlabeled'", 'in', 'subsets:', "subsets.remove('unlabeled')", 'dataset_config:', 'Dict[str,', 'Any]', '=', "{'... | 918,925 |
openvinotoolkit/training_extensions | config_manager.py | ConfigManager.update_data_config | update_data_config | Convert the data yaml format to the data_config format consumed by the task. | [
"Convert",
"the",
"data",
"yaml",
"format",
"to",
"the",
"data_config",
"format",
"consumed",
"by",
"the",
"task."
] | def update_data_config(self, data_yaml: dict) -> None:
if 'data-roots' in data_yaml['data']['train']:
self.data_config['train_subset'] = {'data_roots': data_yaml['data']['train']['data-roots']}
if 'ann-files' in data_yaml['data']['train']:
self.data_config['train_subset']['ann_files'] = ... | ['def', 'update_data_config(self,', 'data_yaml:', 'dict)', '->', 'None:', 'if', "'data-roots'", 'in', "data_yaml['data']['train']:", "self.data_config['train_subset']", '=', "{'data_roots':", "data_yaml['data']['train']['data-roots']}", 'if', "'ann-files'", 'in', "data_yaml['data']['train']:", "self.data_config['train_... | 918,926 |
openvinotoolkit/training_extensions | registry.py | is_template | is_template | A function that determines whether the corresponding template path is a template. | [
"A",
"function",
"that",
"determines",
"whether",
"the",
"corresponding",
"template",
"path",
"is",
"a",
"template."
] | def is_template(template_path: Optional[str]) -> bool:
if template_path and Path(template_path).is_file() and ('template' in Path(template_path).name):
return True
return False | ['def', 'is_template(template_path:', 'Optional[str])', '->', 'bool:', 'if', 'template_path', 'and', 'Path(template_path).is_file()', 'and', "('template'", 'in', 'Path(template_path).name):', 'return', 'True', 'return', 'False'] | 918,930 |
openvinotoolkit/training_extensions | registry.py | Registry.filter | filter | Filters registry by framework and/or task type and returns filtered registry. | [
"Filters",
"registry",
"by",
"framework",
"and/or",
"task",
"type",
"and",
"returns",
"filtered",
"registry."
] | def filter(self, framework=None, task_type=None):
templates = copy.deepcopy(self.templates)
if framework is not None:
templates = [template for template in templates if template.framework.lower() == framework.lower()]
if task_type is not None:
templates = [template for template in templates ... | ['def', 'filter(self,', 'framework=None,', 'task_type=None):', 'templates', '=', 'copy.deepcopy(self.templates)', 'if', 'framework', 'is', 'not', 'None:', 'templates', '=', '[template', 'for', 'template', 'in', 'templates', 'if', 'template.framework.lower()', '==', 'framework.lower()]', 'if', 'task_type', 'is', 'not', ... | 918,931 |
openvinotoolkit/training_extensions | registry.py | Registry.get_backbones | get_backbones | Returns list of backbones for a given template. | [
"Returns",
"list",
"of",
"backbones",
"for",
"a",
"given",
"template."
] | def get_backbones(self, backend_list):
backbone_list = {}
for backend in backend_list:
backbone_list[backend] = get_backbone_list(backend)
return backbone_list | ['def', 'get_backbones(self,', 'backend_list):', 'backbone_list', '=', '{}', 'for', 'backend', 'in', 'backend_list:', 'backbone_list[backend]', '=', 'get_backbone_list(backend)', 'return', 'backbone_list'] | 918,933 |
openvinotoolkit/training_extensions | images_capture.py | ImagesCapture.get_type | get_type | Returns type of image capture. | [
"Returns",
"type",
"of",
"image",
"capture."
] | def get_type(self):
raise NotImplementedError | ['def', 'get_type(self):', 'raise', 'NotImplementedError'] | 918,949 |
openvinotoolkit/training_extensions | visualization.py | draw_masks | draw_masks | Converts predictions to masks and draw them on frame. | [
"Converts",
"predictions",
"to",
"masks",
"and",
"draw",
"them",
"on",
"frame."
] | def draw_masks(frame: Mat, predictions, put_object_count: bool=False):
frame = frame.copy()
(height, width) = (frame.shape[0], frame.shape[1])
segments_image = frame.copy()
aggregated_mask = np.zeros(frame.shape[:2], dtype=np.uint8)
aggregated_colored_mask = np.zeros(frame.shape, dtype=np.uint8)
... | ['def', 'draw_masks(frame:', 'Mat,', 'predictions,', 'put_object_count:', 'bool=False):', 'frame', '=', 'frame.copy()', '(height,', 'width)', '=', '(frame.shape[0],', 'frame.shape[1])', 'segments_image', '=', 'frame.copy()', 'aggregated_mask', '=', 'np.zeros(frame.shape[:2],', 'dtype=np.uint8)', 'aggregated_colored_mas... | 918,959 |
openvinotoolkit/training_extensions | config.py | override_parameters | override_parameters | Overrides parameters values by overrides. | [
"Overrides",
"parameters",
"values",
"by",
"overrides."
] | def override_parameters(overrides, parameters):
allowed_keys = {'default_value', 'value'}
for (k, val) in overrides.items():
if isinstance(val, dict):
if k in parameters.keys():
override_parameters(val, parameters[k])
else:
raise ValueError(f'The "... | ['def', 'override_parameters(overrides,', 'parameters):', 'allowed_keys', '=', "{'default_value',", "'value'}", 'for', '(k,', 'val)', 'in', 'overrides.items():', 'if', 'isinstance(val,', 'dict):', 'if', 'k', 'in', 'parameters.keys():', 'override_parameters(val,', 'parameters[k])', 'else:', 'raise', "ValueError(f'The", ... | 918,963 |
openvinotoolkit/training_extensions | experiment.py | ResourceTracker.start | start | Run a process which tracks resources usage. | [
"Run",
"a",
"process",
"which",
"tracks",
"resources",
"usage."
] | def start(self):
if self._mem_check_proc is not None:
logger.warning('Resource tracker started already. Please execute start after executing stop.')
return
self._queue = mp.Queue()
self._mem_check_proc = mp.Process(target=_check_resource, args=(self._queue, self._resource_type, self._gpu_ids... | ['def', 'start(self):', 'if', 'self._mem_check_proc', 'is', 'not', 'None:', "logger.warning('Resource", 'tracker', 'started', 'already.', 'Please', 'execute', 'start', 'after', 'executing', "stop.')", 'return', 'self._queue', '=', 'mp.Queue()', 'self._mem_check_proc', '=', 'mp.Process(target=_check_resource,', 'args=(s... | 918,964 |
openvinotoolkit/training_extensions | experiment.py | ResourceTracker.stop | stop | Terminate a process to record resources usage. | [
"Terminate",
"a",
"process",
"to",
"record",
"resources",
"usage."
] | def stop(self, output_path: Union[str, Path]):
if self._mem_check_proc is None or not self._mem_check_proc.is_alive():
return
if isinstance(output_path, str):
output_path = Path(output_path)
self._queue.put(output_path)
self._mem_check_proc.join(10)
if self._mem_check_proc.exitcode i... | ['def', 'stop(self,', 'output_path:', 'Union[str,', 'Path]):', 'if', 'self._mem_check_proc', 'is', 'None', 'or', 'not', 'self._mem_check_proc.is_alive():', 'return', 'if', 'isinstance(output_path,', 'str):', 'output_path', '=', 'Path(output_path)', 'self._queue.put(output_path)', 'self._mem_check_proc.join(10)', 'if', ... | 918,965 |
openvinotoolkit/training_extensions | experiment.py | ResourceRecorder.record | record | Record a resource usage. | [
"Record",
"a",
"resource",
"usage."
] | def record(self):
raise NotImplementedError | ['def', 'record(self):', 'raise', 'NotImplementedError'] | 918,966 |
openvinotoolkit/training_extensions | experiment.py | ResourceRecorder.report | report | Aggregate all resource usages. | [
"Aggregate",
"all",
"resource",
"usages."
] | def report(self):
raise NotImplementedError | ['def', 'report(self):', 'raise', 'NotImplementedError'] | 918,967 |
openvinotoolkit/training_extensions | hpo.py | TaskManager.copy_weight | copy_weight | Copy all model weights from work directory. | [
"Copy",
"all",
"model",
"weights",
"from",
"work",
"directory."
] | def copy_weight(self, src: Union[str, Path], det: Union[str, Path]):
src = Path(src)
det = Path(det)
if self.is_mmcv_framework_task():
for weight_candidate in src.rglob('*epoch*.pth'):
if not (weight_candidate.is_symlink() or (det / weight_candidate.name).exists()):
shuti... | ['def', 'copy_weight(self,', 'src:', 'Union[str,', 'Path],', 'det:', 'Union[str,', 'Path]):', 'src', '=', 'Path(src)', 'det', '=', 'Path(det)', 'if', 'self.is_mmcv_framework_task():', 'for', 'weight_candidate', 'in', "src.rglob('*epoch*.pth'):", 'if', 'not', '(weight_candidate.is_symlink()', 'or', '(det', '/', 'weight_... | 918,978 |
openvinotoolkit/training_extensions | hpo.py | TaskManager.get_latest_weight | get_latest_weight | Get latest model weight from all weights. | [
"Get",
"latest",
"model",
"weight",
"from",
"all",
"weights."
] | def get_latest_weight(self, workdir: Union[str, Path]) -> Optional[str]:
latest_weight = None
workdir = Path(workdir)
if self.is_mmcv_framework_task():
pattern = re.compile('(\\d+)\\.pth')
current_latest_epoch = -1
latest_weight = None
for weight_name in workdir.rglob('epoch_... | ['def', 'get_latest_weight(self,', 'workdir:', 'Union[str,', 'Path])', '->', 'Optional[str]:', 'latest_weight', '=', 'None', 'workdir', '=', 'Path(workdir)', 'if', 'self.is_mmcv_framework_task():', 'pattern', '=', "re.compile('(\\\\d+)\\\\.pth')", 'current_latest_epoch', '=', '-1', 'latest_weight', '=', 'None', 'for', ... | 918,979 |
openvinotoolkit/training_extensions | hpo.py | TaskEnvironmentManager.set_epoch | set_epoch | Set epoch on environment. | [
"Set",
"epoch",
"on",
"environment."
] | def set_epoch(self, epoch: int):
hyper_parameter = {f'learning_parameters.{self.task.get_epoch_name()}': epoch}
self.set_hyper_parameter_using_str_key(hyper_parameter) | ['def', 'set_epoch(self,', 'epoch:', 'int):', 'hyper_parameter', '=', "{f'learning_parameters.{self.task.get_epoch_name()}':", 'epoch}', 'self.set_hyper_parameter_using_str_key(hyper_parameter)'] | 918,991 |
openvinotoolkit/training_extensions | hpo.py | HpoRunner.run_hpo | run_hpo | Run HPO and provides optimized hyper parameters. | [
"Run",
"HPO",
"and",
"provides",
"optimized",
"hyper",
"parameters."
] | def run_hpo(self, train_func: Callable, data_roots: Dict[str, Dict]) -> Union[Dict[str, Any], None]:
self._environment.save_initial_weight(self._get_initial_model_weight_path())
hpo_algo = self._get_hpo_algo()
resource_type = 'gpu' if torch.cuda.is_available() else 'cpu'
run_hpo_loop(hpo_algo, partial(t... | ['def', 'run_hpo(self,', 'train_func:', 'Callable,', 'data_roots:', 'Dict[str,', 'Dict])', '->', 'Union[Dict[str,', 'Any],', 'None]:', 'self._environment.save_initial_weight(self._get_initial_model_weight_path())', 'hpo_algo', '=', 'self._get_hpo_algo()', 'resource_type', '=', "'gpu'", 'if', 'torch.cuda.is_available()'... | 918,992 |
openvinotoolkit/training_extensions | hpo.py | Trainer.run | run | Run each training of each trial with given hyper parameters. | [
"Run",
"each",
"training",
"of",
"each",
"trial",
"with",
"given",
"hyper",
"parameters."
] | def run(self):
hyper_parameters = self._prepare_hyper_parameter()
dataset_adapter = self._prepare_dataset_adapter()
dataset = dataset_adapter.get_otx_dataset()
dataset = HpoDataset(dataset, self._hp_config)
label_schema = dataset_adapter.get_label_schema()
environment = self._prepare_environment... | ['def', 'run(self):', 'hyper_parameters', '=', 'self._prepare_hyper_parameter()', 'dataset_adapter', '=', 'self._prepare_dataset_adapter()', 'dataset', '=', 'dataset_adapter.get_otx_dataset()', 'dataset', '=', 'HpoDataset(dataset,', 'self._hp_config)', 'label_schema', '=', 'dataset_adapter.get_label_schema()', 'environ... | 918,993 |
openvinotoolkit/training_extensions | hpo.py | HpoDataset.get_subset | get_subset | Get subset according to subset_ratio if training dataset is requested. | [
"Get",
"subset",
"according",
"to",
"subset_ratio",
"if",
"training",
"dataset",
"is",
"requested."
] | def get_subset(self, subset: Subset):
dataset = self.fullset.get_subset(subset)
if subset != Subset.TRAINING or self.subset_ratio > 0.99:
return dataset
indices = torch.randperm(len(dataset), generator=torch.Generator().manual_seed(42))
indices = indices.tolist()
indices = indices[:int(len(d... | ['def', 'get_subset(self,', 'subset:', 'Subset):', 'dataset', '=', 'self.fullset.get_subset(subset)', 'if', 'subset', '!=', 'Subset.TRAINING', 'or', 'self.subset_ratio', '>', '0.99:', 'return', 'dataset', 'indices', '=', 'torch.randperm(len(dataset),', 'generator=torch.Generator().manual_seed(42))', 'indices', '=', 'in... | 918,994 |
openvinotoolkit/training_extensions | importing.py | get_backbone_list | get_backbone_list | Gather available backbone list from json file & imported lib. | [
"Gather",
"available",
"backbone",
"list",
"from",
"json",
"file",
"&",
"imported",
"lib."
] | def get_backbone_list(backend):
available_backbone_path = os.path.join(get_otx_root_path(), f'cli/builder/supported_backbone/{backend}.json')
available_backbones = {}
if os.path.exists(available_backbone_path):
with open(available_backbone_path, 'r', encoding='UTF-8') as f:
available_bac... | ['def', 'get_backbone_list(backend):', 'available_backbone_path', '=', 'os.path.join(get_otx_root_path(),', "f'cli/builder/supported_backbone/{backend}.json')", 'available_backbones', '=', '{}', 'if', 'os.path.exists(available_backbone_path):', 'with', 'open(available_backbone_path,', "'r',", "encoding='UTF-8')", 'as',... | 918,996 |
openvinotoolkit/training_extensions | importing.py | get_module_args | get_module_args | Gather module's Required Args. | [
"Gather",
"module's",
"Required",
"Args."
] | def get_module_args(module):
if module is None:
return []
required_args = []
default_args = {}
args_signature = inspect.signature(module)
for (arg_key, arg_value) in args_signature.parameters.items():
if arg_value.default is inspect.Parameter.empty:
required_args.append(a... | ['def', 'get_module_args(module):', 'if', 'module', 'is', 'None:', 'return', '[]', 'required_args', '=', '[]', 'default_args', '=', '{}', 'args_signature', '=', 'inspect.signature(module)', 'for', '(arg_key,', 'arg_value)', 'in', 'args_signature.parameters.items():', 'if', 'arg_value.default', 'is', 'inspect.Parameter.... | 918,998 |
openvinotoolkit/training_extensions | importing.py | get_otx_root_path | get_otx_root_path | Get otx root path from importing otx. | [
"Get",
"otx",
"root",
"path",
"from",
"importing",
"otx."
] | def get_otx_root_path():
otx_module = importlib.import_module('otx')
if otx_module:
return os.path.dirname(inspect.getfile(otx_module))
return None | ['def', 'get_otx_root_path():', 'otx_module', '=', "importlib.import_module('otx')", 'if', 'otx_module:', 'return', 'os.path.dirname(inspect.getfile(otx_module))', 'return', 'None'] | 918,999 |
openvinotoolkit/training_extensions | io.py | read_binary | read_binary | Loads binary data stored at path. | [
"Loads",
"binary",
"data",
"stored",
"at",
"path."
] | def read_binary(path: str) -> bytes:
try:
with open(path, 'rb') as read_file:
return read_file.read()
except FileNotFoundError:
return b'' | ['def', 'read_binary(path:', 'str)', '->', 'bytes:', 'try:', 'with', 'open(path,', "'rb')", 'as', 'read_file:', 'return', 'read_file.read()', 'except', 'FileNotFoundError:', 'return', "b''"] | 919,001 |
openvinotoolkit/training_extensions | io.py | read_model | read_model | Creates ModelEntity based on model_configuration and data stored at path. | [
"Creates",
"ModelEntity",
"based",
"on",
"model_configuration",
"and",
"data",
"stored",
"at",
"path."
] | def read_model(model_configuration: ModelConfiguration, path: str, train_dataset: DatasetEntity) -> ModelEntity:
if path.endswith('.bin') or path.endswith('.xml'):
return read_openvino_model(model_configuration, path, train_dataset)
if path.endswith('.pth'):
return read_pytorch_model(model_confi... | ['def', 'read_model(model_configuration:', 'ModelConfiguration,', 'path:', 'str,', 'train_dataset:', 'DatasetEntity)', '->', 'ModelEntity:', 'if', "path.endswith('.bin')", 'or', "path.endswith('.xml'):", 'return', 'read_openvino_model(model_configuration,', 'path,', 'train_dataset)', 'if', "path.endswith('.pth'):", 're... | 919,002 |
openvinotoolkit/training_extensions | io.py | read_pytorch_model | read_pytorch_model | Reads a PyTorch model from disk and returns a ModelEntity object. | [
"Reads",
"a",
"PyTorch",
"model",
"from",
"disk",
"and",
"returns",
"a",
"ModelEntity",
"object."
] | def read_pytorch_model(model_configuration: ModelConfiguration, path: str, train_dataset: DatasetEntity) -> ModelEntity:
optimization_type = ModelOptimizationType.NONE
model_adapters = {'weights.pth': ModelAdapter(read_binary(path))}
if is_checkpoint_nncf(path):
optimization_type = ModelOptimization... | ['def', 'read_pytorch_model(model_configuration:', 'ModelConfiguration,', 'path:', 'str,', 'train_dataset:', 'DatasetEntity)', '->', 'ModelEntity:', 'optimization_type', '=', 'ModelOptimizationType.NONE', 'model_adapters', '=', "{'weights.pth':", 'ModelAdapter(read_binary(path))}', 'if', 'is_checkpoint_nncf(path):', 'o... | 919,004 |
openvinotoolkit/training_extensions | io.py | get_image_files | get_image_files | Recursively get all image file paths from given root_dir. | [
"Recursively",
"get",
"all",
"image",
"file",
"paths",
"from",
"given",
"root_dir."
] | def get_image_files(root_dir: str) -> Optional[List[Tuple[str, str]]]:
img_data_formats = ('.jpg', '.JPG', '.jpeg', '.JPEG', '.gif', '.GIF', '.bmp', '.BMP', '.tif', '.TIF', '.tiff', '.TIFF', '.png', '.PNG')
if root_dir.endswith(img_data_formats):
return [('./', root_dir)]
img_files = []
for (roo... | ['def', 'get_image_files(root_dir:', 'str)', '->', 'Optional[List[Tuple[str,', 'str]]]:', 'img_data_formats', '=', "('.jpg',", "'.JPG',", "'.jpeg',", "'.JPEG',", "'.gif',", "'.GIF',", "'.bmp',", "'.BMP',", "'.tif',", "'.TIF',", "'.tiff',", "'.TIFF',", "'.png',", "'.PNG')", 'if', 'root_dir.endswith(img_data_formats):', ... | 919,007 |
openvinotoolkit/training_extensions | io.py | get_explain_dataset_from_filelist | get_explain_dataset_from_filelist | Get explain dataset with empty annotation. | [
"Get",
"explain",
"dataset",
"with",
"empty",
"annotation."
] | def get_explain_dataset_from_filelist(image_files: list):
empty_annotation = AnnotationSceneEntity(annotations=[], kind=AnnotationSceneKind.PREDICTION)
items = []
for (root_dir, filename) in image_files:
frame = cv2.imread(osp.join(root_dir, filename))
item = DatasetItemEntity(media=Image(cv... | ['def', 'get_explain_dataset_from_filelist(image_files:', 'list):', 'empty_annotation', '=', 'AnnotationSceneEntity(annotations=[],', 'kind=AnnotationSceneKind.PREDICTION)', 'items', '=', '[]', 'for', '(root_dir,', 'filename)', 'in', 'image_files:', 'frame', '=', 'cv2.imread(osp.join(root_dir,', 'filename))', 'item', '... | 919,009 |
openvinotoolkit/training_extensions | multi_gpu.py | MultiGPUManager.finalize | finalize | Join all child processes. | [
"Join",
"all",
"child",
"processes."
] | def finalize(self):
for p in self._processes:
if p.join(30) is None and p.exitcode is None:
p.kill() | ['def', 'finalize(self):', 'for', 'p', 'in', 'self._processes:', 'if', 'p.join(30)', 'is', 'None', 'and', 'p.exitcode', 'is', 'None:', 'p.kill()'] | 919,015 |
openvinotoolkit/training_extensions | multi_gpu.py | MultiGPUManager.run_child_process | run_child_process | Function for multi GPU child process to execute. | [
"Function",
"for",
"multi",
"GPU",
"child",
"process",
"to",
"execute."
] | def run_child_process(train_func: Callable, output_path: str, rdzv_endpoint: str, rank: int, local_rank: int, gpu_ids: List[int], world_size: int):
mp.set_start_method(method=None, force=True)
gpus_arg_idx = sys.argv.index('--gpus')
for _ in range(2):
sys.argv.pop(gpus_arg_idx)
if '--enable-hpo'... | ['def', 'run_child_process(train_func:', 'Callable,', 'output_path:', 'str,', 'rdzv_endpoint:', 'str,', 'rank:', 'int,', 'local_rank:', 'int,', 'gpu_ids:', 'List[int],', 'world_size:', 'int):', 'mp.set_start_method(method=None,', 'force=True)', 'gpus_arg_idx', '=', "sys.argv.index('--gpus')", 'for', '_', 'in', 'range(2... | 919,017 |
openvinotoolkit/training_extensions | parser.py | gen_param_help | gen_param_help | Generates help for hyper parameters section. | [
"Generates",
"help",
"for",
"hyper",
"parameters",
"section."
] | def gen_param_help(hyper_parameters: Dict) -> Dict:
type_map = {'FLOAT': float, 'INTEGER': int, 'BOOLEAN': bool, 'SELECTABLE': str}
help_keys = ('header', 'type', 'default_value', 'max_value', 'min_value')
def _gen_param_help(prefix: str, cur_params: Dict) -> Dict:
cur_help = {}
for (k, val... | ['def', 'gen_param_help(hyper_parameters:', 'Dict)', '->', 'Dict:', 'type_map', '=', "{'FLOAT':", 'float,', "'INTEGER':", 'int,', "'BOOLEAN':", 'bool,', "'SELECTABLE':", 'str}', 'help_keys', '=', "('header',", "'type',", "'default_value',", "'max_value',", "'min_value')", 'def', '_gen_param_help(prefix:', 'str,', 'cur_... | 919,021 |
openvinotoolkit/training_extensions | parser.py | gen_params_dict_from_args | gen_params_dict_from_args | Generates hyper parameters dict from parsed command line arguments. | [
"Generates",
"hyper",
"parameters",
"dict",
"from",
"parsed",
"command",
"line",
"arguments."
] | def gen_params_dict_from_args(args, override_param: Optional[List]=None, type_hint: Optional[dict]=None) -> Dict[str, dict]:
def _get_leaf_node(curr_dict: Dict[str, dict], curr_key: str):
split_key = curr_key.split('.')
node_key = split_key[0]
if len(split_key) == 1:
return (cur... | ['def', 'gen_params_dict_from_args(args,', 'override_param:', 'Optional[List]=None,', 'type_hint:', 'Optional[dict]=None)', '->', 'Dict[str,', 'dict]:', 'def', '_get_leaf_node(curr_dict:', 'Dict[str,', 'dict],', 'curr_key:', 'str):', 'split_key', '=', "curr_key.split('.')", 'node_key', '=', 'split_key[0]', 'if', 'len(s... | 919,022 |
openvinotoolkit/training_extensions | parser.py | str2bool | str2bool | If input type is string, convert it to boolean. | [
"If",
"input",
"type",
"is",
"string,",
"convert",
"it",
"to",
"boolean."
] | def str2bool(val: Union[str, bool]) -> bool:
if isinstance(val, bool):
return val
if isinstance(val, str):
if val.lower() in ('true', '1'):
return True
if val.lower() in ('false', '0'):
return False
raise argparse.ArgumentTypeError('Boolean value expected.') | ['def', 'str2bool(val:', 'Union[str,', 'bool])', '->', 'bool:', 'if', 'isinstance(val,', 'bool):', 'return', 'val', 'if', 'isinstance(val,', 'str):', 'if', 'val.lower()', 'in', "('true',", "'1'):", 'return', 'True', 'if', 'val.lower()', 'in', "('false',", "'0'):", 'return', 'False', 'raise', "argparse.ArgumentTypeError... | 919,023 |
openvinotoolkit/training_extensions | parser.py | get_override_param | get_override_param | Get override param list from params. | [
"Get",
"override",
"param",
"list",
"from",
"params."
] | def get_override_param(params):
return [f"params.{param[2:].split('=')[0]}" for param in params if param.startswith('--')] | ['def', 'get_override_param(params):', 'return', '[f"params.{param[2:].split(\'=\')[0]}"', 'for', 'param', 'in', 'params', 'if', "param.startswith('--')]"] | 919,026 |
openvinotoolkit/training_extensions | action_dataset_adapter.py | ActionClassificationDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Acion Classification. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Acion",
"Classification."
] | def get_otx_dataset(self) -> DatasetEntity:
label_information = self._prepare_label_information(self.dataset)
self.label_entities = label_information['label_entities']
dataset_items: List[DatasetItemEntity] = []
for (subset, subset_data) in self.dataset.items():
for (_, datumaro_items) in subset... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', 'label_information', '=', 'self._prepare_label_information(self.dataset)', 'self.label_entities', '=', "label_information['label_entities']", 'dataset_items:', 'List[DatasetItemEntity]', '=', '[]', 'for', '(subset,', 'subset_data)', 'in', 'self.dataset.items():',... | 919,030 |
openvinotoolkit/training_extensions | action_dataset_adapter.py | ActionDetectionDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Acion Detection. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Acion",
"Detection."
] | def get_otx_dataset(self) -> DatasetEntity:
label_information = self._prepare_label_information(self.dataset)
self.label_entities = label_information['label_entities']
for label_entity in self.label_entities:
label_entity.id = ID(int(label_entity.id) + 1)
dataset_items: List[DatasetItemEntity] =... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', 'label_information', '=', 'self._prepare_label_information(self.dataset)', 'self.label_entities', '=', "label_information['label_entities']", 'for', 'label_entity', 'in', 'self.label_entities:', 'label_entity.id', '=', 'ID(int(label_entity.id)', '+', '1)', 'datas... | 919,031 |
openvinotoolkit/training_extensions | anomaly_dataset_adapter.py | AnomalyClassificationDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Anomaly classification. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Anomaly",
"classification."
] | def get_otx_dataset(self) -> DatasetEntity:
(normal_label, abnormal_label) = self._prepare_anomaly_label_information()
self.label_entities = [normal_label, abnormal_label]
dataset_items: List[DatasetItemEntity] = []
for (subset, subset_data) in self.dataset.items():
for (_, datumaro_items) in su... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', '(normal_label,', 'abnormal_label)', '=', 'self._prepare_anomaly_label_information()', 'self.label_entities', '=', '[normal_label,', 'abnormal_label]', 'dataset_items:', 'List[DatasetItemEntity]', '=', '[]', 'for', '(subset,', 'subset_data)', 'in', 'self.dataset.... | 919,032 |
openvinotoolkit/training_extensions | anomaly_dataset_adapter.py | AnomalyDetectionDatasetAdapter.get_otx_dataset | get_otx_dataset | Conver DatumaroDataset to DatasetEntity for Anomaly detection. | [
"Conver",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Anomaly",
"detection."
] | def get_otx_dataset(self) -> DatasetEntity:
(normal_label, abnormal_label) = self._prepare_anomaly_label_information()
self.label_entities = [normal_label, abnormal_label]
dataset_items: List[DatasetItemEntity] = []
for (subset, subset_data) in self.dataset.items():
for (_, datumaro_items) in su... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', '(normal_label,', 'abnormal_label)', '=', 'self._prepare_anomaly_label_information()', 'self.label_entities', '=', '[normal_label,', 'abnormal_label]', 'dataset_items:', 'List[DatasetItemEntity]', '=', '[]', 'for', '(subset,', 'subset_data)', 'in', 'self.dataset.... | 919,033 |
openvinotoolkit/training_extensions | base_dataset_adapter.py | BaseDatasetAdapter.datum_media_2_otx_media | datum_media_2_otx_media | Convert Datumaro media to OTX media. | [
"Convert",
"Datumaro",
"media",
"to",
"OTX",
"media."
] | def datum_media_2_otx_media(datumaro_media: DatumMediaElement) -> IMediaEntity:
if isinstance(datumaro_media, DatumImage):
path = getattr(datumaro_media, 'path', None)
size = datumaro_media._size
if path and os.path.exists(path) and (not datumaro_media.is_encrypted):
return Image... | ['def', 'datum_media_2_otx_media(datumaro_media:', 'DatumMediaElement)', '->', 'IMediaEntity:', 'if', 'isinstance(datumaro_media,', 'DatumImage):', 'path', '=', 'getattr(datumaro_media,', "'path',", 'None)', 'size', '=', 'datumaro_media._size', 'if', 'path', 'and', 'os.path.exists(path)', 'and', '(not', 'datumaro_media... | 919,036 |
openvinotoolkit/training_extensions | classification_dataset_adapter.py | ClassificationDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Classification. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Classification."
] | def get_otx_dataset(self) -> DatasetEntity:
label_information = self._prepare_label_information(self.dataset)
self.category_items = label_information['category_items']
self.label_groups = label_information['label_groups']
self.label_entities = label_information['label_entities']
dataset_items = self... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', 'label_information', '=', 'self._prepare_label_information(self.dataset)', 'self.category_items', '=', "label_information['category_items']", 'self.label_groups', '=', "label_information['label_groups']", 'self.label_entities', '=', "label_information['label_enti... | 919,037 |
openvinotoolkit/training_extensions | classification_dataset_adapter.py | SelfSLClassificationDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Self-SL Classification. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Self-SL",
"Classification."
] | def get_otx_dataset(self) -> DatasetEntity:
if not self.dataset[Subset.TRAINING].categories():
label_information = self._prepare_fake_label_information()
self.category_items = label_information['category_items']
self.label_groups = label_information['label_groups']
self.label_entitie... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', 'if', 'not', 'self.dataset[Subset.TRAINING].categories():', 'label_information', '=', 'self._prepare_fake_label_information()', 'self.category_items', '=', "label_information['category_items']", 'self.label_groups', '=', "label_information['label_groups']", 'self... | 919,038 |
openvinotoolkit/training_extensions | detection_dataset_adapter.py | DetectionDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Detection. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Detection."
] | def get_otx_dataset(self) -> DatasetEntity:
label_information = self._prepare_label_information(self.dataset)
self.label_entities = label_information['label_entities']
dataset_items: List[DatasetItemEntityWithID] = []
used_labels: List[int] = []
for (subset, subset_data) in self.dataset.items():
... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', 'label_information', '=', 'self._prepare_label_information(self.dataset)', 'self.label_entities', '=', "label_information['label_entities']", 'dataset_items:', 'List[DatasetItemEntityWithID]', '=', '[]', 'used_labels:', 'List[int]', '=', '[]', 'for', '(subset,', ... | 919,039 |
openvinotoolkit/training_extensions | segmentation_dataset_adapter.py | SegmentationDatasetAdapter.get_otx_dataset | get_otx_dataset | Convert DatumaroDataset to DatasetEntity for Segmentation. | [
"Convert",
"DatumaroDataset",
"to",
"DatasetEntity",
"for",
"Segmentation."
] | def get_otx_dataset(self) -> DatasetEntity:
label_information = self._prepare_label_information(self.dataset)
self.label_entities = label_information['label_entities']
dataset_items: List[DatasetItemEntity] = []
used_labels: List[int] = []
self.updated_label_id: Dict[int, int] = {}
if hasattr(se... | ['def', 'get_otx_dataset(self)', '->', 'DatasetEntity:', 'label_information', '=', 'self._prepare_label_information(self.dataset)', 'self.label_entities', '=', "label_information['label_entities']", 'dataset_items:', 'List[DatasetItemEntity]', '=', '[]', 'used_labels:', 'List[int]', '=', '[]', 'self.updated_label_id:',... | 919,040 |
openvinotoolkit/training_extensions | segmentation_dataset_adapter.py | SegmentationDatasetAdapter.set_voc_labels | set_voc_labels | Set labels for common_semantic_segmentation dataset. | [
"Set",
"labels",
"for",
"common_semantic_segmentation",
"dataset."
] | def set_voc_labels(self):
self._remove_labels(['background', 'ignored']) | ['def', 'set_voc_labels(self):', "self._remove_labels(['background',", "'ignored'])"] | 919,041 |
openvinotoolkit/training_extensions | segmentation_dataset_adapter.py | SelfSLSegmentationDatasetAdapter.create_pseudo_masks | create_pseudo_masks | Create pseudo masks for self-sl for semantic segmentation using DetCon. | [
"Create",
"pseudo",
"masks",
"for",
"self-sl",
"for",
"semantic",
"segmentation",
"using",
"DetCon."
] | def create_pseudo_masks(self, img: np.ndarray, pseudo_mask_path: str, mode: str='FH') -> None:
if mode == 'FH':
pseudo_mask = felzenszwalb(img, scale=1000, min_size=1000)
else:
raise ValueError(f'{mode} is not supported to create pseudo masks for DetCon. Choose one of ["FH"].')
cv2.imwrite(p... | ['def', 'create_pseudo_masks(self,', 'img:', 'np.ndarray,', 'pseudo_mask_path:', 'str,', 'mode:', "str='FH')", '->', 'None:', 'if', 'mode', '==', "'FH':", 'pseudo_mask', '=', 'felzenszwalb(img,', 'scale=1000,', 'min_size=1000)', 'else:', 'raise', "ValueError(f'{mode}", 'is', 'not', 'supported', 'to', 'create', 'pseudo'... | 919,043 |
openvinotoolkit/training_extensions | __init__.py | get_dataset_adapter | get_dataset_adapter | Returns a dataset class by task type. | [
"Returns",
"a",
"dataset",
"class",
"by",
"task",
"type."
] | def get_dataset_adapter(task_type: TaskType, train_type: TrainType, train_data_roots: str=None, train_ann_files: str=None, val_data_roots: str=None, val_ann_files: str=None, test_data_roots: str=None, test_ann_files: str=None, unlabeled_data_roots: str=None, unlabeled_file_list: str=None, **kwargs):
train_type_to_b... | ['def', 'get_dataset_adapter(task_type:', 'TaskType,', 'train_type:', 'TrainType,', 'train_data_roots:', 'str=None,', 'train_ann_files:', 'str=None,', 'val_data_roots:', 'str=None,', 'val_ann_files:', 'str=None,', 'test_data_roots:', 'str=None,', 'test_ann_files:', 'str=None,', 'unlabeled_data_roots:', 'str=None,', 'un... | 919,045 |
openvinotoolkit/training_extensions | mem_cache_handler.py | MemCacheHandlerBase.mem_size | mem_size | Get the reserved memory pool size (bytes). | [
"Get",
"the",
"reserved",
"memory",
"pool",
"size",
"(bytes)."
] | def mem_size(self) -> int:
return len(self._arr) | ['def', 'mem_size(self)', '->', 'int:', 'return', 'len(self._arr)'] | 919,046 |
openvinotoolkit/training_extensions | mem_cache_handler.py | MemCacheHandlerBase.freeze | freeze | If frozen, it is impossible to store a new item anymore. | [
"If",
"frozen,",
"it",
"is",
"impossible",
"to",
"store",
"a",
"new",
"item",
"anymore."
] | def freeze(self):
self._freeze.value = True | ['def', 'freeze(self):', 'self._freeze.value', '=', 'True'] | 919,049 |
openvinotoolkit/training_extensions | mem_cache_handler.py | MemCacheHandlerSingleton.delete | delete | Delete the existing MemCacheHandlerBase instance. | [
"Delete",
"the",
"existing",
"MemCacheHandlerBase",
"instance."
] | def delete(cls) -> None:
if hasattr(cls, 'instance'):
del cls.instance | ['def', 'delete(cls)', '->', 'None:', 'if', 'hasattr(cls,', "'instance'):", 'del', 'cls.instance'] | 919,053 |
openvinotoolkit/training_extensions | storage_cache.py | init_arrow_cache | init_arrow_cache | Init arrow format cache from Datumaro. | [
"Init",
"arrow",
"format",
"cache",
"from",
"Datumaro."
] | def init_arrow_cache(dataset: DatumDataset, scheme: Optional[str]=None, **kwargs) -> DatumDataset:
if scheme is None or scheme == 'NONE':
return dataset
cache_paths = arrow_cache_helper(dataset, scheme, **kwargs)
dataset = DatumDataset.import_from(os.path.dirname(cache_paths[0]), 'arrow')
return... | ['def', 'init_arrow_cache(dataset:', 'DatumDataset,', 'scheme:', 'Optional[str]=None,', '**kwargs)', '->', 'DatumDataset:', 'if', 'scheme', 'is', 'None', 'or', 'scheme', '==', "'NONE':", 'return', 'dataset', 'cache_paths', '=', 'arrow_cache_helper(dataset,', 'scheme,', '**kwargs)', 'dataset', '=', 'DatumDataset.import_... | 919,055 |
openvinotoolkit/training_extensions | dataset_manager.py | DatasetManager.get_image_path | get_image_path | Returns the path of image. | [
"Returns",
"the",
"path",
"of",
"image."
] | def get_image_path(data_item: DatasetItem) -> Optional[str]:
if hasattr(data_item.media, 'path'):
return data_item.media.path
return None | ['def', 'get_image_path(data_item:', 'DatasetItem)', '->', 'Optional[str]:', 'if', 'hasattr(data_item.media,', "'path'):", 'return', 'data_item.media.path', 'return', 'None'] | 919,057 |
openvinotoolkit/training_extensions | dataset_manager.py | DatasetManager.export_dataset | export_dataset | Export the Datumaro Dataset. | [
"Export",
"the",
"Datumaro",
"Dataset."
] | def export_dataset(dataset: Dataset, output_dir: str, data_format: str, save_media=True):
return dataset.export(output_dir, data_format, save_media=save_media) | ['def', 'export_dataset(dataset:', 'Dataset,', 'output_dir:', 'str,', 'data_format:', 'str,', 'save_media=True):', 'return', 'dataset.export(output_dir,', 'data_format,', 'save_media=save_media)'] | 919,058 |
openvinotoolkit/training_extensions | omz_wrapper.py | get_model_configuration | get_model_configuration | Getter function of model configuration from name. | [
"Getter",
"function",
"of",
"model",
"configuration",
"from",
"name."
] | def get_model_configuration(model_name):
model_configurations = load_models(_common.MODEL_ROOT, {})
for model in model_configurations:
if model.name == model_name:
_update_model(model)
return model
return None | ['def', 'get_model_configuration(model_name):', 'model_configurations', '=', 'load_models(_common.MODEL_ROOT,', '{})', 'for', 'model', 'in', 'model_configurations:', 'if', 'model.name', '==', 'model_name:', '_update_model(model)', 'return', 'model', 'return', 'None'] | 919,065 |
openvinotoolkit/training_extensions | omz_wrapper.py | convert_model | convert_model | Converting model for OMZ wrapping. | [
"Converting",
"model",
"for",
"OMZ",
"wrapping."
] | def convert_model(model, download_dir=OMZ_CACHE, output_dir=OMZ_CACHE, precisions=None, force=False, *args):
download_dir = Path('') if download_dir is None else Path(download_dir)
output_dir = Path('') if output_dir is None else Path(output_dir)
precisions = precisions if precisions else {'FP32'}
out =... | ['def', 'convert_model(model,', 'download_dir=OMZ_CACHE,', 'output_dir=OMZ_CACHE,', 'precisions=None,', 'force=False,', '*args):', 'download_dir', '=', "Path('')", 'if', 'download_dir', 'is', 'None', 'else', 'Path(download_dir)', 'output_dir', '=', "Path('')", 'if', 'output_dir', 'is', 'None', 'else', 'Path(output_dir)... | 919,067 |
openvinotoolkit/training_extensions | omz_wrapper.py | get_omz_model | get_omz_model | Get OMZ model from name and download_dir. | [
"Get",
"OMZ",
"model",
"from",
"name",
"and",
"download_dir."
] | def get_omz_model(model_name, download_dir=OMZ_CACHE, output_dir=OMZ_CACHE, force=False):
model = get_model_configuration(model_name)
download_model(model, download_dir=download_dir, force=force)
return convert_model(model, download_dir=download_dir, output_dir=output_dir, force=force) | ['def', 'get_omz_model(model_name,', 'download_dir=OMZ_CACHE,', 'output_dir=OMZ_CACHE,', 'force=False):', 'model', '=', 'get_model_configuration(model_name)', 'download_model(model,', 'download_dir=download_dir,', 'force=force)', 'return', 'convert_model(model,', 'download_dir=download_dir,', 'output_dir=output_dir,', ... | 919,068 |
openvinotoolkit/training_extensions | registry.py | Registry.get | get | Get from module name (key). | [
"Get",
"from",
"module",
"name",
"(key)."
] | def get(self, key: Any) -> Any:
if key not in self._registry_dict:
self._key_not_found(key)
return self._registry_dict[key] | ['def', 'get(self,', 'key:', 'Any)', '->', 'Any:', 'if', 'key', 'not', 'in', 'self._registry_dict:', 'self._key_not_found(key)', 'return', 'self._registry_dict[key]'] | 919,070 |
openvinotoolkit/training_extensions | utils.py | load_ov_model | load_ov_model | Load ov_model from model_path. | [
"Load",
"ov_model",
"from",
"model_path."
] | def load_ov_model(model_path: str, weight_path: Optional[str]=None, convert_dynamic: bool=False) -> Model:
model_path = str(model_path)
if model_path.startswith('omz://'):
model_path = model_path.replace('omz://', '')
assert model_path in AVAILABLE_OMZ_MODELS
ov_ir_path = get_omz_model(m... | ['def', 'load_ov_model(model_path:', 'str,', 'weight_path:', 'Optional[str]=None,', 'convert_dynamic:', 'bool=False)', '->', 'Model:', 'model_path', '=', 'str(model_path)', 'if', "model_path.startswith('omz://'):", 'model_path', '=', "model_path.replace('omz://',", "'')", 'assert', 'model_path', 'in', 'AVAILABLE_OMZ_MO... | 919,072 |
openvinotoolkit/training_extensions | parser.py | parameter_parser | parameter_parser | Parameter Parser from graph. | [
"Parameter",
"Parser",
"from",
"graph."
] | def parameter_parser(graph) -> List[str]:
return type_parser(graph, ['Parameter']) | ['def', 'parameter_parser(graph)', '->', 'List[str]:', 'return', 'type_parser(graph,', "['Parameter'])"] | 919,079 |
openvinotoolkit/training_extensions | parser_mixin.py | ParserMixin.parse | parse | Parse function of ParserMixin class. | [
"Parse",
"function",
"of",
"ParserMixin",
"class."
] | def parse(self, model_path_or_model: Union[str, ov.Model], weight_path: Optional[str]=None, inputs: Optional[Union[Dict[str, Union[str, List[str]]], List[str], str]]=None, outputs: Optional[Union[Dict[str, Union[str, List[str]]], List[str], str]]=None, parser: Optional[Union[str, Callable]]=None, **kwargs) -> Tuple[Uni... | ['def', 'parse(self,', 'model_path_or_model:', 'Union[str,', 'ov.Model],', 'weight_path:', 'Optional[str]=None,', 'inputs:', 'Optional[Union[Dict[str,', 'Union[str,', 'List[str]]],', 'List[str],', 'str]]=None,', 'outputs:', 'Optional[Union[Dict[str,', 'Union[str,', 'List[str]]],', 'List[str],', 'str]]=None,', 'parser:'... | 919,081 |
openvinotoolkit/training_extensions | utils.py | get_dynamic_shape | get_dynamic_shape | Getter function for dynamic shape. | [
"Getter",
"function",
"for",
"dynamic",
"shape."
] | def get_dynamic_shape(output):
shape = [str(i) for i in output.get_partial_shape()]
for (i, shape_) in enumerate(shape):
try:
shape_ = int(shape_)
except ValueError:
shape_ = -1
shape[i] = shape_
return shape | ['def', 'get_dynamic_shape(output):', 'shape', '=', '[str(i)', 'for', 'i', 'in', 'output.get_partial_shape()]', 'for', '(i,', 'shape_)', 'in', 'enumerate(shape):', 'try:', 'shape_', '=', 'int(shape_)', 'except', 'ValueError:', 'shape_', '=', '-1', 'shape[i]', '=', 'shape_', 'return', 'shape'] | 919,086 |
openvinotoolkit/training_extensions | utils.py | convert_op_to_torch | convert_op_to_torch | Convert op Node to torch. | [
"Convert",
"op",
"Node",
"to",
"torch."
] | def convert_op_to_torch(op_node: Node):
op_type = op_node.get_type_name()
op_version = op_node.get_type_info().version_id
try:
torch_module = OPS.get_by_type_version(op_type, op_version).from_ov(op_node)
except Exception as e:
raise e
return torch_module | ['def', 'convert_op_to_torch(op_node:', 'Node):', 'op_type', '=', 'op_node.get_type_name()', 'op_version', '=', 'op_node.get_type_info().version_id', 'try:', 'torch_module', '=', 'OPS.get_by_type_version(op_type,', 'op_version).from_ov(op_node)', 'except', 'Exception', 'as', 'e:', 'raise', 'e', 'return', 'torch_module'... | 919,087 |
openvinotoolkit/training_extensions | op_module.py | convert_op_to_torch_module | convert_op_to_torch_module | Convert op Node to torch module. | [
"Convert",
"op",
"Node",
"to",
"torch",
"module."
] | def convert_op_to_torch_module(target_op: Node):
dependent_modules = []
for in_port in target_op.inputs():
out_port = in_port.get_source_output()
parent = out_port.get_node()
parent_type = parent.get_type_name()
if parent_type == 'Constant':
dependent_modules.append(c... | ['def', 'convert_op_to_torch_module(target_op:', 'Node):', 'dependent_modules', '=', '[]', 'for', 'in_port', 'in', 'target_op.inputs():', 'out_port', '=', 'in_port.get_source_output()', 'parent', '=', 'out_port.get_node()', 'parent_type', '=', 'parent.get_type_name()', 'if', 'parent_type', '==', "'Constant':", 'depende... | 919,088 |
openvinotoolkit/training_extensions | hpo_base.py | HpoBase.is_done | is_done | Check whether HPO algorithm is done. | [
"Check",
"whether",
"HPO",
"algorithm",
"is",
"done."
] | def is_done(self):
raise NotImplementedError | ['def', 'is_done(self):', 'raise', 'NotImplementedError'] | 919,091 |
openvinotoolkit/training_extensions | hpo_base.py | HpoBase.get_next_sample | get_next_sample | Get next sample to train. | [
"Get",
"next",
"sample",
"to",
"train."
] | def get_next_sample(self):
raise NotImplementedError | ['def', 'get_next_sample(self):', 'raise', 'NotImplementedError'] | 919,092 |
openvinotoolkit/training_extensions | hpo_base.py | HpoBase.auto_config | auto_config | Configure HPO algorithm automatically. | [
"Configure",
"HPO",
"algorithm",
"automatically."
] | def auto_config(self):
raise NotImplementedError | ['def', 'auto_config(self):', 'raise', 'NotImplementedError'] | 919,093 |
openvinotoolkit/training_extensions | hpo_base.py | HpoBase.get_progress | get_progress | Get current progress of HPO algorithm. | [
"Get",
"current",
"progress",
"of",
"HPO",
"algorithm."
] | def get_progress(self):
raise NotImplementedError | ['def', 'get_progress(self):', 'raise', 'NotImplementedError'] | 919,094 |
openvinotoolkit/training_extensions | hpo_base.py | HpoBase.report_score | report_score | Report a score to HPO algorithm. | [
"Report",
"a",
"score",
"to",
"HPO",
"algorithm."
] | def report_score(self, score, resource, trial_id, done):
raise NotImplementedError | ['def', 'report_score(self,', 'score,', 'resource,', 'trial_id,', 'done):', 'raise', 'NotImplementedError'] | 919,095 |
openvinotoolkit/training_extensions | hpo_base.py | HpoBase.get_best_config | get_best_config | Get best config of HPO algorithm. | [
"Get",
"best",
"config",
"of",
"HPO",
"algorithm."
] | def get_best_config(self):
raise NotImplementedError | ['def', 'get_best_config(self):', 'raise', 'NotImplementedError'] | 919,096 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.configuration | configuration | Configuration to train with. | [
"Configuration",
"to",
"train",
"with."
] | def configuration(self):
return self._configuration | ['def', 'configuration(self):', 'return', 'self._configuration'] | 919,097 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.iteration | iteration | Iteration to use for training. | [
"Iteration",
"to",
"use",
"for",
"training."
] | def iteration(self):
return self._iteration | ['def', 'iteration(self):', 'return', 'self._iteration'] | 919,098 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.train_environment | train_environment | Train environment for the trial. | [
"Train",
"environment",
"for",
"the",
"trial."
] | def train_environment(self):
return self._train_environment | ['def', 'train_environment(self):', 'return', 'self._train_environment'] | 919,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.