code-loader 1.0.216.dev0__py3-none-any.whl → 1.0.218.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- code_loader/__init__.py +1 -1
- code_loader/contract/datasetclasses.py +5 -0
- code_loader/contract/responsedataclasses.py +8 -0
- code_loader/inner_leap_binder/fp_confidence_contract.py +88 -0
- code_loader/inner_leap_binder/leapbinder.py +13 -2
- code_loader/inner_leap_binder/leapbinder_decorators.py +20 -5
- code_loader/leaploader.py +26 -7
- code_loader/mixpanel_tracker.py +16 -5
- {code_loader-1.0.216.dev0.dist-info → code_loader-1.0.218.dev0.dist-info}/METADATA +1 -1
- {code_loader-1.0.216.dev0.dist-info → code_loader-1.0.218.dev0.dist-info}/RECORD +12 -11
- {code_loader-1.0.216.dev0.dist-info → code_loader-1.0.218.dev0.dist-info}/LICENSE +0 -0
- {code_loader-1.0.216.dev0.dist-info → code_loader-1.0.218.dev0.dist-info}/WHEEL +0 -0
code_loader/__init__.py
CHANGED
|
@@ -5,6 +5,6 @@ from code_loader.experiment_api.client import Client
|
|
|
5
5
|
|
|
6
6
|
try:
|
|
7
7
|
from code_loader.mixpanel_tracker import track_code_loader_loaded
|
|
8
|
-
track_code_loader_loaded({'
|
|
8
|
+
track_code_loader_loaded({'load_trigger': 'module_import'})
|
|
9
9
|
except Exception:
|
|
10
10
|
pass
|
|
@@ -179,6 +179,8 @@ class ElementInstance:
|
|
|
179
179
|
# Per-instance metric values keyed by the registered name of a tensorleap_custom_instances_metric.
|
|
180
180
|
# Only meaningful on false-positive instances (they have no ground-truth row for the metric to run on).
|
|
181
181
|
instance_metrics: Optional[Dict[str, float]] = None
|
|
182
|
+
score: Optional[float] = None
|
|
183
|
+
matched_gt: Optional[bool] = None
|
|
182
184
|
|
|
183
185
|
SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
|
|
184
186
|
InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse, int], Optional[ElementInstance]]
|
|
@@ -335,6 +337,9 @@ class ElementInstanceMasksHandler:
|
|
|
335
337
|
class FalsePositiveInstancesHandler:
|
|
336
338
|
name: str
|
|
337
339
|
function: Callable[..., Any]
|
|
340
|
+
operating_threshold: Optional[float] = None
|
|
341
|
+
candidate_floor: Optional[float] = None
|
|
342
|
+
max_candidates_per_image: int = 30
|
|
338
343
|
|
|
339
344
|
@dataclass
|
|
340
345
|
class GroundTruthHandler(DatasetBaseHandler):
|
|
@@ -171,10 +171,18 @@ class LeapAnalysisConfiguration:
|
|
|
171
171
|
use_additional_set_as_unlabeled_candidate: Optional[bool] = None # None = engine default (ON); False keeps additional samples out of Label Next / Unlabelled Data / aggressor fixing
|
|
172
172
|
|
|
173
173
|
|
|
174
|
+
@dataclass
|
|
175
|
+
class FalsePositiveConfidenceConfig:
|
|
176
|
+
operating_threshold: float
|
|
177
|
+
candidate_floor: float
|
|
178
|
+
max_candidates_per_image: int
|
|
179
|
+
|
|
180
|
+
|
|
174
181
|
@dataclass
|
|
175
182
|
class EngineFileContract:
|
|
176
183
|
node_connections: Optional[List[NodeConnection]] = None
|
|
177
184
|
leap_analysis_configuration: Optional[LeapAnalysisConfiguration] = None
|
|
185
|
+
false_positive_confidence: Optional[FalsePositiveConfidenceConfig] = None
|
|
178
186
|
|
|
179
187
|
|
|
180
188
|
@dataclass
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import warnings
|
|
3
|
+
from typing import Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from code_loader.contract.datasetclasses import ElementInstance, FalsePositiveInstancesHandler, \
|
|
8
|
+
DatasetIntegrationSetup
|
|
9
|
+
from code_loader.contract.enums import DataStateType, DatasetMetadataType
|
|
10
|
+
|
|
11
|
+
_PREFIX = "tensorleap_false_positive_instances_encoder validation failed: "
|
|
12
|
+
_LABELED_STATES = (DataStateType.training, DataStateType.validation, DataStateType.test)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _is_finite_number(value: object) -> bool:
|
|
16
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
|
|
17
|
+
return False
|
|
18
|
+
return math.isfinite(float(value))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_confidence_args(operating_threshold: Optional[float], candidate_floor: Optional[float],
|
|
22
|
+
max_candidates_per_image: int) -> None:
|
|
23
|
+
if operating_threshold is None:
|
|
24
|
+
if candidate_floor is not None or max_candidates_per_image != 30:
|
|
25
|
+
raise ValueError(_PREFIX + "candidate_floor and max_candidates_per_image require operating_threshold.")
|
|
26
|
+
return
|
|
27
|
+
if not _is_finite_number(operating_threshold):
|
|
28
|
+
raise ValueError(_PREFIX + f"operating_threshold should be a finite float. Got {operating_threshold!r}.")
|
|
29
|
+
if candidate_floor is None:
|
|
30
|
+
raise ValueError(_PREFIX + "candidate_floor is required when operating_threshold is declared.")
|
|
31
|
+
if not _is_finite_number(candidate_floor) or candidate_floor >= operating_threshold:
|
|
32
|
+
raise ValueError(_PREFIX + f"candidate_floor should be a finite float below operating_threshold "
|
|
33
|
+
f"({operating_threshold}). Got {candidate_floor!r}.")
|
|
34
|
+
if not isinstance(max_candidates_per_image, (int, np.integer)) or isinstance(max_candidates_per_image, bool) \
|
|
35
|
+
or max_candidates_per_image < 1:
|
|
36
|
+
raise ValueError(_PREFIX + f"max_candidates_per_image should be an int >= 1. "
|
|
37
|
+
f"Got {max_candidates_per_image!r}.")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def declare_confidence_metadata_types(setup_container: DatasetIntegrationSetup) -> None:
|
|
41
|
+
false_positive_instances = setup_container.false_positive_instances
|
|
42
|
+
if false_positive_instances is None or false_positive_instances.operating_threshold is None:
|
|
43
|
+
return
|
|
44
|
+
handler = next((handler for handler in setup_container.metadata
|
|
45
|
+
if handler.name == "builtin_instance_metadata"), None)
|
|
46
|
+
if handler is None:
|
|
47
|
+
return
|
|
48
|
+
declared: Dict[str, DatasetMetadataType] = {
|
|
49
|
+
'is_instance': DatasetMetadataType.string,
|
|
50
|
+
'original_sample_id': DatasetMetadataType.string,
|
|
51
|
+
'instance_name': DatasetMetadataType.string,
|
|
52
|
+
'is_false_positive': DatasetMetadataType.string,
|
|
53
|
+
'confidence': DatasetMetadataType.float,
|
|
54
|
+
'above_operating_threshold': DatasetMetadataType.string,
|
|
55
|
+
}
|
|
56
|
+
if isinstance(handler.metadata_type, dict):
|
|
57
|
+
for name, metadata_type in declared.items():
|
|
58
|
+
handler.metadata_type.setdefault(name, metadata_type)
|
|
59
|
+
else:
|
|
60
|
+
handler.metadata_type = declared
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def validate_confidence_contract(instances: List[ElementInstance], state: Optional[DataStateType],
|
|
64
|
+
handler: Optional[FalsePositiveInstancesHandler]) -> None:
|
|
65
|
+
if handler is None or handler.operating_threshold is None:
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
scores: List[float] = []
|
|
69
|
+
for j, instance in enumerate(instances):
|
|
70
|
+
if instance.score is None or not _is_finite_number(instance.score):
|
|
71
|
+
raise Exception(f"{_PREFIX}operating_threshold is declared, so element {j} of the returned list "
|
|
72
|
+
f"should have a finite float score. Got {instance.score!r}.")
|
|
73
|
+
scores.append(float(instance.score))
|
|
74
|
+
if handler.candidate_floor is not None and \
|
|
75
|
+
not np.float32(instance.score) >= np.float32(handler.candidate_floor):
|
|
76
|
+
raise Exception(f"{_PREFIX}score {instance.score!r} of element {j} is below candidate_floor "
|
|
77
|
+
f"{handler.candidate_floor}. Return only candidates with score >= candidate_floor.")
|
|
78
|
+
|
|
79
|
+
if state in _LABELED_STATES:
|
|
80
|
+
for j, instance in enumerate(instances):
|
|
81
|
+
if not isinstance(instance.matched_gt, (bool, np.bool_)):
|
|
82
|
+
raise Exception(f"{_PREFIX}matched_gt of element {j} should be a bool on the {state.value} state "
|
|
83
|
+
f"(True when the candidate matches a ground-truth instance). "
|
|
84
|
+
f"Got {instance.matched_gt!r}.")
|
|
85
|
+
|
|
86
|
+
if any(scores[i] < scores[i + 1] for i in range(len(scores) - 1)):
|
|
87
|
+
warnings.warn("tensorleap_false_positive_instances_encoder warning: the returned instances are not "
|
|
88
|
+
"sorted by score in descending order. Tensorleap sorts them.")
|
|
@@ -31,6 +31,8 @@ from code_loader.default_metrics import metrics_names_to_functions_and_direction
|
|
|
31
31
|
from code_loader.utils import to_numpy_return_wrapper, get_shape, to_numpy_return_masks_wrapper, \
|
|
32
32
|
to_numpy_return_fp_masks_wrapper
|
|
33
33
|
from code_loader.contract.sim_config import parse_sim_config, sample_sim_params
|
|
34
|
+
from code_loader.inner_leap_binder.fp_confidence_contract import validate_confidence_args, \
|
|
35
|
+
declare_confidence_metadata_types
|
|
34
36
|
from code_loader.visualizers.default_visualizers import DefaultVisualizer, \
|
|
35
37
|
default_graph_visualizer, \
|
|
36
38
|
default_image_visualizer, default_horizontal_bar_visualizer, default_word_visualizer, \
|
|
@@ -341,15 +343,24 @@ class LeapBinder:
|
|
|
341
343
|
self.setup_container.instance_masks.append(ElementInstanceMasksHandler(name, function))
|
|
342
344
|
|
|
343
345
|
|
|
344
|
-
def set_false_positive_instances(self, function: Callable[..., Any], name: str
|
|
346
|
+
def set_false_positive_instances(self, function: Callable[..., Any], name: str,
|
|
347
|
+
operating_threshold: Optional[float] = None,
|
|
348
|
+
candidate_floor: Optional[float] = None,
|
|
349
|
+
max_candidates_per_image: int = 30) -> None:
|
|
345
350
|
"""
|
|
346
351
|
Set the false-positive instances handler. It receives (sample_id, preprocess, predictions)
|
|
347
352
|
and returns a list of ElementInstance, one per false-positive prediction.
|
|
348
353
|
"""
|
|
349
354
|
if self.setup_container.false_positive_instances is not None:
|
|
350
355
|
raise Exception("only one tensorleap_false_positive_instances_encoder can be defined")
|
|
356
|
+
validate_confidence_args(operating_threshold, candidate_floor, max_candidates_per_image)
|
|
351
357
|
function = to_numpy_return_fp_masks_wrapper(function)
|
|
352
|
-
self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(
|
|
358
|
+
self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(
|
|
359
|
+
name, function,
|
|
360
|
+
float(operating_threshold) if operating_threshold is not None else None,
|
|
361
|
+
float(candidate_floor) if candidate_floor is not None else None,
|
|
362
|
+
int(max_candidates_per_image))
|
|
363
|
+
declare_confidence_metadata_types(self.setup_container)
|
|
353
364
|
|
|
354
365
|
def set_false_positive_empty_gt(self, function: Callable[..., Any], gt_name: str) -> None:
|
|
355
366
|
"""
|
|
@@ -39,6 +39,8 @@ from code_loader.contract.visualizer_classes import LeapImage, LeapImageMask, Le
|
|
|
39
39
|
LeapValidationError, map_leap_data_type_to_visualizer_class
|
|
40
40
|
from code_loader.inner_leap_binder.leapbinder import mapping_runtime_mode_env_var_mame, \
|
|
41
41
|
_reject_stringized_sample_preprocess_response
|
|
42
|
+
from code_loader.inner_leap_binder.fp_confidence_contract import validate_confidence_contract, \
|
|
43
|
+
validate_confidence_args, declare_confidence_metadata_types
|
|
42
44
|
from code_loader.mixpanel_tracker import clear_integration_events, AnalyticsEvent, emit_integration_event_once
|
|
43
45
|
|
|
44
46
|
_called_from_inside_tl_decorator = 0
|
|
@@ -3262,15 +3264,21 @@ def _register_builtin_instance_metadata() -> None:
|
|
|
3262
3264
|
makes the engine produce instance samples.
|
|
3263
3265
|
"""
|
|
3264
3266
|
if any(h.name == "builtin_instance_metadata" for h in leap_binder.setup_container.metadata):
|
|
3267
|
+
declare_confidence_metadata_types(leap_binder.setup_container)
|
|
3265
3268
|
return
|
|
3266
3269
|
|
|
3267
|
-
def builtin_instance_metadata(idx: str, preprocess: PreprocessResponse) -> Dict[str, str]:
|
|
3268
|
-
result = {'is_instance': '0', 'original_sample_id': idx, 'instance_name': 'none'}
|
|
3269
|
-
|
|
3270
|
+
def builtin_instance_metadata(idx: str, preprocess: PreprocessResponse) -> Dict[str, Optional[str]]:
|
|
3271
|
+
result: Dict[str, Optional[str]] = {'is_instance': '0', 'original_sample_id': idx, 'instance_name': 'none'}
|
|
3272
|
+
false_positive_instances = leap_binder.setup_container.false_positive_instances
|
|
3273
|
+
if false_positive_instances is not None:
|
|
3270
3274
|
result['is_false_positive'] = '0'
|
|
3275
|
+
if false_positive_instances.operating_threshold is not None:
|
|
3276
|
+
result['confidence'] = None
|
|
3277
|
+
result['above_operating_threshold'] = None
|
|
3271
3278
|
return result
|
|
3272
3279
|
|
|
3273
3280
|
leap_binder.set_metadata(builtin_instance_metadata, "builtin_instance_metadata")
|
|
3281
|
+
declare_confidence_metadata_types(leap_binder.setup_container)
|
|
3274
3282
|
|
|
3275
3283
|
|
|
3276
3284
|
def _register_builtin_instance_extra_metadata(metadata_types: Dict[str, DatasetMetadataType]) -> None:
|
|
@@ -3502,7 +3510,9 @@ def tensorleap_instances_masks_encoder(name: str):
|
|
|
3502
3510
|
|
|
3503
3511
|
|
|
3504
3512
|
def tensorleap_false_positive_instances_encoder(
|
|
3505
|
-
name: str, instance_metadata_types: Optional[Dict[str, DatasetMetadataType]] = None
|
|
3513
|
+
name: str, instance_metadata_types: Optional[Dict[str, DatasetMetadataType]] = None,
|
|
3514
|
+
operating_threshold: Optional[float] = None, candidate_floor: Optional[float] = None,
|
|
3515
|
+
max_candidates_per_image: int = 30):
|
|
3506
3516
|
"""Register the false-positive instances encoder.
|
|
3507
3517
|
|
|
3508
3518
|
`instance_metadata_types` declares the keys (and types) of the `instance_metadata` the returned
|
|
@@ -3510,6 +3520,8 @@ def tensorleap_false_positive_instances_encoder(
|
|
|
3510
3520
|
with any keys the element-instance preprocess declares; a key not declared here (or by the
|
|
3511
3521
|
GT instances) is dropped from false-positive rows by the engine.
|
|
3512
3522
|
"""
|
|
3523
|
+
validate_confidence_args(operating_threshold, candidate_floor, max_candidates_per_image)
|
|
3524
|
+
|
|
3513
3525
|
def decorating_function(user_function: Callable):
|
|
3514
3526
|
def _validate_input_args(sample_id, preprocess_response, predictions):
|
|
3515
3527
|
assert isinstance(sample_id, (str, int)), \
|
|
@@ -3542,7 +3554,8 @@ def tensorleap_false_positive_instances_encoder(
|
|
|
3542
3554
|
|
|
3543
3555
|
return result
|
|
3544
3556
|
|
|
3545
|
-
leap_binder.set_false_positive_instances(inner_without_validate, name
|
|
3557
|
+
leap_binder.set_false_positive_instances(inner_without_validate, name, operating_threshold, candidate_floor,
|
|
3558
|
+
max_candidates_per_image)
|
|
3546
3559
|
_register_builtin_instance_metadata()
|
|
3547
3560
|
if instance_metadata_types:
|
|
3548
3561
|
_register_builtin_instance_extra_metadata(instance_metadata_types)
|
|
@@ -3556,6 +3569,8 @@ def tensorleap_false_positive_instances_encoder(
|
|
|
3556
3569
|
result = inner_without_validate(sample_id, preprocess_response, predictions)
|
|
3557
3570
|
|
|
3558
3571
|
_validate_result(result)
|
|
3572
|
+
validate_confidence_contract(result, preprocess_response.state,
|
|
3573
|
+
leap_binder.setup_container.false_positive_instances)
|
|
3559
3574
|
return result
|
|
3560
3575
|
|
|
3561
3576
|
return inner
|
code_loader/leaploader.py
CHANGED
|
@@ -18,7 +18,8 @@ from code_loader.contract.datasetclasses import DatasetSample, DatasetBaseHandle
|
|
|
18
18
|
PreprocessResponse, VisualizerHandler, LeapData, \
|
|
19
19
|
PredictionTypeHandler, MetadataHandler, CustomLayerHandler, MetricHandler, VisualizerHandlerData, MetricHandlerData, \
|
|
20
20
|
MetricCallableReturnType, CustomLossHandlerData, CustomLossHandler, RawInputsForHeatmap, SamplePreprocessResponse, \
|
|
21
|
-
ElementInstance, custom_latent_space_attribute, DatasetIntegrationSetup, InstanceMetricHandler, _simulation_context
|
|
21
|
+
ElementInstance, custom_latent_space_attribute, DatasetIntegrationSetup, InstanceMetricHandler, _simulation_context, \
|
|
22
|
+
FalsePositiveInstancesHandler
|
|
22
23
|
from code_loader.contract.enums import DataStateEnum, TestingSectionEnum, DataStateType, DatasetMetadataType, \
|
|
23
24
|
CustomLatentSpaceComputedAt
|
|
24
25
|
from code_loader.contract.mapping import NodeMappingType
|
|
@@ -26,10 +27,11 @@ from code_loader.contract.exceptions import DatasetScriptException
|
|
|
26
27
|
from code_loader.contract.responsedataclasses import DatasetIntegParseResult, DatasetTestResultPayload, \
|
|
27
28
|
DatasetPreprocess, DatasetSetup, DatasetInputInstance, DatasetOutputInstance, DatasetMetadataInstance, \
|
|
28
29
|
VisualizerInstance, PredictionTypeInstance, ModelSetup, CustomLayerInstance, MetricInstance, CustomLossInstance, \
|
|
29
|
-
EngineFileContract, SimulationInstance
|
|
30
|
+
EngineFileContract, SimulationInstance, FalsePositiveConfidenceConfig
|
|
30
31
|
from code_loader.contract.sim_config import FloatBounds, IntBounds, CategoricalBounds, sample_sim_params
|
|
31
32
|
from code_loader.inner_leap_binder import global_leap_binder
|
|
32
33
|
from code_loader.inner_leap_binder.leapbinder import mapping_runtime_mode_env_var_mame
|
|
34
|
+
from code_loader.inner_leap_binder.fp_confidence_contract import validate_confidence_contract
|
|
33
35
|
from code_loader.leaploaderbase import LeapLoaderBase
|
|
34
36
|
from code_loader.utils import get_root_exception_file_and_line_number, get_metadata_type_from_variable, \
|
|
35
37
|
validate_autoregressive_state_types, autoregressive_nests_equal, is_absent_metadata_value, \
|
|
@@ -101,7 +103,7 @@ class LeapLoader(LeapLoaderBase):
|
|
|
101
103
|
try:
|
|
102
104
|
from code_loader.mixpanel_tracker import track_code_loader_loaded
|
|
103
105
|
track_code_loader_loaded({
|
|
104
|
-
'
|
|
106
|
+
'load_trigger': 'leap_loader_instantiated',
|
|
105
107
|
'code_path': code_path,
|
|
106
108
|
'code_entry_name': code_entry_name
|
|
107
109
|
})
|
|
@@ -467,7 +469,16 @@ class LeapLoader(LeapLoaderBase):
|
|
|
467
469
|
print_log=print_log,
|
|
468
470
|
engine_file_contract=EngineFileContract(
|
|
469
471
|
global_leap_binder.mapping_connections,
|
|
470
|
-
global_leap_binder.leap_analysis_configuration
|
|
472
|
+
global_leap_binder.leap_analysis_configuration,
|
|
473
|
+
self._false_positive_confidence_config()))
|
|
474
|
+
|
|
475
|
+
@staticmethod
|
|
476
|
+
def _false_positive_confidence_config() -> Optional[FalsePositiveConfidenceConfig]:
|
|
477
|
+
handler = global_leap_binder.setup_container.false_positive_instances
|
|
478
|
+
if handler is None or handler.operating_threshold is None or handler.candidate_floor is None:
|
|
479
|
+
return None
|
|
480
|
+
return FalsePositiveConfidenceConfig(handler.operating_threshold, handler.candidate_floor,
|
|
481
|
+
handler.max_candidates_per_image)
|
|
471
482
|
|
|
472
483
|
def _check_integration_test_exists(self) -> DatasetTestResultPayload:
|
|
473
484
|
test_result = DatasetTestResultPayload('integration_test')
|
|
@@ -1802,7 +1813,8 @@ class LeapLoader(LeapLoaderBase):
|
|
|
1802
1813
|
return self.get_sample_id_type()(sample_id)
|
|
1803
1814
|
|
|
1804
1815
|
def get_false_positive_instances(self, state: DataStateEnum, sample_ids: List[Union[str, int]],
|
|
1805
|
-
predictions: Dict[str, npt.NDArray[np.float32]]
|
|
1816
|
+
predictions: Dict[str, npt.NDArray[np.float32]],
|
|
1817
|
+
raise_errors: bool = False
|
|
1806
1818
|
) -> List[Optional[List[ElementInstance]]]:
|
|
1807
1819
|
"""Run the false-positive encoder once per sample. `predictions` arrays carry a leading
|
|
1808
1820
|
batch axis of len(sample_ids); row i is handed to the user function for sample_ids[i].
|
|
@@ -1812,6 +1824,7 @@ class LeapLoader(LeapLoaderBase):
|
|
|
1812
1824
|
returned something that is not a list of ElementInstance. A failed sample does not fail
|
|
1813
1825
|
the others; its error is printed with the sample id. A batch-size mismatch between
|
|
1814
1826
|
`predictions` and `sample_ids`, or a missing encoder, still raises: those are caller errors.
|
|
1827
|
+
With `raise_errors`, the first failing sample re-raises instead.
|
|
1815
1828
|
"""
|
|
1816
1829
|
self.exec_script()
|
|
1817
1830
|
handler = global_leap_binder.setup_container.false_positive_instances
|
|
@@ -1828,8 +1841,11 @@ class LeapLoader(LeapLoaderBase):
|
|
|
1828
1841
|
row = {name: array[i] for name, array in predictions.items()}
|
|
1829
1842
|
try:
|
|
1830
1843
|
instances = handler.function(self._native_sample_id(sample_id), preprocess_response, row)
|
|
1831
|
-
self._validate_false_positive_instances(instances, set(self._instance_metric_handler_by_name())
|
|
1844
|
+
self._validate_false_positive_instances(instances, set(self._instance_metric_handler_by_name()),
|
|
1845
|
+
preprocess_response.state, handler)
|
|
1832
1846
|
except Exception as e:
|
|
1847
|
+
if raise_errors:
|
|
1848
|
+
raise
|
|
1833
1849
|
print(f"tensorleap_false_positive_instances_encoder failed for sample {sample_id!r} "
|
|
1834
1850
|
f"(state {state.name}): {e!r}")
|
|
1835
1851
|
results.append(None)
|
|
@@ -1838,7 +1854,9 @@ class LeapLoader(LeapLoaderBase):
|
|
|
1838
1854
|
return results
|
|
1839
1855
|
|
|
1840
1856
|
@staticmethod
|
|
1841
|
-
def _validate_false_positive_instances(instances: Any, registered_instance_metrics: Set[str]
|
|
1857
|
+
def _validate_false_positive_instances(instances: Any, registered_instance_metrics: Set[str],
|
|
1858
|
+
state: Optional[DataStateType],
|
|
1859
|
+
handler: FalsePositiveInstancesHandler) -> None:
|
|
1842
1860
|
prefix = "tensorleap_false_positive_instances_encoder validation failed: "
|
|
1843
1861
|
if not isinstance(instances, list):
|
|
1844
1862
|
raise Exception(f"{prefix}The return type should be a list of ElementInstance. "
|
|
@@ -1862,6 +1880,7 @@ class LeapLoader(LeapLoaderBase):
|
|
|
1862
1880
|
except (TypeError, ValueError):
|
|
1863
1881
|
raise Exception(f"{prefix}instance_metrics[{key!r}] of element {j} should be castable to "
|
|
1864
1882
|
f"float. Got {type(value)}.")
|
|
1883
|
+
validate_confidence_contract(instances, state, handler)
|
|
1865
1884
|
|
|
1866
1885
|
def get_false_positive_empty_gt(self, state: DataStateEnum,
|
|
1867
1886
|
sample_id: Union[str, int]) -> Dict[str, npt.NDArray[np.float32]]:
|
code_loader/mixpanel_tracker.py
CHANGED
|
@@ -12,12 +12,14 @@ import mixpanel # type: ignore[import]
|
|
|
12
12
|
|
|
13
13
|
logger = logging.getLogger(__name__)
|
|
14
14
|
|
|
15
|
-
TRACKING_VERSION = '
|
|
15
|
+
TRACKING_VERSION = '2'
|
|
16
16
|
TL_DISABLE_ANALYTICS_ENV_VAR = 'TL_DISABLE_ANALYTICS'
|
|
17
|
+
# Every code-loader event is sent under this one name; `event_type` says which one it is.
|
|
18
|
+
CODE_LOADER_EVENT_NAME = 'code_loader_event'
|
|
17
19
|
|
|
18
20
|
|
|
19
21
|
class AnalyticsEvent(str, Enum):
|
|
20
|
-
"""Enumeration of all tracked analytics events."""
|
|
22
|
+
"""Enumeration of all tracked analytics events, sent as the `event_type` of a code_loader_event."""
|
|
21
23
|
CODE_LOADER_LOADED = "code_loader_loaded"
|
|
22
24
|
LOAD_MODEL_INTEGRATION_TEST = "load_model_integration_test"
|
|
23
25
|
PREPROCESS_INTEGRATION_TEST = "preprocess_integration_test"
|
|
@@ -28,7 +30,7 @@ class AnalyticsEvent(str, Enum):
|
|
|
28
30
|
|
|
29
31
|
class CodeLoaderLoadedProps(TypedDict, total=False):
|
|
30
32
|
"""Properties for code_loader_loaded event."""
|
|
31
|
-
|
|
33
|
+
load_trigger: str
|
|
32
34
|
code_path: str
|
|
33
35
|
code_entry_name: str
|
|
34
36
|
|
|
@@ -171,8 +173,10 @@ class MixpanelTracker:
|
|
|
171
173
|
|
|
172
174
|
if event_properties:
|
|
173
175
|
properties.update(event_properties)
|
|
174
|
-
|
|
175
|
-
|
|
176
|
+
|
|
177
|
+
properties['event_type'] = _event_type(event_name)
|
|
178
|
+
|
|
179
|
+
self.mp.track(distinct_id, CODE_LOADER_EVENT_NAME, properties)
|
|
176
180
|
except Exception as e:
|
|
177
181
|
logger.debug(f"Failed to track event '{event_name}': {e}")
|
|
178
182
|
|
|
@@ -194,6 +198,13 @@ class MixpanelTracker:
|
|
|
194
198
|
self._track_event(event_name, event_properties)
|
|
195
199
|
|
|
196
200
|
|
|
201
|
+
def _event_type(event_name: Union[str, AnalyticsEvent]) -> str:
|
|
202
|
+
# str() of a (str, Enum) member is "AnalyticsEvent.X"; the event type is its value.
|
|
203
|
+
if isinstance(event_name, AnalyticsEvent):
|
|
204
|
+
return event_name.value
|
|
205
|
+
return str(event_name)
|
|
206
|
+
|
|
207
|
+
|
|
197
208
|
# Global tracker instance
|
|
198
209
|
_tracker = None
|
|
199
210
|
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
|
|
2
|
-
code_loader/__init__.py,sha256=
|
|
2
|
+
code_loader/__init__.py,sha256=v1cQGia6bCE7X-DbF3Hekr6P7d0hERAQtiBWzrXeM9g,408
|
|
3
3
|
code_loader/contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
-
code_loader/contract/datasetclasses.py,sha256=
|
|
4
|
+
code_loader/contract/datasetclasses.py,sha256=24KEuivii3DA41Mv1x3PF08NqOgXGXPPE2B0v7PFBao,20375
|
|
5
5
|
code_loader/contract/enums.py,sha256=wXxYS5aigaiPRgl8-MToX6MaHCbFge9gAUAwh2g6K8k,1916
|
|
6
6
|
code_loader/contract/exceptions.py,sha256=jWqu5i7t-0IG0jGRsKF4DjJdrsdpJjIYpUkN1F4RiyQ,51
|
|
7
7
|
code_loader/contract/mapping.py,sha256=i-yVyFuGUITL5lchPNfYlu7bhwk-yuoHPacAeFhcYr8,1490
|
|
8
|
-
code_loader/contract/responsedataclasses.py,sha256=
|
|
8
|
+
code_loader/contract/responsedataclasses.py,sha256=SRsg5B1sDYQDhtdlpbcpe8x9KJbIqbvkkGX-dYghWOU,6659
|
|
9
9
|
code_loader/contract/sim_config.py,sha256=le8KMALZiP0WU4UcuKnTOSWBW2rNjpnWYfII502NqDM,3493
|
|
10
10
|
code_loader/contract/visualizer_classes.py,sha256=4DWC3e4VI9vgMBwyWxX73YsRTZLjj_2hCDTo_AaQnF8,21608
|
|
11
11
|
code_loader/default_losses.py,sha256=NoOQym1106bDN5dcIk56Elr7ZG5quUHArqfP5-Nyxyo,1139
|
|
@@ -21,18 +21,19 @@ code_loader/experiment_api/types.py,sha256=MY8xFARHwdVA7p4dxyhD60ShmttgTvb4qdp1o
|
|
|
21
21
|
code_loader/experiment_api/utils.py,sha256=XZHtxge12TS4H4-8PjV3sKuhp8Ud6ojAiIzTZJEqBqc,3304
|
|
22
22
|
code_loader/experiment_api/workingspace_config_utils.py,sha256=DLzXQCg4dgTV_YgaSbeTVzq-2ja_SQw4zi7LXwKL9cY,990
|
|
23
23
|
code_loader/inner_leap_binder/__init__.py,sha256=koOlJyMNYzGbEsoIbXathSmQ-L38N_pEXH_HvL7beXU,99
|
|
24
|
-
code_loader/inner_leap_binder/
|
|
25
|
-
code_loader/inner_leap_binder/
|
|
26
|
-
code_loader/
|
|
24
|
+
code_loader/inner_leap_binder/fp_confidence_contract.py,sha256=JXuehIfli1lV_NkggMjJ_6uurBUIN9ctZNL8ZZIXbzU,4772
|
|
25
|
+
code_loader/inner_leap_binder/leapbinder.py,sha256=ccGfdLTLcGo7_J3FIPWzxD3ZaaiukVGCtyhdrjo_tkw,72281
|
|
26
|
+
code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=vvTLwMrwQyWypXs5rr9Hf2-EuiYjULlV8yhdzSq5i6M,222387
|
|
27
|
+
code_loader/leaploader.py,sha256=-yCnIGceXz0fdGmwqUo5fKNOM_Nb8MoXPxWMNItug2E,110590
|
|
27
28
|
code_loader/leaploaderbase.py,sha256=mymMOE9wo0qOUnQKQApEpvsZ5M_yhIeG62T5LKvt14A,13600
|
|
28
|
-
code_loader/mixpanel_tracker.py,sha256=
|
|
29
|
+
code_loader/mixpanel_tracker.py,sha256=XYBjF0U-WQdf77n0sQh-iDS7r4ovq9PSLbX34Bf_Ris,9636
|
|
29
30
|
code_loader/plot_functions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
30
31
|
code_loader/plot_functions/plot_functions.py,sha256=O4xFSxL8DoFVF02rj9ePN2BJrKCMElJVGPQOluYd3GE,17184
|
|
31
32
|
code_loader/plot_functions/visualize.py,sha256=gsBAYYkwMh7jIpJeDMPS8G4CW-pxwx6LznoQIvi4vpo,657
|
|
32
33
|
code_loader/utils.py,sha256=Jrmf9byeGwamj5XYxrLkVowb1IqsFKJ1FLy3slLApCw,13301
|
|
33
34
|
code_loader/visualizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
34
35
|
code_loader/visualizers/default_visualizers.py,sha256=grTPin_lCE9aci8i8CqA7DqQwAyXRB7_EamA3na_pls,5438
|
|
35
|
-
code_loader-1.0.
|
|
36
|
-
code_loader-1.0.
|
|
37
|
-
code_loader-1.0.
|
|
38
|
-
code_loader-1.0.
|
|
36
|
+
code_loader-1.0.218.dev0.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
|
|
37
|
+
code_loader-1.0.218.dev0.dist-info/METADATA,sha256=VeL3MZyxWJ1aZ8uwprunwg6KdgzUswsYzeu6KHGPcLs,1095
|
|
38
|
+
code_loader-1.0.218.dev0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
|
|
39
|
+
code_loader-1.0.218.dev0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|