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 | hpo_base.py | Trial.get_train_configuration | get_train_configuration | Get configurations needed to trian. | [
"Get",
"configurations",
"needed",
"to",
"trian."
] | def get_train_configuration(self) -> Dict[str, Any]:
self._configuration['iterations'] = self.iteration
return {'id': self.id, 'configuration': self.configuration, 'train_environment': self.train_environment} | ['def', 'get_train_configuration(self)', '->', 'Dict[str,', 'Any]:', "self._configuration['iterations']", '=', 'self.iteration', 'return', "{'id':", 'self.id,', "'configuration':", 'self.configuration,', "'train_environment':", 'self.train_environment}'] | 919,100 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.register_score | register_score | Register score to the trial. | [
"Register",
"score",
"to",
"the",
"trial."
] | def register_score(self, score: Union[int, float], resource: Union[int, float]):
check_positive(resource, 'resource')
self.score[resource] = score | ['def', 'register_score(self,', 'score:', 'Union[int,', 'float],', 'resource:', 'Union[int,', 'float]):', 'check_positive(resource,', "'resource')", 'self.score[resource]', '=', 'score'] | 919,101 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.get_best_score | get_best_score | Get best score of the trial. | [
"Get",
"best",
"score",
"of",
"the",
"trial."
] | def get_best_score(self, mode: str='max', resource_limit: Optional[Union[float, int]]=None) -> Optional[Union[float, int]]:
check_mode_input(mode)
if resource_limit is None:
scores = self.score.values()
else:
scores = [val for (key, val) in self.score.items() if key <= resource_limit]
if... | ['def', 'get_best_score(self,', 'mode:', "str='max',", 'resource_limit:', 'Optional[Union[float,', 'int]]=None)', '->', 'Optional[Union[float,', 'int]]:', 'check_mode_input(mode)', 'if', 'resource_limit', 'is', 'None:', 'scores', '=', 'self.score.values()', 'else:', 'scores', '=', '[val', 'for', '(key,', 'val)', 'in', ... | 919,102 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.save_results | save_results | Save a result in the 'save_path'. | [
"Save",
"a",
"result",
"in",
"the",
"'save_path'."
] | def save_results(self, save_path: str):
results = {'id': self.id, 'configuration': self.configuration, 'train_environment': self.train_environment, 'score': self.score}
with open(save_path, 'w', encoding='utf-8') as f:
json.dump(results, f) | ['def', 'save_results(self,', 'save_path:', 'str):', 'results', '=', "{'id':", 'self.id,', "'configuration':", 'self.configuration,', "'train_environment':", 'self.train_environment,', "'score':", 'self.score}', 'with', 'open(save_path,', "'w',", "encoding='utf-8')", 'as', 'f:', 'json.dump(results,', 'f)'] | 919,104 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.finalize | finalize | Set done as True. | [
"Set",
"done",
"as",
"True."
] | def finalize(self):
if not self.score:
raise RuntimeError(f"Trial{self.id} didn't report any score but tries to be done.")
self._done = True | ['def', 'finalize(self):', 'if', 'not', 'self.score:', 'raise', 'RuntimeError(f"Trial{self.id}', "didn't", 'report', 'any', 'score', 'but', 'tries', 'to', 'be', 'done.")', 'self._done', '=', 'True'] | 919,105 |
openvinotoolkit/training_extensions | hpo_base.py | Trial.is_done | is_done | Check the trial is done. | [
"Check",
"the",
"trial",
"is",
"done."
] | def is_done(self):
if self.iteration is None:
raise ValueError("iteration isn't set yet.")
return self._done or self.get_progress() >= self.iteration | ['def', 'is_done(self):', 'if', 'self.iteration', 'is', 'None:', 'raise', 'ValueError("iteration', "isn't", 'set', 'yet.")', 'return', 'self._done', 'or', 'self.get_progress()', '>=', 'self.iteration'] | 919,106 |
openvinotoolkit/training_extensions | hpo_runner.py | run_hpo_loop | run_hpo_loop | Run the HPO loop. | [
"Run",
"the",
"HPO",
"loop."
] | def run_hpo_loop(hpo_algo: HpoBase, train_func: Callable, resource_type: Literal['gpu', 'cpu']='gpu', num_parallel_trial: Optional[int]=None, num_gpu_for_single_trial: Optional[int]=None, available_gpu: Optional[str]=None):
hpo_loop = HpoLoop(hpo_algo, train_func, resource_type, num_parallel_trial, num_gpu_for_sing... | ['def', 'run_hpo_loop(hpo_algo:', 'HpoBase,', 'train_func:', 'Callable,', 'resource_type:', "Literal['gpu',", "'cpu']='gpu',", 'num_parallel_trial:', 'Optional[int]=None,', 'num_gpu_for_single_trial:', 'Optional[int]=None,', 'available_gpu:', 'Optional[str]=None):', 'hpo_loop', '=', 'HpoLoop(hpo_algo,', 'train_func,', ... | 919,107 |
openvinotoolkit/training_extensions | hyperband.py | AshaTrial.bracket | bracket | Bracket where the trial is inlcuded. | [
"Bracket",
"where",
"the",
"trial",
"is",
"inlcuded."
] | def bracket(self):
return self._bracket | ['def', 'bracket(self):', 'return', 'self._bracket'] | 919,110 |
openvinotoolkit/training_extensions | hyperband.py | AshaTrial.save_results | save_results | Save a result of the trial at 'save_path'. | [
"Save",
"a",
"result",
"of",
"the",
"trial",
"at",
"'save_path'."
] | def save_results(self, save_path: str):
results = {'id': self.id, 'rung': self.rung, 'configuration': self.configuration, 'train_environment': self.train_environment, 'score': self.score}
with open(save_path, 'w', encoding='utf-8') as f:
json.dump(results, f) | ['def', 'save_results(self,', 'save_path:', 'str):', 'results', '=', "{'id':", 'self.id,', "'rung':", 'self.rung,', "'configuration':", 'self.configuration,', "'train_environment':", 'self.train_environment,', "'score':", 'self.score}', 'with', 'open(save_path,', "'w',", "encoding='utf-8')", 'as', 'f:', 'json.dump(resu... | 919,111 |
openvinotoolkit/training_extensions | hyperband.py | Rung.num_required_trial | num_required_trial | Number of required trials for the rung. | [
"Number",
"of",
"required",
"trials",
"for",
"the",
"rung."
] | def num_required_trial(self):
return self._num_required_trial | ['def', 'num_required_trial(self):', 'return', 'self._num_required_trial'] | 919,112 |
openvinotoolkit/training_extensions | hyperband.py | Rung.resource | resource | Resource to use for training a trial. | [
"Resource",
"to",
"use",
"for",
"training",
"a",
"trial."
] | def resource(self):
return self._resource | ['def', 'resource(self):', 'return', 'self._resource'] | 919,113 |
openvinotoolkit/training_extensions | hyperband.py | Rung.add_new_trial | add_new_trial | Add a new trial to the rung. | [
"Add",
"a",
"new",
"trial",
"to",
"the",
"rung."
] | def add_new_trial(self, trial: AshaTrial):
if not self.need_more_trials():
raise RuntimeError(f'{self.rung_idx} rung has already sufficient trials.')
trial.iteration = self.resource
trial.rung = self.rung_idx
trial.status = TrialStatus.READY
self._trials.append(trial) | ['def', 'add_new_trial(self,', 'trial:', 'AshaTrial):', 'if', 'not', 'self.need_more_trials():', 'raise', "RuntimeError(f'{self.rung_idx}", 'rung', 'has', 'already', 'sufficient', "trials.')", 'trial.iteration', '=', 'self.resource', 'trial.rung', '=', 'self.rung_idx', 'trial.status', '=', 'TrialStatus.READY', 'self._t... | 919,114 |
openvinotoolkit/training_extensions | hyperband.py | Rung.get_best_trial | get_best_trial | Get best trial in the rung. | [
"Get",
"best",
"trial",
"in",
"the",
"rung."
] | def get_best_trial(self, mode: str='max') -> Optional[AshaTrial]:
check_mode_input(mode)
best_score = None
best_trial = None
for trial in self._trials:
if trial.rung != self.rung_idx:
continue
trial_score = trial.get_best_score(mode, self.resource)
if trial_score is n... | ['def', 'get_best_trial(self,', 'mode:', "str='max')", '->', 'Optional[AshaTrial]:', 'check_mode_input(mode)', 'best_score', '=', 'None', 'best_trial', '=', 'None', 'for', 'trial', 'in', 'self._trials:', 'if', 'trial.rung', '!=', 'self.rung_idx:', 'continue', 'trial_score', '=', 'trial.get_best_score(mode,', 'self.reso... | 919,115 |
openvinotoolkit/training_extensions | hyperband.py | Rung.need_more_trials | need_more_trials | Check whether the rung needs more trials. | [
"Check",
"whether",
"the",
"rung",
"needs",
"more",
"trials."
] | def need_more_trials(self) -> bool:
return self.num_required_trial > self.get_num_trials() | ['def', 'need_more_trials(self)', '->', 'bool:', 'return', 'self.num_required_trial', '>', 'self.get_num_trials()'] | 919,116 |
openvinotoolkit/training_extensions | hyperband.py | Rung.get_num_trials | get_num_trials | Number of trials the rung has. | [
"Number",
"of",
"trials",
"the",
"rung",
"has."
] | def get_num_trials(self) -> int:
return len(self._trials) | ['def', 'get_num_trials(self)', '->', 'int:', 'return', 'len(self._trials)'] | 919,117 |
openvinotoolkit/training_extensions | hyperband.py | Rung.is_done | is_done | Check that the rung is done. | [
"Check",
"that",
"the",
"rung",
"is",
"done."
] | def is_done(self) -> bool:
if self.need_more_trials():
return False
for trial in self._trials:
if not trial.is_done():
return False
return True | ['def', 'is_done(self)', '->', 'bool:', 'if', 'self.need_more_trials():', 'return', 'False', 'for', 'trial', 'in', 'self._trials:', 'if', 'not', 'trial.is_done():', 'return', 'False', 'return', 'True'] | 919,118 |
openvinotoolkit/training_extensions | hyperband.py | Rung.get_trial_to_promote | get_trial_to_promote | Get a trial to promote. | [
"Get",
"a",
"trial",
"to",
"promote."
] | def get_trial_to_promote(self, asynchronous_sha: bool=False, mode: str='max') -> Optional[AshaTrial]:
num_finished_trial = 0
num_promoted_trial = 0
best_score = None
best_trial = None
for trial in self._trials:
if trial.rung == self._rung_idx:
if trial.is_done() and trial.status ... | ['def', 'get_trial_to_promote(self,', 'asynchronous_sha:', 'bool=False,', 'mode:', "str='max')", '->', 'Optional[AshaTrial]:', 'num_finished_trial', '=', '0', 'num_promoted_trial', '=', '0', 'best_score', '=', 'None', 'best_trial', '=', 'None', 'for', 'trial', 'in', 'self._trials:', 'if', 'trial.rung', '==', 'self._run... | 919,119 |
openvinotoolkit/training_extensions | hyperband.py | Bracket.max_rung | max_rung | Number of rungs the bracket has. | [
"Number",
"of",
"rungs",
"the",
"bracket",
"has."
] | def max_rung(self):
return self.calcuate_max_rung_idx(self._minimum_resource, self.maximum_resource, self._reduction_factor) | ['def', 'max_rung(self):', 'return', 'self.calcuate_max_rung_idx(self._minimum_resource,', 'self.maximum_resource,', 'self._reduction_factor)'] | 919,122 |
openvinotoolkit/training_extensions | hyperband.py | Bracket.print_result | print_result | Print a bracket result. | [
"Print",
"a",
"bracket",
"result."
] | def print_result(self):
print('*' * 20, f'{self.id} bracket', '*' * 20)
result = self._get_result()
del result['rung_status']
for (key, val) in result.items():
print(f'{key} : {val}')
best_trial = self.get_best_trial()
if best_trial is None:
print("This bracket isn't started yet!... | ['def', 'print_result(self):', "print('*'", '*', '20,', "f'{self.id}", "bracket',", "'*'", '*', '20)', 'result', '=', 'self._get_result()', 'del', "result['rung_status']", 'for', '(key,', 'val)', 'in', 'result.items():', "print(f'{key}", ':', "{val}')", 'best_trial', '=', 'self.get_best_trial()', 'if', 'best_trial', 'i... | 919,128 |
openvinotoolkit/training_extensions | hyperband.py | HyperBand.get_progress | get_progress | Get current progress of ASHA. | [
"Get",
"current",
"progress",
"of",
"ASHA."
] | def get_progress(self) -> Union[int, float]:
if self.is_done():
return 1
if self.expected_time_ratio is None:
total_resource = self._get_full_asha_resource()
else:
total_resource = self._get_expected_total_resource()
progress = self._get_used_resource() / total_resource
retur... | ['def', 'get_progress(self)', '->', 'Union[int,', 'float]:', 'if', 'self.is_done():', 'return', '1', 'if', 'self.expected_time_ratio', 'is', 'None:', 'total_resource', '=', 'self._get_full_asha_resource()', 'else:', 'total_resource', '=', 'self._get_expected_total_resource()', 'progress', '=', 'self._get_used_resource(... | 919,132 |
openvinotoolkit/training_extensions | hyperband.py | HyperBand.report_score | report_score | Report a score to ASHA. | [
"Report",
"a",
"score",
"to",
"ASHA."
] | def report_score(self, score: Union[float, int], resource: Union[float, int], trial_id: str, done: bool=False) -> Literal[TrialStatus.STOP, TrialStatus.RUNNING]:
trial = self._trials[trial_id]
if done:
if self.maximum_resource is None and trial.estimating_max_resource:
self.maximum_resource ... | ['def', 'report_score(self,', 'score:', 'Union[float,', 'int],', 'resource:', 'Union[float,', 'int],', 'trial_id:', 'str,', 'done:', 'bool=False)', '->', 'Literal[TrialStatus.STOP,', 'TrialStatus.RUNNING]:', 'trial', '=', 'self._trials[trial_id]', 'if', 'done:', 'if', 'self.maximum_resource', 'is', 'None', 'and', 'tria... | 919,133 |
openvinotoolkit/training_extensions | hyperband.py | HyperBand.print_result | print_result | Print a ASHA result. | [
"Print",
"a",
"ASHA",
"result."
] | def print_result(self):
print(f'HPO(ASHA) result summary\nBest config : {self.get_best_config()}.\nHyper band runs {len(self._brackets)} brackets.\nBrackets summary:')
for bracket in self._brackets.values():
bracket.print_result() | ['def', 'print_result(self):', "print(f'HPO(ASHA)", 'result', 'summary\\nBest', 'config', ':', '{self.get_best_config()}.\\nHyper', 'band', 'runs', '{len(self._brackets)}', 'brackets.\\nBrackets', "summary:')", 'for', 'bracket', 'in', 'self._brackets.values():', 'bracket.print_result()'] | 919,136 |
openvinotoolkit/training_extensions | resource_manager.py | CPUResourceManager.reserve_resource | reserve_resource | Reserve a resource under 'trial_id'. | [
"Reserve",
"a",
"resource",
"under",
"'trial_id'."
] | def reserve_resource(self, trial_id: Any) -> Optional[Dict]:
if not self.have_available_resource():
return None
if trial_id in self._usage_status:
raise RuntimeError(f'{trial_id} already has reserved resource.')
logger.debug(f'{trial_id} reserved.')
self._usage_status.append(trial_id)
... | ['def', 'reserve_resource(self,', 'trial_id:', 'Any)', '->', 'Optional[Dict]:', 'if', 'not', 'self.have_available_resource():', 'return', 'None', 'if', 'trial_id', 'in', 'self._usage_status:', 'raise', "RuntimeError(f'{trial_id}", 'already', 'has', 'reserved', "resource.')", "logger.debug(f'{trial_id}", "reserved.')", ... | 919,139 |
openvinotoolkit/training_extensions | resource_manager.py | CPUResourceManager.release_resource | release_resource | Release a resource under 'trial_id'. | [
"Release",
"a",
"resource",
"under",
"'trial_id'."
] | def release_resource(self, trial_id: Any):
if trial_id not in self._usage_status:
logger.warning(f"{trial_id} trial don't use resource now.")
else:
self._usage_status.remove(trial_id)
logger.debug(f'{trial_id} released.') | ['def', 'release_resource(self,', 'trial_id:', 'Any):', 'if', 'trial_id', 'not', 'in', 'self._usage_status:', 'logger.warning(f"{trial_id}', 'trial', "don't", 'use', 'resource', 'now.")', 'else:', 'self._usage_status.remove(trial_id)', "logger.debug(f'{trial_id}", "released.')"] | 919,140 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.type | type | Type of hyper parameter in search space. | [
"Type",
"of",
"hyper",
"parameter",
"in",
"search",
"space."
] | def type(self):
return self._type | ['def', 'type(self):', 'return', 'self._type'] | 919,145 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.min | min | Lower bounding of search space. | [
"Lower",
"bounding",
"of",
"search",
"space."
] | def min(self):
return self._min | ['def', 'min(self):', 'return', 'self._min'] | 919,146 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.choice_list | choice_list | Candidiates for choice type. | [
"Candidiates",
"for",
"choice",
"type."
] | def choice_list(self):
return self._choice_list | ['def', 'choice_list(self):', 'return', 'self._choice_list'] | 919,148 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.is_categorical | is_categorical | Check current instance is categorical type. | [
"Check",
"current",
"instance",
"is",
"categorical",
"type."
] | def is_categorical(self):
return self._type == 'choice' | ['def', 'is_categorical(self):', 'return', 'self._type', '==', "'choice'"] | 919,150 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.use_log_scale | use_log_scale | Check current instance is one of type to use `log scale`. | [
"Check",
"current",
"instance",
"is",
"one",
"of",
"type",
"to",
"use",
"`log",
"scale`."
] | def use_log_scale(self):
return self._type in ('loguniform', 'qloguniform') | ['def', 'use_log_scale(self):', 'return', 'self._type', 'in', "('loguniform',", "'qloguniform')"] | 919,152 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.upper_space | upper_space | Get upper bound value considering log scale if necessary. | [
"Get",
"upper",
"bound",
"value",
"considering",
"log",
"scale",
"if",
"necessary."
] | def upper_space(self):
if self.use_log_scale():
return math.log(self._max, self._log_base)
return self._max | ['def', 'upper_space(self):', 'if', 'self.use_log_scale():', 'return', 'math.log(self._max,', 'self._log_base)', 'return', 'self._max'] | 919,154 |
openvinotoolkit/training_extensions | search_space.py | SingleSearchSpace.space_to_real | space_to_real | Convert search space from HPO perspective to human perspective. | [
"Convert",
"search",
"space",
"from",
"HPO",
"perspective",
"to",
"human",
"perspective."
] | def space_to_real(self, number: Union[int, float]) -> Union[int, float]:
if self.is_categorical():
idx = max(min(int(number), len(self._choice_list) - 1), 0)
return self._choice_list[idx]
if self.use_log_scale():
number = self._log_base ** number
if self.use_quantized_step():
... | ['def', 'space_to_real(self,', 'number:', 'Union[int,', 'float])', '->', 'Union[int,', 'float]:', 'if', 'self.is_categorical():', 'idx', '=', 'max(min(int(number),', 'len(self._choice_list)', '-', '1),', '0)', 'return', 'self._choice_list[idx]', 'if', 'self.use_log_scale():', 'number', '=', 'self._log_base', '**', 'num... | 919,155 |
openvinotoolkit/training_extensions | search_space.py | SearchSpace.get_real_config | get_real_config | Convert search space of each config from HPO perspective to human perspective. | [
"Convert",
"search",
"space",
"of",
"each",
"config",
"from",
"HPO",
"perspective",
"to",
"human",
"perspective."
] | def get_real_config(self, config: Dict) -> Dict:
real_config = {}
for (param, value) in config.items():
real_config[param] = self[param].space_to_real(value)
return real_config | ['def', 'get_real_config(self,', 'config:', 'Dict)', '->', 'Dict:', 'real_config', '=', '{}', 'for', '(param,', 'value)', 'in', 'config.items():', 'real_config[param]', '=', 'self[param].space_to_real(value)', 'return', 'real_config'] | 919,158 |
openvinotoolkit/training_extensions | search_space.py | SearchSpace.get_bayeopt_search_space | get_bayeopt_search_space | Return hyper parameter serach sapce as bayeopt library format. | [
"Return",
"hyper",
"parameter",
"serach",
"sapce",
"as",
"bayeopt",
"library",
"format."
] | def get_bayeopt_search_space(self) -> Dict:
bayesopt_space = {}
for (key, val) in self.search_space.items():
bayesopt_space[key] = (val.lower_space(), val.upper_space())
return bayesopt_space | ['def', 'get_bayeopt_search_space(self)', '->', 'Dict:', 'bayesopt_space', '=', '{}', 'for', '(key,', 'val)', 'in', 'self.search_space.items():', 'bayesopt_space[key]', '=', '(val.lower_space(),', 'val.upper_space())', 'return', 'bayesopt_space'] | 919,160 |
openvinotoolkit/training_extensions | utils.py | check_positive | check_positive | Validate that value is positivle. | [
"Validate",
"that",
"value",
"is",
"positivle."
] | def check_positive(value, variable_name: Optional[str]=None, error_message: Optional[str]=None):
if value <= 0:
if error_message is not None:
message = error_message
elif variable_name:
message = f'{variable_name} should be positive.\nyour value : {value}'
else:
... | ['def', 'check_positive(value,', 'variable_name:', 'Optional[str]=None,', 'error_message:', 'Optional[str]=None):', 'if', 'value', '<=', '0:', 'if', 'error_message', 'is', 'not', 'None:', 'message', '=', 'error_message', 'elif', 'variable_name:', 'message', '=', "f'{variable_name}", 'should', 'be', 'positive.\\nyour', ... | 919,163 |
openvinotoolkit/training_extensions | utils.py | check_not_negative | check_not_negative | Validate that value isn't negative. | [
"Validate",
"that",
"value",
"isn't",
"negative."
] | def check_not_negative(value, variable_name: Optional[str]=None, error_message: Optional[str]=None):
if value < 0:
if error_message is not None:
message = error_message
elif variable_name:
message = f'{variable_name} should be positive.\nyour value : {value}'
else:
... | ['def', 'check_not_negative(value,', 'variable_name:', 'Optional[str]=None,', 'error_message:', 'Optional[str]=None):', 'if', 'value', '<', '0:', 'if', 'error_message', 'is', 'not', 'None:', 'message', '=', 'error_message', 'elif', 'variable_name:', 'message', '=', "f'{variable_name}", 'should', 'be', 'positive.\\nyour... | 919,164 |
openvinotoolkit/training_extensions | utils.py | check_mode_input | check_mode_input | Validate that mode is 'max' or 'min'. | [
"Validate",
"that",
"mode",
"is",
"'max'",
"or",
"'min'."
] | def check_mode_input(mode: str):
if mode not in ['max', 'min']:
raise ValueError(f'mode should be max or min.\nYour value : {mode}') | ['def', 'check_mode_input(mode:', 'str):', 'if', 'mode', 'not', 'in', "['max',", "'min']:", 'raise', "ValueError(f'mode", 'should', 'be', 'max', 'or', 'min.\\nYour', 'value', ':', "{mode}')"] | 919,165 |
openvinotoolkit/training_extensions | run_model_templates_tests.py | what_to_test | what_to_test | Returns a dict containing information whether it is needed to run tests for particular algorithm. | [
"Returns",
"a",
"dict",
"containing",
"information",
"whether",
"it",
"is",
"needed",
"to",
"run",
"tests",
"for",
"particular",
"algorithm."
] | def what_to_test():
print(f'sys.argv={sys.argv!r}')
run_algo_tests = {d: True for d in ALGO_DIRS}
if len(sys.argv) > 2:
run_algo_tests = {d: False for d in ALGO_DIRS}
changed_files = sys.argv[2:]
print(f'changed_files={changed_files!r}')
for changed_file in changed_files:
... | ['def', 'what_to_test():', "print(f'sys.argv={sys.argv!r}')", 'run_algo_tests', '=', '{d:', 'True', 'for', 'd', 'in', 'ALGO_DIRS}', 'if', 'len(sys.argv)', '>', '2:', 'run_algo_tests', '=', '{d:', 'False', 'for', 'd', 'in', 'ALGO_DIRS}', 'changed_files', '=', 'sys.argv[2:]', "print(f'changed_files={changed_files!r}')", ... | 919,166 |
openvinotoolkit/training_extensions | run_model_templates_tests.py | test | test | Runs tests for algorithms and other stuff (misc). | [
"Runs",
"tests",
"for",
"algorithms",
"and",
"other",
"stuff",
"(misc)."
] | def test(run_algo_tests):
passed = {}
success = True
command = ['pytest', os.path.join('tests', 'ote_cli', 'misc'), '-v']
try:
res = run(command, env=collect_env_vars(wd), check=True).returncode == 0
except:
res = False
passed['misc'] = res
success *= res
for algo_dir in ... | ['def', 'test(run_algo_tests):', 'passed', '=', '{}', 'success', '=', 'True', 'command', '=', "['pytest',", "os.path.join('tests',", "'ote_cli',", "'misc'),", "'-v']", 'try:', 'res', '=', 'run(command,', 'env=collect_env_vars(wd),', 'check=True).returncode', '==', '0', 'except:', 'res', '=', 'False', "passed['misc']", ... | 919,167 |
openvinotoolkit/training_extensions | regression_test_helpers.py | RegressionTestConfig.get_template_performance | get_template_performance | Get proper template performance inside of performance list. | [
"Get",
"proper",
"template",
"performance",
"inside",
"of",
"performance",
"list."
] | def get_template_performance(self, template: ModelTemplate, **kwargs):
performance = None
results = None
task_type = kwargs.get('task_type', self.task_type)
train_type = kwargs.get('train_type', self.train_type)
label_type = kwargs.get('label_type', self.label_type)
if 'anomaly' in task_type:
... | ['def', 'get_template_performance(self,', 'template:', 'ModelTemplate,', '**kwargs):', 'performance', '=', 'None', 'results', '=', 'None', 'task_type', '=', "kwargs.get('task_type',", 'self.task_type)', 'train_type', '=', "kwargs.get('train_type',", 'self.train_type)', 'label_type', '=', "kwargs.get('label_type',", 'se... | 919,182 |
openvinotoolkit/training_extensions | summarize_test_results.py | filter_task | filter_task | Find prpoer task and task_key. | [
"Find",
"prpoer",
"task",
"and",
"task_key."
] | def filter_task(root: str) -> Dict[str, str]:
task = root.split('/')[-1]
if 'tiling' in task:
task_key = '_'.join(task.split('_')[1:])
else:
task_key = task
return (task_key, task) | ['def', 'filter_task(root:', 'str)', '->', 'Dict[str,', 'str]:', 'task', '=', "root.split('/')[-1]", 'if', "'tiling'", 'in', 'task:', 'task_key', '=', "'_'.join(task.split('_')[1:])", 'else:', 'task_key', '=', 'task', 'return', '(task_key,', 'task)'] | 919,185 |
openvinotoolkit/training_extensions | summarize_test_results.py | is_anomaly_task | is_anomaly_task | Returns True if task is anomaly. | [
"Returns",
"True",
"if",
"task",
"is",
"anomaly."
] | def is_anomaly_task(task: str) -> bool:
return 'anomaly' in task | ['def', 'is_anomaly_task(task:', 'str)', '->', 'bool:', 'return', "'anomaly'", 'in', 'task'] | 919,186 |
openvinotoolkit/training_extensions | summarize_test_results.py | fill_model_performance | fill_model_performance | Fill the result_data by checking the index of data. | [
"Fill",
"the",
"result_data",
"by",
"checking",
"the",
"index",
"of",
"data."
] | def fill_model_performance(items: Union[list, str], test_type: str, result_data: dict):
if isinstance(items, list):
result_data[test_type].append(f'{items[0][0]}: {items[0][1]}')
if test_type == 'train':
result_data[f'{test_type} E2E Time (Sec.)'].append(f'{items[2][1]}')
res... | ['def', 'fill_model_performance(items:', 'Union[list,', 'str],', 'test_type:', 'str,', 'result_data:', 'dict):', 'if', 'isinstance(items,', 'list):', "result_data[test_type].append(f'{items[0][0]}:", "{items[0][1]}')", 'if', 'test_type', '==', "'train':", "result_data[f'{test_type}", 'E2E', 'Time', "(Sec.)'].append(f'{... | 919,187 |
openvinotoolkit/training_extensions | test_anomaly_classificaiton.py | TestRegressionAnomalyClassification.test_otx_train_kpi_test | test_otx_train_kpi_test | KPI tests: measure the train+val time and evaluation time and compare with criteria. | [
"KPI",
"tests:",
"measure",
"the",
"train+val",
"time",
"and",
"evaluation",
"time",
"and",
"compare",
"with",
"criteria."
] | def test_otx_train_kpi_test(self, reg_cfg, template, category):
performance = reg_cfg.get_template_performance(template, category=category)
kpi_train_result = regression_train_time_testing(train_time_criteria=reg_cfg.config_dict['kpi_e2e_train_time_criteria']['train'][category], e2e_train_time=performance[templ... | ['def', 'test_otx_train_kpi_test(self,', 'reg_cfg,', 'template,', 'category):', 'performance', '=', 'reg_cfg.get_template_performance(template,', 'category=category)', 'kpi_train_result', '=', "regression_train_time_testing(train_time_criteria=reg_cfg.config_dict['kpi_e2e_train_time_criteria']['train'][category],", "e2... | 919,191 |
openvinotoolkit/training_extensions | fixtures.py | current_test_parameters_fx | current_test_parameters_fx | This fixture returns the test parameter `test_parameters` of the current test. | [
"This",
"fixture",
"returns",
"the",
"test",
"parameter",
"`test_parameters`",
"of",
"the",
"current",
"test."
] | def current_test_parameters_fx(request, force_logging_fx):
cur_test_params = deepcopy(request.node.callspec.params)
assert 'test_parameters' in cur_test_params, f"The test {request.node.name} should be parametrized by parameter 'test_parameters'"
return cur_test_params['test_parameters'] | ['def', 'current_test_parameters_fx(request,', 'force_logging_fx):', 'cur_test_params', '=', 'deepcopy(request.node.callspec.params)', 'assert', "'test_parameters'", 'in', 'cur_test_params,', 'f"The', 'test', '{request.node.name}', 'should', 'be', 'parametrized', 'by', 'parameter', '\'test_parameters\'"', 'return', "cu... | 919,203 |
openvinotoolkit/training_extensions | logging.py | get_logger | get_logger | The function returns the common logger for all OTX training tests. | [
"The",
"function",
"returns",
"the",
"common",
"logger",
"for",
"all",
"OTX",
"training",
"tests."
] | def get_logger():
logger_name = '.'.join(__name__.split('.')[:-1])
return logging.getLogger(logger_name) | ['def', 'get_logger():', 'logger_name', '=', "'.'.join(__name__.split('.')[:-1])", 'return', 'logging.getLogger(logger_name)'] | 919,206 |
openvinotoolkit/training_extensions | pytest_insertions.py | otx_pytest_addoption_insertion | otx_pytest_addoption_insertion | The function should be called in the standard pytest hook pytest_addoption to add the options required for reallife training tests. | [
"The",
"function",
"should",
"be",
"called",
"in",
"the",
"standard",
"pytest",
"hook",
"pytest_addoption",
"to",
"add",
"the",
"options",
"required",
"for",
"reallife",
"training",
"tests."
] | def otx_pytest_addoption_insertion(parser):
if _e2e_pytest_addoption:
_e2e_pytest_addoption(parser)
parser.addoption('--dataset-definitions', action='store', default=None, help='Path to the dataset_definitions.yml file for tests that require datasets.')
parser.addoption('--test-usecase', action='sto... | ['def', 'otx_pytest_addoption_insertion(parser):', 'if', '_e2e_pytest_addoption:', '_e2e_pytest_addoption(parser)', "parser.addoption('--dataset-definitions',", "action='store',", 'default=None,', "help='Path", 'to', 'the', 'dataset_definitions.yml', 'file', 'for', 'tests', 'that', 'require', "datasets.')", "parser.add... | 919,209 |
openvinotoolkit/training_extensions | test_helpers.py | generate_labels | generate_labels | Generate list of LabelEntity given length and domain. | [
"Generate",
"list",
"of",
"LabelEntity",
"given",
"length",
"and",
"domain."
] | def generate_labels(length: int, domain: Domain) -> List[LabelEntity]:
output: List[LabelEntity] = []
for i in range(length):
output.append(LabelEntity(name=f'{i + 1}', domain=domain, id=ID(i + 1)))
return output | ['def', 'generate_labels(length:', 'int,', 'domain:', 'Domain)', '->', 'List[LabelEntity]:', 'output:', 'List[LabelEntity]', '=', '[]', 'for', 'i', 'in', 'range(length):', "output.append(LabelEntity(name=f'{i", '+', "1}',", 'domain=domain,', 'id=ID(i', '+', '1)))', 'return', 'output'] | 919,224 |
openvinotoolkit/training_extensions | test_helpers.py | generate_action_cls_otx_dataset | generate_action_cls_otx_dataset | Generate otx_dataset for action classification task. | [
"Generate",
"otx_dataset",
"for",
"action",
"classification",
"task."
] | def generate_action_cls_otx_dataset(video_len: int, frame_len: int, labels: List[LabelEntity]) -> DatasetEntity:
items: List[DatasetItemEntity] = []
for video_id in range(video_len):
if video_id > 1:
subset = Subset.VALIDATION
else:
subset = Subset.TRAINING
for fr... | ['def', 'generate_action_cls_otx_dataset(video_len:', 'int,', 'frame_len:', 'int,', 'labels:', 'List[LabelEntity])', '->', 'DatasetEntity:', 'items:', 'List[DatasetItemEntity]', '=', '[]', 'for', 'video_id', 'in', 'range(video_len):', 'if', 'video_id', '>', '1:', 'subset', '=', 'Subset.VALIDATION', 'else:', 'subset', '... | 919,225 |
openvinotoolkit/training_extensions | test_helpers.py | return_args | return_args | This function returns its args. | [
"This",
"function",
"returns",
"its",
"args."
] | def return_args(*args, **kwargs):
return (args, kwargs) | ['def', 'return_args(*args,', '**kwargs):', 'return', '(args,', 'kwargs)'] | 919,227 |
openvinotoolkit/training_extensions | test_helpers.py | return_inputs | return_inputs | This function returns its input. | [
"This",
"function",
"returns",
"its",
"input."
] | def return_inputs(inputs):
return inputs | ['def', 'return_inputs(inputs):', 'return', 'inputs'] | 919,228 |
openvinotoolkit/training_extensions | test_task.py | TestMMActionTask.test_evaluate_with_empty_annot | test_evaluate_with_empty_annot | Test evaluate function with empty_annot. | [
"Test",
"evaluate",
"function",
"with",
"empty_annot."
] | def test_evaluate_with_empty_annot(self) -> None:
_config = ModelConfiguration(ActionConfig(), self.cls_label_schema)
_model = ModelEntity(self.cls_dataset, _config)
resultset = ResultSetEntity(_model, self.cls_dataset, self.cls_dataset.with_empty_annotations())
self.cls_task.evaluate(resultset)
ass... | ['def', 'test_evaluate_with_empty_annot(self)', '->', 'None:', '_config', '=', 'ModelConfiguration(ActionConfig(),', 'self.cls_label_schema)', '_model', '=', 'ModelEntity(self.cls_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.cls_dataset,', 'self.cls_dataset.with_empty_annotations())', 'self... | 919,230 |
openvinotoolkit/training_extensions | test_action_cls_dataset.py | TestOTXActionClsDataset.test_pipeline | test_pipeline | Test RawFrameDecode transform contains otx_dataset. | [
"Test",
"RawFrameDecode",
"transform",
"contains",
"otx_dataset."
] | def test_pipeline(self) -> None:
dataset = OTXActionClsDataset(self.otx_dataset, self.labels, self.pipeline)
for transform in dataset.pipeline.transforms:
if isinstance(transform, RawFrameDecode):
assert transform.otx_dataset == self.otx_dataset | ['def', 'test_pipeline(self)', '->', 'None:', 'dataset', '=', 'OTXActionClsDataset(self.otx_dataset,', 'self.labels,', 'self.pipeline)', 'for', 'transform', 'in', 'dataset.pipeline.transforms:', 'if', 'isinstance(transform,', 'RawFrameDecode):', 'assert', 'transform.otx_dataset', '==', 'self.otx_dataset'] | 919,236 |
openvinotoolkit/training_extensions | test_action_cls_dataset.py | TestOTXActionClsDataset.test_len | test_len | Test dataset length is same with video_len. | [
"Test",
"dataset",
"length",
"is",
"same",
"with",
"video_len."
] | def test_len(self) -> None:
dataset = OTXActionClsDataset(self.otx_dataset, self.labels, self.pipeline)
assert len(dataset) == self.video_len | ['def', 'test_len(self)', '->', 'None:', 'dataset', '=', 'OTXActionClsDataset(self.otx_dataset,', 'self.labels,', 'self.pipeline)', 'assert', 'len(dataset)', '==', 'self.video_len'] | 919,237 |
openvinotoolkit/training_extensions | test_action_fast_rcnn.py | MockDetector.simple_test | simple_test | Return dummy person detection results. | [
"Return",
"dummy",
"person",
"detection",
"results."
] | def simple_test(self, *args, **kwargs):
sample_det_bboxes = torch.Tensor([[0.0, 0.0, 1.0, 1.0, 1.0]] * 100).unsqueeze(0)
sample_det_labels = torch.ones(1, 100)
sample_det_labels[0][0] = 0
return (sample_det_bboxes, sample_det_labels) | ['def', 'simple_test(self,', '*args,', '**kwargs):', 'sample_det_bboxes', '=', 'torch.Tensor([[0.0,', '0.0,', '1.0,', '1.0,', '1.0]]', '*', '100).unsqueeze(0)', 'sample_det_labels', '=', 'torch.ones(1,', '100)', 'sample_det_labels[0][0]', '=', '0', 'return', '(sample_det_bboxes,', 'sample_det_labels)'] | 919,244 |
openvinotoolkit/training_extensions | test_action_roi_head.py | TestAVARoIHead.test_simple_test | test_simple_test | Test simple test function. | [
"Test",
"simple",
"test",
"function."
] | def test_simple_test(self, mocker) -> None:
sample_input = torch.randn(1, 432, 32, 8, 1)
proposal_list = [torch.Tensor([[0, 0, 10, 10]])]
img_metas = [{'scores': np.array([1.0]), 'img_shape': (256, 256)}]
with torch.no_grad():
out = self.roi_head.simple_test(sample_input, proposal_list, img_meta... | ['def', 'test_simple_test(self,', 'mocker)', '->', 'None:', 'sample_input', '=', 'torch.randn(1,', '432,', '32,', '8,', '1)', 'proposal_list', '=', '[torch.Tensor([[0,', '0,', '10,', '10]])]', 'img_metas', '=', "[{'scores':", 'np.array([1.0]),', "'img_shape':", '(256,', '256)}]', 'with', 'torch.no_grad():', 'out', '=',... | 919,248 |
openvinotoolkit/training_extensions | test_action_dataloader.py | TestActionOVDemoDataLoader.test_len | test_len | Test initialization and __len__ function. | [
"Test",
"initialization",
"and",
"__len__",
"function."
] | def test_len(self) -> None:
dataloader = ActionOVDemoDataLoader(self.dataset, 'ACTION_CLASSIFICATION', 8, 256, 256)
assert len(dataloader) == self.data_len | ['def', 'test_len(self)', '->', 'None:', 'dataloader', '=', 'ActionOVDemoDataLoader(self.dataset,', "'ACTION_CLASSIFICATION',", '8,', '256,', '256)', 'assert', 'len(dataloader)', '==', 'self.data_len'] | 919,254 |
openvinotoolkit/training_extensions | conftest.py | setup_task_environment | setup_task_environment | Returns a task environment, a model and datset. | [
"Returns",
"a",
"task",
"environment,",
"a",
"model",
"and",
"datset."
] | def setup_task_environment(request):
task_type = request.param
dataset: DatasetEntity = get_hazelnut_dataset(task_type, one_each=True)
task_environment = create_task_environment(dataset, task_type)
output_model = ModelEntity(dataset, task_environment.get_model_configuration())
environment = TestEnvi... | ['def', 'setup_task_environment(request):', 'task_type', '=', 'request.param', 'dataset:', 'DatasetEntity', '=', 'get_hazelnut_dataset(task_type,', 'one_each=True)', 'task_environment', '=', 'create_task_environment(dataset,', 'task_type)', 'output_model', '=', 'ModelEntity(dataset,', 'task_environment.get_model_config... | 919,258 |
openvinotoolkit/training_extensions | test_progress_callback.py | TestProgressCallback.test_progress_callback | test_progress_callback | Tests if progress callback runs and that the progress is not reset after validation step. | [
"Tests",
"if",
"progress",
"callback",
"runs",
"and",
"that",
"the",
"progress",
"is",
"not",
"reset",
"after",
"validation",
"step."
] | def test_progress_callback(self):
datamodule = DummyDataModule(TaskType.ANOMALY_CLASSIFICATION)
model = DummyModel()
progress_callback = ProgressCallback()
stage_checker = ProgressStageCheckerCallback(progress_callback)
trainer = pl.Trainer(logger=False, enable_checkpointing=False, max_epochs=5, cal... | ['def', 'test_progress_callback(self):', 'datamodule', '=', 'DummyDataModule(TaskType.ANOMALY_CLASSIFICATION)', 'model', '=', 'DummyModel()', 'progress_callback', '=', 'ProgressCallback()', 'stage_checker', '=', 'ProgressStageCheckerCallback(progress_callback)', 'trainer', '=', 'pl.Trainer(logger=False,', 'enable_check... | 919,261 |
openvinotoolkit/training_extensions | test_inference.py | TestInferenceTask.test_inference | test_inference | Tests the inference method. | [
"Tests",
"the",
"inference",
"method."
] | def test_inference(self, tmpdir, setup_task_environment):
root = str(tmpdir.mkdir('anomaly_inference_test'))
setup_task_environment = deepcopy(setup_task_environment)
task_environment = setup_task_environment.task_environment
task_type = setup_task_environment.task_type
output_model = setup_task_env... | ['def', 'test_inference(self,', 'tmpdir,', 'setup_task_environment):', 'root', '=', "str(tmpdir.mkdir('anomaly_inference_test'))", 'setup_task_environment', '=', 'deepcopy(setup_task_environment)', 'task_environment', '=', 'setup_task_environment.task_environment', 'task_type', '=', 'setup_task_environment.task_type', ... | 919,264 |
openvinotoolkit/training_extensions | test_nncf.py | TestNNCFTask.test_nncf | test_nncf | Tests the NNCF optimize method. | [
"Tests",
"the",
"NNCF",
"optimize",
"method."
] | def test_nncf(self, tmpdir, setup_task_environment):
root = str(tmpdir.mkdir('anomaly_nncf_test'))
setup_task_environment = deepcopy(setup_task_environment)
task_environment = setup_task_environment.task_environment
output_model = setup_task_environment.output_model
dataset = setup_task_environment.... | ['def', 'test_nncf(self,', 'tmpdir,', 'setup_task_environment):', 'root', '=', "str(tmpdir.mkdir('anomaly_nncf_test'))", 'setup_task_environment', '=', 'deepcopy(setup_task_environment)', 'task_environment', '=', 'setup_task_environment.task_environment', 'output_model', '=', 'setup_task_environment.output_model', 'dat... | 919,265 |
openvinotoolkit/training_extensions | test_openvino.py | TestOpenVINOTask.test_openvino | test_openvino | Tests the OpenVINO optimize method. | [
"Tests",
"the",
"OpenVINO",
"optimize",
"method."
] | def test_openvino(self, tmpdir, setup_task_environment):
root = str(tmpdir.mkdir('anomaly_openvino_test'))
setup_task_environment = deepcopy(setup_task_environment)
task_type = setup_task_environment.task_type
dataset: DatasetEntity = setup_task_environment.dataset
task_environment = setup_task_envi... | ['def', 'test_openvino(self,', 'tmpdir,', 'setup_task_environment):', 'root', '=', "str(tmpdir.mkdir('anomaly_openvino_test'))", 'setup_task_environment', '=', 'deepcopy(setup_task_environment)', 'task_type', '=', 'setup_task_environment.task_type', 'dataset:', 'DatasetEntity', '=', 'setup_task_environment.dataset', 't... | 919,267 |
openvinotoolkit/training_extensions | test_task.py | TestMMClassificationTask.test_cls_evaluate | test_cls_evaluate | Test evaluate function for classification. | [
"Test",
"evaluate",
"function",
"for",
"classification."
] | def test_cls_evaluate(self) -> None:
_config = ModelConfiguration(ClassificationConfig('header'), self.mc_cls_label_schema)
_model = ModelEntity(self.mc_cls_dataset, _config)
resultset = ResultSetEntity(_model, self.mc_cls_dataset, self.mc_cls_dataset)
self.mc_cls_task.evaluate(resultset)
assert res... | ['def', 'test_cls_evaluate(self)', '->', 'None:', '_config', '=', "ModelConfiguration(ClassificationConfig('header'),", 'self.mc_cls_label_schema)', '_model', '=', 'ModelEntity(self.mc_cls_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.mc_cls_dataset,', 'self.mc_cls_dataset)', 'self.mc_cls_ta... | 919,271 |
openvinotoolkit/training_extensions | test_task.py | TestMMClassificationTask.test_cls_evaluate_with_empty_annotations | test_cls_evaluate_with_empty_annotations | Test evaluate function for classification with empty predictions. | [
"Test",
"evaluate",
"function",
"for",
"classification",
"with",
"empty",
"predictions."
] | def test_cls_evaluate_with_empty_annotations(self) -> None:
_config = ModelConfiguration(ClassificationConfig('header'), self.mc_cls_label_schema)
_model = ModelEntity(self.mc_cls_dataset, _config)
resultset = ResultSetEntity(_model, self.mc_cls_dataset, self.mc_cls_dataset.with_empty_annotations())
sel... | ['def', 'test_cls_evaluate_with_empty_annotations(self)', '->', 'None:', '_config', '=', "ModelConfiguration(ClassificationConfig('header'),", 'self.mc_cls_label_schema)', '_model', '=', 'ModelEntity(self.mc_cls_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.mc_cls_dataset,', 'self.mc_cls_dat... | 919,272 |
openvinotoolkit/training_extensions | test_byol.py | TestBYOL.test_train_step | test_train_step | Test train_step function wraps forward and _parse_losses. | [
"Test",
"train_step",
"function",
"wraps",
"forward",
"and",
"_parse_losses."
] | def test_train_step(self) -> None:
img1 = torch.randn((1, 3, 2, 2))
img2 = torch.randn((1, 3, 2, 2))
outputs = self.byol.train_step(data=dict(img1=img1, img2=img2), optimizer=None)
assert 'loss' in outputs
assert 'log_vars' in outputs
assert 'num_samples' in outputs | ['def', 'test_train_step(self)', '->', 'None:', 'img1', '=', 'torch.randn((1,', '3,', '2,', '2))', 'img2', '=', 'torch.randn((1,', '3,', '2,', '2))', 'outputs', '=', 'self.byol.train_step(data=dict(img1=img1,', 'img2=img2),', 'optimizer=None)', 'assert', "'loss'", 'in', 'outputs', 'assert', "'log_vars'", 'in', 'outputs... | 919,275 |
openvinotoolkit/training_extensions | test_contrastive_head.py | TestConstrastiveHead.test_forward_no_size_average | test_forward_no_size_average | Test forward function without size averaging. | [
"Test",
"forward",
"function",
"without",
"size",
"averaging."
] | def test_forward_no_size_average(self) -> None:
contrastive_head = ConstrastiveHead(predictor={}, size_average=False)
contrastive_head.init_weights()
result = contrastive_head(self.inputs, self.targets)
expected_result = {'loss': torch.tensor(0.0511)}
assert torch.allclose(result['loss'], expected_r... | ['def', 'test_forward_no_size_average(self)', '->', 'None:', 'contrastive_head', '=', 'ConstrastiveHead(predictor={},', 'size_average=False)', 'contrastive_head.init_weights()', 'result', '=', 'contrastive_head(self.inputs,', 'self.targets)', 'expected_result', '=', "{'loss':", 'torch.tensor(0.0511)}', 'assert', "torch... | 919,276 |
openvinotoolkit/training_extensions | test_semisl_cls_head.py | TestSemiSLClsHead.setUp | setUp | Semi-SL for Classification Head Settings. | [
"Semi-SL",
"for",
"Classification",
"Head",
"Settings."
] | def setUp(self):
self.in_channels = 1280
self.num_classes = 10
self.head_cfg = dict(type='SemiLinearClsHead', in_channels=self.in_channels, num_classes=self.num_classes) | ['def', 'setUp(self):', 'self.in_channels', '=', '1280', 'self.num_classes', '=', '10', 'self.head_cfg', '=', "dict(type='SemiLinearClsHead',", 'in_channels=self.in_channels,', 'num_classes=self.num_classes)'] | 919,277 |
openvinotoolkit/training_extensions | test_semisl_cls_head.py | TestSemiSLClsHead.test_build_semisl_cls_head_value_error | test_build_semisl_cls_head_value_error | Verifies that SemiSLClsHead parameters check with ValueError. | [
"Verifies",
"that",
"SemiSLClsHead",
"parameters",
"check",
"with",
"ValueError."
] | def test_build_semisl_cls_head_value_error(self):
with pytest.raises(ValueError):
self.head_cfg['num_classes'] = 0
build_head(self.head_cfg)
with pytest.raises(ValueError):
self.head_cfg['num_classes'] = -1
build_head(self.head_cfg)
with pytest.raises(ValueError):
sel... | ['def', 'test_build_semisl_cls_head_value_error(self):', 'with', 'pytest.raises(ValueError):', "self.head_cfg['num_classes']", '=', '0', 'build_head(self.head_cfg)', 'with', 'pytest.raises(ValueError):', "self.head_cfg['num_classes']", '=', '-1', 'build_head(self.head_cfg)', 'with', 'pytest.raises(ValueError):', "self.... | 919,280 |
openvinotoolkit/training_extensions | test_semisl_cls_head.py | TestSemiSLClsHead.test_forward | test_forward | Verifies that SemiSLClsHead forward function works. | [
"Verifies",
"that",
"SemiSLClsHead",
"forward",
"function",
"works."
] | def test_forward(self, mocker):
head = build_head(self.head_cfg)
labeled_batch_size = 16
unlabeled_batch_size = 64
dummy_gt = torch.randint(self.num_classes, (labeled_batch_size,))
labeled = torch.rand(labeled_batch_size, self.in_channels)
unlabeled_weak = torch.rand(unlabeled_batch_size, self.i... | ['def', 'test_forward(self,', 'mocker):', 'head', '=', 'build_head(self.head_cfg)', 'labeled_batch_size', '=', '16', 'unlabeled_batch_size', '=', '64', 'dummy_gt', '=', 'torch.randint(self.num_classes,', '(labeled_batch_size,))', 'labeled', '=', 'torch.rand(labeled_batch_size,', 'self.in_channels)', 'unlabeled_weak', '... | 919,281 |
openvinotoolkit/training_extensions | test_semisl_cls_head.py | TestSemiSLClsHead.test_simple_test | test_simple_test | Verifies that SemiSLClsHead simple_test function works. | [
"Verifies",
"that",
"SemiSLClsHead",
"simple_test",
"function",
"works."
] | def test_simple_test(self):
head = build_head(self.head_cfg)
dummy_feature = torch.rand(3, self.in_channels)
features = head.simple_test(dummy_feature)
assert len(features) == 3
assert len(features[0]) == self.num_classes | ['def', 'test_simple_test(self):', 'head', '=', 'build_head(self.head_cfg)', 'dummy_feature', '=', 'torch.rand(3,', 'self.in_channels)', 'features', '=', 'head.simple_test(dummy_feature)', 'assert', 'len(features)', '==', '3', 'assert', 'len(features[0])', '==', 'self.num_classes'] | 919,282 |
openvinotoolkit/training_extensions | test_selfsl_mlp.py | TestSelfSLMLP.test_init_weights_undefined_initialization | test_init_weights_undefined_initialization | Test init_weights function when undefined initialization is given. | [
"Test",
"init_weights",
"function",
"when",
"undefined",
"initialization",
"is",
"given."
] | def test_init_weights_undefined_initialization(self, init_linear: str) -> None:
selfslmlp = SelfSLMLP(in_channels=2, hid_channels=2, out_channels=2, use_conv=False, with_avg_pool=True)
with pytest.raises(ValueError):
selfslmlp.init_weights(init_linear) | ['def', 'test_init_weights_undefined_initialization(self,', 'init_linear:', 'str)', '->', 'None:', 'selfslmlp', '=', 'SelfSLMLP(in_channels=2,', 'hid_channels=2,', 'out_channels=2,', 'use_conv=False,', 'with_avg_pool=True)', 'with', 'pytest.raises(ValueError):', 'selfslmlp.init_weights(init_linear)'] | 919,285 |
openvinotoolkit/training_extensions | test_selfsl_mlp.py | TestSelfSLMLP.test_forward_tensor | test_forward_tensor | Test forward function for tensor. | [
"Test",
"forward",
"function",
"for",
"tensor."
] | def test_forward_tensor(self, inputs: torch.Tensor, norm_cfg: Dict, use_conv: bool, with_avg_pool: bool, expected: torch.Size) -> None:
selfslmlp = SelfSLMLP(in_channels=2, hid_channels=2, out_channels=2, norm_cfg=norm_cfg, use_conv=use_conv, with_avg_pool=with_avg_pool)
results = selfslmlp(inputs)
assert r... | ['def', 'test_forward_tensor(self,', 'inputs:', 'torch.Tensor,', 'norm_cfg:', 'Dict,', 'use_conv:', 'bool,', 'with_avg_pool:', 'bool,', 'expected:', 'torch.Size)', '->', 'None:', 'selfslmlp', '=', 'SelfSLMLP(in_channels=2,', 'hid_channels=2,', 'out_channels=2,', 'norm_cfg=norm_cfg,', 'use_conv=use_conv,', 'with_avg_poo... | 919,286 |
openvinotoolkit/training_extensions | test_selfsl_mlp.py | TestSelfSLMLP.test_forward_unsupported_format | test_forward_unsupported_format | Test forward function for unsupported format. | [
"Test",
"forward",
"function",
"for",
"unsupported",
"format."
] | def test_forward_unsupported_format(self, inputs: str) -> None:
selfslmlp = SelfSLMLP(in_channels=2, hid_channels=2, out_channels=2)
with pytest.raises(TypeError):
selfslmlp(inputs) | ['def', 'test_forward_unsupported_format(self,', 'inputs:', 'str)', '->', 'None:', 'selfslmlp', '=', 'SelfSLMLP(in_channels=2,', 'hid_channels=2,', 'out_channels=2)', 'with', 'pytest.raises(TypeError):', 'selfslmlp(inputs)'] | 919,288 |
openvinotoolkit/training_extensions | test_early_stopping_hook.py | TestEarlyStoppingHook.test_init_rule | test_init_rule | Test funciton for init_rule function. | [
"Test",
"funciton",
"for",
"init_rule",
"function."
] | def test_init_rule(self) -> None:
hook = EarlyStoppingHook(interval=5)
with pytest.raises(KeyError):
hook._init_rule('Invalid Key', 'Invalid Indicator')
with pytest.raises(ValueError):
hook._init_rule(None, 'Invalid Indicator')
hook._init_rule('greater', 'acc')
assert hook.rule == 'g... | ['def', 'test_init_rule(self)', '->', 'None:', 'hook', '=', 'EarlyStoppingHook(interval=5)', 'with', 'pytest.raises(KeyError):', "hook._init_rule('Invalid", "Key',", "'Invalid", "Indicator')", 'with', 'pytest.raises(ValueError):', 'hook._init_rule(None,', "'Invalid", "Indicator')", "hook._init_rule('greater',", "'acc')... | 919,289 |
openvinotoolkit/training_extensions | test_early_stopping_hook.py | TestReduceLROnPlateauLrUpdaterHook.test_before_run | test_before_run | Test function for before_run. | [
"Test",
"function",
"for",
"before_run."
] | def test_before_run(self) -> None:
hook = ReduceLROnPlateauLrUpdaterHook(interval=5, min_lr=1e-05)
runner = MockRunner()
hook.before_run(runner)
assert hook.base_lr == [0.0001]
assert hook.bad_count == 0
assert hook.last_iter == 0
assert hook.current_lr == -1.0
assert hook.best_score == ... | ['def', 'test_before_run(self)', '->', 'None:', 'hook', '=', 'ReduceLROnPlateauLrUpdaterHook(interval=5,', 'min_lr=1e-05)', 'runner', '=', 'MockRunner()', 'hook.before_run(runner)', 'assert', 'hook.base_lr', '==', '[0.0001]', 'assert', 'hook.bad_count', '==', '0', 'assert', 'hook.last_iter', '==', '0', 'assert', 'hook.... | 919,293 |
openvinotoolkit/training_extensions | test_eval_hook.py | test_single_gpu_test | test_single_gpu_test | Test function for single_gpu_test. | [
"Test",
"function",
"for",
"single_gpu_test."
] | def test_single_gpu_test() -> None:
class _MockModel(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, *args, **kwargs):
return torch.Tensor([0])
model = _MockModel()
single_gpu_test(model, MockDataloader()) | ['def', 'test_single_gpu_test()', '->', 'None:', 'class', '_MockModel(torch.nn.Module):', 'def', '__init__(self):', 'super().__init__()', 'def', 'forward(self,', '*args,', '**kwargs):', 'return', 'torch.Tensor([0])', 'model', '=', '_MockModel()', 'single_gpu_test(model,', 'MockDataloader())'] | 919,294 |
openvinotoolkit/training_extensions | test_augments.py | TestAugment.test_rotate_with_list_interpolation_instance | test_rotate_with_list_interpolation_instance | Test whether list of interpolation instances are accepted. | [
"Test",
"whether",
"list",
"of",
"interpolation",
"instances",
"are",
"accepted."
] | def test_rotate_with_list_interpolation_instance(self, image: Image.Image) -> None:
result = Augments.rotate(image, 45, resample=[Image.BICUBIC, Image.BILINEAR])
assert isinstance(result, Image.Image) | ['def', 'test_rotate_with_list_interpolation_instance(self,', 'image:', 'Image.Image)', '->', 'None:', 'result', '=', 'Augments.rotate(image,', '45,', 'resample=[Image.BICUBIC,', 'Image.BILINEAR])', 'assert', 'isinstance(result,', 'Image.Image)'] | 919,297 |
openvinotoolkit/training_extensions | test_augments.py | TestCythonAugments.test_blend | test_blend | Test that it raises an assertion error if dst is not a numpy array. | [
"Test",
"that",
"it",
"raises",
"an",
"assertion",
"error",
"if",
"dst",
"is",
"not",
"a",
"numpy",
"array."
] | def test_blend(self, image: Image.Image) -> None:
with pytest.raises(AssertionError):
CythonAugments.blend(image, image, 0.5) | ['def', 'test_blend(self,', 'image:', 'Image.Image)', '->', 'None:', 'with', 'pytest.raises(AssertionError):', 'CythonAugments.blend(image,', 'image,', '0.5)'] | 919,300 |
openvinotoolkit/training_extensions | test_random_augment.py | TestOTXRandAugment.test_with_default_arguments | test_with_default_arguments | Test case with default arguments. | [
"Test",
"case",
"with",
"default",
"arguments."
] | def test_with_default_arguments(self, mocker, sample_np_image: np.ndarray) -> None:
mocker.patch('random.random', return_value=0.1)
transform = OTXRandAugment(num_aug=2, magnitude=5, cutout_value=16)
data = {'img': sample_np_image}
results = transform(data)
assert isinstance(results['img'], np.ndarr... | ['def', 'test_with_default_arguments(self,', 'mocker,', 'sample_np_image:', 'np.ndarray)', '->', 'None:', "mocker.patch('random.random',", 'return_value=0.1)', 'transform', '=', 'OTXRandAugment(num_aug=2,', 'magnitude=5,', 'cutout_value=16)', 'data', '=', "{'img':", 'sample_np_image}', 'results', '=', 'transform(data)'... | 919,302 |
openvinotoolkit/training_extensions | test_random_augment.py | TestOTXRandAugment.test_with_img_fields_argument | test_with_img_fields_argument | Test case with img_fields argument. | [
"Test",
"case",
"with",
"img_fields",
"argument."
] | def test_with_img_fields_argument(self, mocker, sample_np_image: np.ndarray) -> None:
mocker.patch('random.random', return_value=0.1)
transform = OTXRandAugment(num_aug=2, magnitude=5, cutout_value=16)
data = {'img1': sample_np_image, 'img2': sample_np_image, 'img_fields': ['img1']}
results = transform(... | ['def', 'test_with_img_fields_argument(self,', 'mocker,', 'sample_np_image:', 'np.ndarray)', '->', 'None:', "mocker.patch('random.random',", 'return_value=0.1)', 'transform', '=', 'OTXRandAugment(num_aug=2,', 'magnitude=5,', 'cutout_value=16)', 'data', '=', "{'img1':", 'sample_np_image,', "'img2':", 'sample_np_image,',... | 919,303 |
openvinotoolkit/training_extensions | test_twocrop_transform.py | test_TwoCropTransform | test_TwoCropTransform | Test the TwoCropTransform instance. | [
"Test",
"the",
"TwoCropTransform",
"instance."
] | def test_TwoCropTransform() -> None:
data = {}
data['img'] = np.ones((224, 224, 3), dtype=np.uint8)
data['gt_label'] = 0
pipeline = [dict(type='Resize', size=(256, 256)), dict(type='RandomCrop', size=(224, 224)), dict(type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375]), dict(t... | ['def', 'test_TwoCropTransform()', '->', 'None:', 'data', '=', '{}', "data['img']", '=', 'np.ones((224,', '224,', '3),', 'dtype=np.uint8)', "data['gt_label']", '=', '0', 'pipeline', '=', "[dict(type='Resize',", 'size=(256,', '256)),', "dict(type='RandomCrop',", 'size=(224,', '224)),', "dict(type='Normalize',", 'mean=[1... | 919,305 |
openvinotoolkit/training_extensions | test_helpers.py | generate_random_torch_image | generate_random_torch_image | Generate random torch tensor image. | [
"Generate",
"random",
"torch",
"tensor",
"image."
] | def generate_random_torch_image(batch=1, width=3, height=3, channels=3, channel_last=False):
if channel_last is False:
img = torch.rand(batch, channels, height, width)
else:
img = torch.rand(batch, height, width, channels)
return img | ['def', 'generate_random_torch_image(batch=1,', 'width=3,', 'height=3,', 'channels=3,', 'channel_last=False):', 'if', 'channel_last', 'is', 'False:', 'img', '=', 'torch.rand(batch,', 'channels,', 'height,', 'width)', 'else:', 'img', '=', 'torch.rand(batch,', 'height,', 'width,', 'channels)', 'return', 'img'] | 919,306 |
openvinotoolkit/training_extensions | test_task.py | TestMMDetectionTask.test_det_evaluate | test_det_evaluate | Test evaluate function for detection. | [
"Test",
"evaluate",
"function",
"for",
"detection."
] | def test_det_evaluate(self) -> None:
_config = ModelConfiguration(DetectionConfig(), self.det_label_schema)
_model = ModelEntity(self.det_dataset, _config)
resultset = ResultSetEntity(_model, self.det_dataset, self.det_dataset)
self.det_task.evaluate(resultset)
assert resultset.performance.score.val... | ['def', 'test_det_evaluate(self)', '->', 'None:', '_config', '=', 'ModelConfiguration(DetectionConfig(),', 'self.det_label_schema)', '_model', '=', 'ModelEntity(self.det_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.det_dataset,', 'self.det_dataset)', 'self.det_task.evaluate(resultset)', 'as... | 919,309 |
openvinotoolkit/training_extensions | test_task.py | TestMMDetectionTask.test_det_evaluate_with_empty_annotations | test_det_evaluate_with_empty_annotations | Test evaluate function for detection with empty predictions. | [
"Test",
"evaluate",
"function",
"for",
"detection",
"with",
"empty",
"predictions."
] | def test_det_evaluate_with_empty_annotations(self) -> None:
_config = ModelConfiguration(DetectionConfig(), self.det_label_schema)
_model = ModelEntity(self.det_dataset, _config)
resultset = ResultSetEntity(_model, self.det_dataset, self.det_dataset.with_empty_annotations())
self.det_task.evaluate(resul... | ['def', 'test_det_evaluate_with_empty_annotations(self)', '->', 'None:', '_config', '=', 'ModelConfiguration(DetectionConfig(),', 'self.det_label_schema)', '_model', '=', 'ModelEntity(self.det_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.det_dataset,', 'self.det_dataset.with_empty_annotatio... | 919,310 |
openvinotoolkit/training_extensions | test_task.py | TestMMDetectionTask.test_iseg_evaluate | test_iseg_evaluate | Test evaluate function for instance segmentation. | [
"Test",
"evaluate",
"function",
"for",
"instance",
"segmentation."
] | def test_iseg_evaluate(self) -> None:
_config = ModelConfiguration(DetectionConfig(), self.iseg_label_schema)
_model = ModelEntity(self.iseg_dataset, _config)
resultset = ResultSetEntity(_model, self.iseg_dataset, self.iseg_dataset)
self.iseg_task.evaluate(resultset)
assert resultset.performance.sco... | ['def', 'test_iseg_evaluate(self)', '->', 'None:', '_config', '=', 'ModelConfiguration(DetectionConfig(),', 'self.iseg_label_schema)', '_model', '=', 'ModelEntity(self.iseg_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.iseg_dataset,', 'self.iseg_dataset)', 'self.iseg_task.evaluate(resultset)... | 919,311 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestColorJitter.test_call | test_call | Test __call__ method of ColorJitter. | [
"Test",
"__call__",
"method",
"of",
"ColorJitter."
] | def test_call(self, data: dict[str, np.ndarray]) -> None:
transform = ColorJitter()
outputs = transform(data)
assert outputs.keys() == data.keys()
assert np.array_equal(outputs['img'], data['img']) | ['def', 'test_call(self,', 'data:', 'dict[str,', 'np.ndarray])', '->', 'None:', 'transform', '=', 'ColorJitter()', 'outputs', '=', 'transform(data)', 'assert', 'outputs.keys()', '==', 'data.keys()', 'assert', "np.array_equal(outputs['img'],", "data['img'])"] | 919,316 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestColorJitter.test_repr | test_repr | Test __repr__ method of ColorJitter. | [
"Test",
"__repr__",
"method",
"of",
"ColorJitter."
] | def test_repr(self) -> None:
transform = ColorJitter(brightness=0.2)
assert str(transform) in ['ColorJitter(brightness=[0.8, 1.2], contrast=None, saturation=None, hue=None)', 'ColorJitter(brightness=(0.8, 1.2), contrast=None, saturation=None, hue=None)'] | ['def', 'test_repr(self)', '->', 'None:', 'transform', '=', 'ColorJitter(brightness=0.2)', 'assert', 'str(transform)', 'in', "['ColorJitter(brightness=[0.8,", '1.2],', 'contrast=None,', 'saturation=None,', "hue=None)',", "'ColorJitter(brightness=(0.8,", '1.2),', 'contrast=None,', 'saturation=None,', "hue=None)']"] | 919,317 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestRandomGaussianBlur.test_repr | test_repr | Test __repr__ method of RandomGaussianBlur. | [
"Test",
"__repr__",
"method",
"of",
"RandomGaussianBlur."
] | def test_repr(self) -> None:
pipeline = RandomGaussianBlur(0.1, 2.0)
assert repr(pipeline) == 'RandomGaussianBlur' | ['def', 'test_repr(self)', '->', 'None:', 'pipeline', '=', 'RandomGaussianBlur(0.1,', '2.0)', 'assert', 'repr(pipeline)', '==', "'RandomGaussianBlur'"] | 919,318 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestRandomApply.test_random_apply_with | test_random_apply_with | Test RandomApply with a single transform. | [
"Test",
"RandomApply",
"with",
"a",
"single",
"transform."
] | def test_random_apply_with(self) -> None:
transform_cfgs = [dict(type='ColorJitter', brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1)]
random_apply = RandomApply(transform_cfgs, p=0.0)
inputs = {'img': Image.fromarray(np.ones((256, 256, 3), dtype=np.uint8))}
results = random_apply(inputs)
asse... | ['def', 'test_random_apply_with(self)', '->', 'None:', 'transform_cfgs', '=', "[dict(type='ColorJitter',", 'brightness=0.4,', 'contrast=0.4,', 'saturation=0.4,', 'hue=0.1)]', 'random_apply', '=', 'RandomApply(transform_cfgs,', 'p=0.0)', 'inputs', '=', "{'img':", 'Image.fromarray(np.ones((256,', '256,', '3),', 'dtype=np... | 919,319 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestNDArrayToPILImage.test_rept | test_rept | Test __repr__ method of NDArrayToPILImage. | [
"Test",
"__repr__",
"method",
"of",
"NDArrayToPILImage."
] | def test_rept(self) -> None:
pipeline = NDArrayToPILImage(keys=['image'])
assert repr(pipeline) == 'NDArrayToPILImage' | ['def', 'test_rept(self)', '->', 'None:', 'pipeline', '=', "NDArrayToPILImage(keys=['image'])", 'assert', 'repr(pipeline)', '==', "'NDArrayToPILImage'"] | 919,322 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestPILImageToNDArray.test_call | test_call | Test __call__ method of PILImageToNDArray. | [
"Test",
"__call__",
"method",
"of",
"PILImageToNDArray."
] | def test_call(self, data: dict[str, np.ndarray]) -> None:
pipeline = PILImageToNDArray(keys=['image'])
data = {'image': Image.fromarray(data['img'])}
output = pipeline(data)
assert isinstance(output['image'], np.ndarray)
assert output['image'].shape == (256, 256, 3) | ['def', 'test_call(self,', 'data:', 'dict[str,', 'np.ndarray])', '->', 'None:', 'pipeline', '=', "PILImageToNDArray(keys=['image'])", 'data', '=', "{'image':", "Image.fromarray(data['img'])}", 'output', '=', 'pipeline(data)', 'assert', "isinstance(output['image'],", 'np.ndarray)', 'assert', "output['image'].shape", '==... | 919,323 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestPILImageToNDArray.test_repr | test_repr | Test __repr__ method of PILImageToNDArray. | [
"Test",
"__repr__",
"method",
"of",
"PILImageToNDArray."
] | def test_repr(self) -> None:
pipeline = PILImageToNDArray(keys=['image'])
assert repr(pipeline) == 'PILImageToNDArray' | ['def', 'test_repr(self)', '->', 'None:', 'pipeline', '=', "PILImageToNDArray(keys=['image'])", 'assert', 'repr(pipeline)', '==', "'PILImageToNDArray'"] | 919,324 |
openvinotoolkit/training_extensions | test_custom_max_iou_assigner.py | TestCustomMaxIoUAssigner.test_assign_cpu | test_assign_cpu | Test custom assign function on cpu. | [
"Test",
"custom",
"assign",
"function",
"on",
"cpu."
] | def test_assign_cpu(self):
gt_bboxes = torch.randn(350, 4)
bboxes = torch.randn(20000, 4)
assign_result = self.assigner.assign(bboxes, gt_bboxes)
assert assign_result.gt_inds.shape == torch.Size([20000])
assert assign_result.max_overlaps.shape == torch.Size([20000]) | ['def', 'test_assign_cpu(self):', 'gt_bboxes', '=', 'torch.randn(350,', '4)', 'bboxes', '=', 'torch.randn(20000,', '4)', 'assign_result', '=', 'self.assigner.assign(bboxes,', 'gt_bboxes)', 'assert', 'assign_result.gt_inds.shape', '==', 'torch.Size([20000])', 'assert', 'assign_result.max_overlaps.shape', '==', 'torch.Si... | 919,329 |
openvinotoolkit/training_extensions | test_task.py | TestOTXDetTaskNNCF.test_save_model | test_save_model | Test save_model method in OTXDetTaskNNCF. | [
"Test",
"save_model",
"method",
"in",
"OTXDetTaskNNCF."
] | def test_save_model(self, mocker):
mocker.patch('torch.load', return_value='')
self.det_nncf_task._recipe_cfg = Config({'model': {'bbox_head': {'anchor_generator': {'reclustering_anchors': True, 'heights': [10], 'widths': [10]}}}})
self.det_nncf_task.config = self.det_nncf_task._recipe_cfg
self.det_nncf... | ['def', 'test_save_model(self,', 'mocker):', "mocker.patch('torch.load',", "return_value='')", 'self.det_nncf_task._recipe_cfg', '=', "Config({'model':", "{'bbox_head':", "{'anchor_generator':", "{'reclustering_anchors':", 'True,', "'heights':", '[10],', "'widths':", '[10]}}}})', 'self.det_nncf_task.config', '=', 'self... | 919,337 |
openvinotoolkit/training_extensions | test_task.py | TestOTXDetTaskNNCF.test_optimize | test_optimize | Test optimize method in OTXDetTaskNNCF. | [
"Test",
"optimize",
"method",
"in",
"OTXDetTaskNNCF."
] | def test_optimize(self, mocker):
(self.dataset, _) = generate_det_dataset(task_type=TaskType.DETECTION)
mock_lcurve_val = OTXLoggerHook.Curve()
mock_lcurve_val.x = [0, 1]
mock_lcurve_val.y = [0.1, 0.2]
mock_run_task = mocker.patch.object(DetectionNNCFTask, '_train_model', return_value={'final_ckpt':... | ['def', 'test_optimize(self,', 'mocker):', '(self.dataset,', '_)', '=', 'generate_det_dataset(task_type=TaskType.DETECTION)', 'mock_lcurve_val', '=', 'OTXLoggerHook.Curve()', 'mock_lcurve_val.x', '=', '[0,', '1]', 'mock_lcurve_val.y', '=', '[0.1,', '0.2]', 'mock_run_task', '=', 'mocker.patch.object(DetectionNNCFTask,',... | 919,338 |
openvinotoolkit/training_extensions | test_detection_config_utils.py | test_patch_samples_per_gpu | test_patch_samples_per_gpu | Test samples per gpu function works correctly. | [
"Test",
"samples",
"per",
"gpu",
"function",
"works",
"correctly."
] | def test_patch_samples_per_gpu(model_cfg):
cfg = OTXConfig.fromfile(model_cfg)
model_template = parse_model_template(Path(model_cfg).parent / 'template.yaml')
hyper_parameters = create(model_template.hyper_parameters.data)
patch_from_hyperparams(cfg, hyper_parameters)
params = hyper_parameters.learn... | ['def', 'test_patch_samples_per_gpu(model_cfg):', 'cfg', '=', 'OTXConfig.fromfile(model_cfg)', 'model_template', '=', 'parse_model_template(Path(model_cfg).parent', '/', "'template.yaml')", 'hyper_parameters', '=', 'create(model_template.hyper_parameters.data)', 'patch_from_hyperparams(cfg,', 'hyper_parameters)', 'para... | 919,340 |
openvinotoolkit/training_extensions | test_task.py | TestOpenVINORotatedRectInferencer.test_pre_process | test_pre_process | Test pre_process method in RotatedRectInferencer. | [
"Test",
"pre_process",
"method",
"in",
"RotatedRectInferencer."
] | def test_pre_process(self):
self.ov_inferencer.model.preprocess.return_value = (None, {'foo': 'bar'})
returned_value = self.ov_inferencer.pre_process(self.fake_input)
assert returned_value == (None, {'foo': 'bar'}) | ['def', 'test_pre_process(self):', 'self.ov_inferencer.model.preprocess.return_value', '=', '(None,', "{'foo':", "'bar'})", 'returned_value', '=', 'self.ov_inferencer.pre_process(self.fake_input)', 'assert', 'returned_value', '==', '(None,', "{'foo':", "'bar'})"] | 919,345 |
openvinotoolkit/training_extensions | test_task.py | TestOpenVINODetectionTask.test_infer | test_infer | Test infer method in OpenVINODetectionTask. | [
"Test",
"infer",
"method",
"in",
"OpenVINODetectionTask."
] | def test_infer(self, mocker):
(self.dataset, labels) = generate_det_dataset(task_type=TaskType.DETECTION)
fake_ann_scene = self.dataset[0].annotation_scene
mock_predict = mocker.patch.object(OpenVINODetectionInferencer, 'predict', return_value=(fake_ann_scene, (None, None)))
updated_dataset = self.ov_ta... | ['def', 'test_infer(self,', 'mocker):', '(self.dataset,', 'labels)', '=', 'generate_det_dataset(task_type=TaskType.DETECTION)', 'fake_ann_scene', '=', 'self.dataset[0].annotation_scene', 'mock_predict', '=', 'mocker.patch.object(OpenVINODetectionInferencer,', "'predict',", 'return_value=(fake_ann_scene,', '(None,', 'No... | 919,346 |
openvinotoolkit/training_extensions | test_task.py | TestOpenVINODetectionTask.test_infer_async | test_infer_async | Test async infer method in OpenVINODetectionTask. | [
"Test",
"async",
"infer",
"method",
"in",
"OpenVINODetectionTask."
] | def test_infer_async(self, mocker):
(self.dataset, labels) = generate_det_dataset(task_type=TaskType.DETECTION)
mock_pre_process = mocker.patch.object(OpenVINODetectionInferencer, 'pre_process', return_value=(None, {'foo', 'bar'}))
updated_dataset = self.ov_task.infer(self.dataset, InferenceParameters(enabl... | ['def', 'test_infer_async(self,', 'mocker):', '(self.dataset,', 'labels)', '=', 'generate_det_dataset(task_type=TaskType.DETECTION)', 'mock_pre_process', '=', 'mocker.patch.object(OpenVINODetectionInferencer,', "'pre_process',", 'return_value=(None,', "{'foo',", "'bar'}))", 'updated_dataset', '=', 'self.ov_task.infer(s... | 919,347 |
openvinotoolkit/training_extensions | test_task.py | TestOpenVINODetectionTask.test_evaluate | test_evaluate | Test evaluate method in OpenVINODetectionTask. | [
"Test",
"evaluate",
"method",
"in",
"OpenVINODetectionTask."
] | def test_evaluate(self, mocker):
result_set = ResultSetEntity(model=None, ground_truth_dataset=DatasetEntity(), prediction_dataset=DatasetEntity())
fake_metrics = mocker.patch('otx.api.usecases.evaluation.f_measure.FMeasure', autospec=True)
fake_metrics.get_performance.return_value = Performance(score=Score... | ['def', 'test_evaluate(self,', 'mocker):', 'result_set', '=', 'ResultSetEntity(model=None,', 'ground_truth_dataset=DatasetEntity(),', 'prediction_dataset=DatasetEntity())', 'fake_metrics', '=', "mocker.patch('otx.api.usecases.evaluation.f_measure.FMeasure',", 'autospec=True)', 'fake_metrics.get_performance.return_value... | 919,348 |
openvinotoolkit/training_extensions | test_tiling_detection.py | create_otx_dataset | create_otx_dataset | Create a random OTX dataset. | [
"Create",
"a",
"random",
"OTX",
"dataset."
] | def create_otx_dataset(height: int, width: int, labels: List[str], domain: Domain=Domain.DETECTION):
labels = []
for label in ['rectangle', 'ellipse', 'triangle']:
labels.append(LabelEntity(name=label, domain=domain))
(image, anno_list) = generate_random_annotated_image(width, height, labels)
im... | ['def', 'create_otx_dataset(height:', 'int,', 'width:', 'int,', 'labels:', 'List[str],', 'domain:', 'Domain=Domain.DETECTION):', 'labels', '=', '[]', 'for', 'label', 'in', "['rectangle',", "'ellipse',", "'triangle']:", 'labels.append(LabelEntity(name=label,', 'domain=domain))', '(image,', 'anno_list)', '=', 'generate_r... | 919,351 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.