code-loader 1.0.219rc1__tar.gz → 1.0.220__tar.gz

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.
Files changed (38) hide show
  1. {code_loader-1.0.219rc1 → code_loader-1.0.220}/PKG-INFO +3 -4
  2. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/datasetclasses.py +10 -80
  3. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/enums.py +0 -14
  4. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/responsedataclasses.py +7 -16
  5. code_loader-1.0.220/code_loader/inner_leap_binder/fp_confidence_contract.py +95 -0
  6. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/inner_leap_binder/leapbinder.py +18 -10
  7. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/inner_leap_binder/leapbinder_decorators.py +55 -55
  8. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/leaploader.py +27 -351
  9. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/utils.py +2 -1
  10. {code_loader-1.0.219rc1 → code_loader-1.0.220}/pyproject.toml +1 -1
  11. {code_loader-1.0.219rc1 → code_loader-1.0.220}/LICENSE +0 -0
  12. {code_loader-1.0.219rc1 → code_loader-1.0.220}/README.md +0 -0
  13. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/__init__.py +0 -0
  14. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/__init__.py +0 -0
  15. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/exceptions.py +0 -0
  16. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/mapping.py +0 -0
  17. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/sim_config.py +0 -0
  18. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/contract/visualizer_classes.py +0 -0
  19. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/default_losses.py +0 -0
  20. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/default_metrics.py +0 -0
  21. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/__init__.py +0 -0
  22. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/api.py +0 -0
  23. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/cli_config_utils.py +0 -0
  24. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/client.py +0 -0
  25. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/epoch.py +0 -0
  26. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/experiment.py +0 -0
  27. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/experiment_context.py +0 -0
  28. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/types.py +0 -0
  29. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/utils.py +0 -0
  30. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/experiment_api/workingspace_config_utils.py +0 -0
  31. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/inner_leap_binder/__init__.py +0 -0
  32. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/leaploaderbase.py +0 -0
  33. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/mixpanel_tracker.py +0 -0
  34. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/plot_functions/__init__.py +0 -0
  35. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/plot_functions/plot_functions.py +0 -0
  36. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/plot_functions/visualize.py +0 -0
  37. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/visualizers/__init__.py +0 -0
  38. {code_loader-1.0.219rc1 → code_loader-1.0.220}/code_loader/visualizers/default_visualizers.py +0 -0
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.219rc1
3
+ Version: 1.0.220
4
4
  Summary:
5
+ Home-page: https://github.com/tensorleap/code-loader
5
6
  License: MIT
6
- License-File: LICENSE
7
7
  Author: dorhar
8
8
  Author-email: doron.harnoy@tensorleap.ai
9
9
  Requires-Python: >=3.8,<3.13
@@ -20,7 +20,6 @@ Requires-Dist: numpy (>=2.3.2,<3.0.0) ; python_version >= "3.11" and python_vers
20
20
  Requires-Dist: psutil (>=5.9.5,<6.0.0)
21
21
  Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
22
22
  Requires-Dist: requests (>=2.32.3,<3.0.0)
23
- Project-URL: Homepage, https://github.com/tensorleap/code-loader
24
23
  Project-URL: Repository, https://github.com/tensorleap/code-loader
25
24
  Description-Content-Type: text/markdown
26
25
 
@@ -6,15 +6,12 @@ import numpy as np
6
6
  import numpy.typing as npt
7
7
 
8
8
  from code_loader.contract.enums import DataStateType, DataStateEnum, LeapDataType, ConfusionMatrixValue, \
9
- MetricDirection, DatasetMetadataType, LatentSpaceReduction, CustomLatentSpaceComputedAt, ImageRange
9
+ MetricDirection, DatasetMetadataType, LatentSpaceReduction, CustomLatentSpaceComputedAt
10
10
  from code_loader.contract.visualizer_classes import LeapImage, LeapText, LeapGraph, LeapHorizontalBar, \
11
11
  LeapTextMask, LeapImageMask, LeapImageWithBBox, LeapImageWithHeatmap, LeapVideo, LeapAudio, LeapPointCloud
12
12
  from code_loader.contract.sim_config import SimConfig
13
13
 
14
14
  custom_latent_space_attribute = "custom_latent_space"
15
- # Stamped by @tensorleap_instances_masks_encoder on the function it returns, so FoundationInput(masks=fn)
16
- # can verify it was handed a registered masks encoder and resolve it to the registered name.
17
- masks_encoder_name_attribute = "tensorleap_masks_encoder_name"
18
15
 
19
16
  # Hard cap on a custom latent space's per-sample width, applied AFTER any reduction. The
20
17
  # soft threshold only warns. MAX_CUSTOM_LATENT_SPACES mirrors the engine's
@@ -173,7 +170,7 @@ class PreprocessResponse:
173
170
  @dataclass
174
171
  class ElementInstance:
175
172
  name: str
176
- mask: npt.NDArray[np.float32]
173
+ mask: Optional[npt.NDArray[np.float32]]
177
174
  instance_metadata: Optional[Dict[str, Union[Optional[str], int, bool, Optional[float]]]] = None
178
175
  # Per-key "this value is absent", the same pair shape DatasetSample carries. Populated at the
179
176
  # masks funnel (utils.to_numpy_return_masks_wrapper) so the engine copies flags rather than
@@ -182,6 +179,12 @@ class ElementInstance:
182
179
  # Per-instance metric values keyed by the registered name of a tensorleap_custom_instances_metric.
183
180
  # Only meaningful on false-positive instances (they have no ground-truth row for the metric to run on).
184
181
  instance_metrics: Optional[Dict[str, float]] = None
182
+ # Confidence mode (the FP encoder declares operating_threshold): the candidate's score, required on every
183
+ # candidate. Ignored (may stay None) when no threshold is declared.
184
+ score: Optional[float] = None
185
+ # Confidence mode, training / validation / test only: whether this candidate matches a ground-truth instance,
186
+ # by the integration's own rule (IoU threshold, class). Ignored on unlabeled / additional.
187
+ matched_gt: Optional[bool] = None
185
188
 
186
189
  SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
187
190
  InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse, int], Optional[ElementInstance]]
@@ -324,85 +327,10 @@ class DatasetBaseHandler:
324
327
  function: SectionCallableInterface
325
328
 
326
329
 
327
- @dataclass
328
- class FoundationInput:
329
- """Marks an input encoder as the image a foundation encoder (SigLIP 2, OWLv2) reads.
330
-
331
- Exactly one input encoder per project carries it. The platform inverts the tensor to uint8 pixels
332
- with one global affine map resolved from `range` -- never from per-image statistics -- and feeds
333
- the result to the encoder's own preprocessing.
334
-
335
- `range`: the convention's theoretical [min, max] of the tensor, not the observed min/max of the
336
- samples. An `ImageRange` preset or a `(min, max)` tuple (e.g. caffe: `(-123.68, 151.06)`).
337
- `rgb_channels`: the three indices along the channel axis (`channel_dim`) that are R, G and B --
338
- `(2, 1, 0)` for BGR, `(3, 2, 1)` for a multispectral true colour, `(0, 0, 0)` for grayscale.
339
- `masks`: for a dedicated foundation input (an encoder not passed to the model) in an
340
- element-instance project, the function returned by a second `@tensorleap_instances_masks_encoder`
341
- that draws each instance in this image's coordinates. Pass the decorated function, not its name.
342
- """
343
- range: Union[ImageRange, Tuple[float, float]]
344
- rgb_channels: Tuple[int, int, int] = (0, 1, 2)
345
- masks: Optional[Callable[..., Any]] = None
346
-
347
- def __post_init__(self) -> None:
348
- if not isinstance(self.range, ImageRange):
349
- self.range = self._validated_range(self.range)
350
- self.rgb_channels = self._validated_rgb_channels(self.rgb_channels)
351
- if self.masks is not None and not isinstance(self.masks_encoder_name, str):
352
- raise TypeError(
353
- f'FoundationInput() validation failed: masks should be the function returned by a '
354
- f'@tensorleap_instances_masks_encoder decorator -- pass the decorated function object, '
355
- f'not the encoder name. Got {self.masks!r}.')
356
-
357
- @staticmethod
358
- def _validated_range(value: Any) -> Tuple[float, float]:
359
- message = (f'FoundationInput() validation failed: range should be an ImageRange preset or a '
360
- f'(min, max) tuple of two numbers with min < max. Got {value!r}.')
361
- if isinstance(value, (str, bytes)) or not isinstance(value, (tuple, list)) or len(value) != 2:
362
- raise TypeError(message)
363
- if not all(isinstance(v, (int, float, np.integer, np.floating)) and not isinstance(v, bool) for v in value):
364
- raise TypeError(message)
365
- low, high = float(value[0]), float(value[1])
366
- if not (np.isfinite(low) and np.isfinite(high)) or not low < high:
367
- raise ValueError(message)
368
- return low, high
369
-
370
- @staticmethod
371
- def _validated_rgb_channels(value: Any) -> Tuple[int, int, int]:
372
- message = (f'FoundationInput() validation failed: rgb_channels should be three non-negative channel '
373
- f'indices (R, G, B) along the channel axis. Got {value!r}.')
374
- if isinstance(value, (str, bytes)) or not isinstance(value, (tuple, list)) or len(value) != 3:
375
- raise TypeError(message)
376
- if not all(isinstance(v, (int, np.integer)) and not isinstance(v, bool) for v in value):
377
- raise TypeError(message)
378
- if any(int(v) < 0 for v in value):
379
- raise ValueError(message)
380
- return int(value[0]), int(value[1]), int(value[2])
381
-
382
- def bounds(self) -> Tuple[float, float]:
383
- """The declared (min, max) as floats, preset or tuple alike."""
384
- if isinstance(self.range, ImageRange):
385
- low, high = self.range.value
386
- return float(low), float(high)
387
- return self.range
388
-
389
- @property
390
- def masks_encoder_name(self) -> Optional[str]:
391
- """The registered name of the masks encoder behind `masks`, None when no `masks=` was given."""
392
- if self.masks is None:
393
- return None
394
- name = getattr(self.masks, masks_encoder_name_attribute, None)
395
- return name if isinstance(name, str) else None
396
-
397
-
398
330
  @dataclass
399
331
  class InputHandler(DatasetBaseHandler):
400
332
  shape: Optional[List[int]] = None
401
333
  channel_dim: Optional[int] = -1
402
- # The probe result's dtype name ('float32', 'uint8'), recorded by check_handler next to shape.
403
- dtype: Optional[str] = None
404
- # Set when the encoder carries foundation=FoundationInput(...): the image a foundation encoder reads.
405
- foundation: Optional[FoundationInput] = None
406
334
 
407
335
  @dataclass
408
336
  class ElementInstanceMasksHandler:
@@ -413,6 +341,8 @@ class ElementInstanceMasksHandler:
413
341
  class FalsePositiveInstancesHandler:
414
342
  name: str
415
343
  function: Callable[..., Any]
344
+ operating_threshold: Optional[float] = None
345
+ candidate_floor: Optional[float] = None
416
346
 
417
347
  @dataclass
418
348
  class GroundTruthHandler(DatasetBaseHandler):
@@ -79,17 +79,3 @@ class LatentSpaceReduction(Enum):
79
79
  class CustomLatentSpaceComputedAt(Enum):
80
80
  DATASET = 'dataset'
81
81
  MODEL = 'model'
82
-
83
-
84
- class ImageRange(Enum):
85
- """Theoretical (min, max) of an image tensor under a photometric convention.
86
-
87
- Used by `FoundationInput.range` to describe a model's input encoder so the platform can invert
88
- it back to uint8 pixels for a foundation encoder. These are the conventions' bounds, not the
89
- observed min/max of any sample.
90
- """
91
- BYTE = (0.0, 255.0) # raw 8-bit pixels
92
- UNIT = (0.0, 1.0) # x / 255
93
- SIGNED = (-1.0, 1.0) # x / 127.5 - 1
94
- IMAGENET = (-2.118, 2.640) # (x / 255 - mean) / std with the ImageNet mean/std
95
- CLIP = (-1.792, 2.146) # (x / 255 - mean) / std with the CLIP mean/std
@@ -19,26 +19,10 @@ class DatasetBaseSectionInstance:
19
19
  name: str
20
20
 
21
21
 
22
- @dataclass
23
- class FoundationInputInstance:
24
- """What the engine needs to run a foundation image encoder on this input: the declared
25
- convention (`range`, `rgb_channels`), the probe's dtype, whether the integration test wires the
26
- input to the model (native: invert the tensor; not wired: a dedicated image, resize to the
27
- encoder frame) and, for a dedicated input in an instance project, its own masks encoder."""
28
- range: List[float]
29
- rgb_channels: List[int]
30
- dtype: str
31
- wired_to_model: bool
32
- masks_encoder: Optional[str] = None
33
-
34
-
35
22
  @dataclass
36
23
  class DatasetInputInstance(DatasetBaseSectionInstance):
37
24
  shape: List[int]
38
25
  channel_dim: Optional[int] = -1
39
- # Set for the one input that carries foundation=FoundationInput(...). Default None so an old
40
- # engine payload deserialises unchanged (same pattern as DatasetSetup.has_element_instances).
41
- foundation: Optional[FoundationInputInstance] = None
42
26
 
43
27
 
44
28
  @dataclass
@@ -187,10 +171,17 @@ class LeapAnalysisConfiguration:
187
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
188
172
 
189
173
 
174
+ @dataclass
175
+ class FalsePositiveConfidenceConfig:
176
+ operating_threshold: float
177
+ candidate_floor: float
178
+
179
+
190
180
  @dataclass
191
181
  class EngineFileContract:
192
182
  node_connections: Optional[List[NodeConnection]] = None
193
183
  leap_analysis_configuration: Optional[LeapAnalysisConfiguration] = None
184
+ false_positive_confidence: Optional[FalsePositiveConfidenceConfig] = None
194
185
 
195
186
 
196
187
  @dataclass
@@ -0,0 +1,95 @@
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]) -> None:
22
+ if operating_threshold is None:
23
+ if candidate_floor is not None:
24
+ raise ValueError(_PREFIX + "candidate_floor requires operating_threshold.")
25
+ return
26
+ if not _is_finite_number(operating_threshold):
27
+ raise ValueError(_PREFIX + f"operating_threshold should be a finite float. Got {operating_threshold!r}.")
28
+ if candidate_floor is None:
29
+ raise ValueError(_PREFIX + "candidate_floor is required when operating_threshold is declared.")
30
+ if not _is_finite_number(candidate_floor) or candidate_floor >= operating_threshold:
31
+ raise ValueError(_PREFIX + f"candidate_floor should be a finite float below operating_threshold "
32
+ f"({operating_threshold}). Got {candidate_floor!r}.")
33
+
34
+
35
+ def declare_confidence_metadata_types(setup_container: DatasetIntegrationSetup) -> None:
36
+ false_positive_instances = setup_container.false_positive_instances
37
+ if false_positive_instances is None or false_positive_instances.operating_threshold is None:
38
+ return
39
+ handler = next((handler for handler in setup_container.metadata
40
+ if handler.name == "builtin_instance_metadata"), None)
41
+ if handler is None:
42
+ return
43
+ declared: Dict[str, DatasetMetadataType] = {
44
+ 'is_instance': DatasetMetadataType.string,
45
+ 'original_sample_id': DatasetMetadataType.string,
46
+ 'instance_name': DatasetMetadataType.string,
47
+ 'is_false_positive': DatasetMetadataType.string,
48
+ 'confidence': DatasetMetadataType.float,
49
+ 'above_operating_threshold': DatasetMetadataType.string,
50
+ }
51
+ if isinstance(handler.metadata_type, dict):
52
+ for name, metadata_type in declared.items():
53
+ handler.metadata_type.setdefault(name, metadata_type)
54
+ else:
55
+ handler.metadata_type = declared
56
+
57
+
58
+ def validate_confidence_contract(instances: List[ElementInstance], state: Optional[DataStateType],
59
+ handler: Optional[FalsePositiveInstancesHandler]) -> None:
60
+ if handler is None or handler.operating_threshold is None:
61
+ return
62
+
63
+ scores: List[float] = []
64
+ for j, instance in enumerate(instances):
65
+ if instance.score is None or not _is_finite_number(instance.score):
66
+ raise Exception(f"{_PREFIX}operating_threshold is declared, so element {j} of the returned list "
67
+ f"should have a finite float score (call .item() on a tensor). Got {instance.score!r}.")
68
+ scores.append(float(instance.score))
69
+ if handler.candidate_floor is not None and \
70
+ not np.float32(instance.score) >= np.float32(handler.candidate_floor):
71
+ raise Exception(f"{_PREFIX}score {instance.score!r} of element {j} is below candidate_floor "
72
+ f"{handler.candidate_floor}. Return only candidates with score >= candidate_floor.")
73
+
74
+ if state in _LABELED_STATES:
75
+ for j, instance in enumerate(instances):
76
+ if not isinstance(instance.matched_gt, (bool, np.bool_)):
77
+ raise Exception(f"{_PREFIX}matched_gt of element {j} should be a bool on the {state.value} state "
78
+ f"(True when the candidate matches a ground-truth instance by the integration's "
79
+ f"own IoU / class rule). Got {instance.matched_gt!r}.")
80
+ is_row = not instance.matched_gt and \
81
+ np.float32(scores[j]) >= np.float32(handler.operating_threshold)
82
+ if instance.mask is None and is_row:
83
+ raise Exception(f"{_PREFIX}mask of element {j} is None. mask may be None only for calibration-only "
84
+ f"candidates (matched, or below operating_threshold) on labeled states; an unmatched "
85
+ f"candidate with score >= operating_threshold needs a mask.")
86
+ else:
87
+ for j, instance in enumerate(instances):
88
+ if instance.mask is None:
89
+ raise Exception(f"{_PREFIX}mask of element {j} is None. mask may be None only for calibration-only "
90
+ f"candidates (matched, or below operating_threshold) on labeled states; every "
91
+ f"candidate on the {state.value if state is not None else 'given'} state needs a mask.")
92
+
93
+ if any(scores[i] < scores[i + 1] for i in range(len(scores) - 1)):
94
+ warnings.warn("tensorleap_false_positive_instances_encoder warning: the returned instances are not "
95
+ "sorted by score in descending order. Tensorleap sorts them.")
@@ -17,7 +17,7 @@ from code_loader.contract.datasetclasses import SectionCallableInterface, InputH
17
17
  CustomMultipleReturnCallableInterfaceMultiArgs, DatasetBaseHandler, custom_latent_space_attribute, \
18
18
  RawInputsForHeatmap, VisualizerHandlerData, MetricHandlerData, CustomLossHandlerData, SamplePreprocessResponse, \
19
19
  ElementInstanceMasksHandler, FalsePositiveInstancesHandler, InstanceCallableInterface, InstanceSectionCallableInterface, \
20
- CustomLatentSpaceHandler, InstanceMetricHandler, MAX_CUSTOM_LATENT_SPACES, FoundationInput, \
20
+ CustomLatentSpaceHandler, InstanceMetricHandler, MAX_CUSTOM_LATENT_SPACES, \
21
21
  SimulationHandler, _simulation_context, AutoregressiveStepHandler, AutoregressiveStepCallableInterface, \
22
22
  AUTOREGRESSIVE_LATENT_SPACE_AGGREGATIONS, AUTOREGRESSIVE_IMPLICIT_ARG_NAMES, \
23
23
  AutoregressiveMetricHandler, AutoregressiveLossHandler, AutoregressiveVisualizerHandler
@@ -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, \
@@ -301,8 +303,7 @@ class LeapBinder:
301
303
  SimulationHandler(name=name, function=function, sim_config=sim_config)
302
304
  )
303
305
 
304
- def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1,
305
- foundation: Optional[FoundationInput] = None) -> None:
306
+ def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1) -> None:
306
307
  """
307
308
  Set the input handler function.
308
309
 
@@ -310,7 +311,6 @@ class LeapBinder:
310
311
  function (SectionCallableInterface): The input handler function.
311
312
  name (str): The name of the input section.
312
313
  channel_dim (int): The dimension of the channels axis
313
- foundation (Optional[FoundationInput]): marks this input as the image a foundation encoder reads
314
314
 
315
315
  Example:
316
316
  def input_encoder(subset: PreprocessResponse, index: int) -> np.ndarray:
@@ -323,7 +323,7 @@ class LeapBinder:
323
323
  leap_binder.set_input(input_encoder, name='input_encoder', channel_dim=-1)
324
324
  """
325
325
  function = to_numpy_return_wrapper(function)
326
- self.setup_container.inputs.append(InputHandler(name, function, channel_dim=channel_dim, foundation=foundation))
326
+ self.setup_container.inputs.append(InputHandler(name, function, channel_dim=channel_dim))
327
327
 
328
328
  self._encoder_names.append(name)
329
329
 
@@ -343,15 +343,25 @@ class LeapBinder:
343
343
  self.setup_container.instance_masks.append(ElementInstanceMasksHandler(name, function))
344
344
 
345
345
 
346
- def set_false_positive_instances(self, function: Callable[..., Any], name: str) -> None:
346
+ def set_false_positive_instances(self, function: Callable[..., Any], name: str,
347
+ operating_threshold: Optional[float] = None,
348
+ candidate_floor: Optional[float] = None) -> None:
347
349
  """
348
350
  Set the false-positive instances handler. It receives (sample_id, preprocess, predictions)
349
- and returns a list of ElementInstance, one per false-positive prediction.
351
+ and returns a list of ElementInstance: one per false-positive prediction, or, when
352
+ `operating_threshold` is declared, one per candidate down to `candidate_floor` (matched ones
353
+ included), each with a score. The full contract is in the docstring of
354
+ `tensorleap_false_positive_instances_encoder`.
350
355
  """
351
356
  if self.setup_container.false_positive_instances is not None:
352
357
  raise Exception("only one tensorleap_false_positive_instances_encoder can be defined")
358
+ validate_confidence_args(operating_threshold, candidate_floor)
353
359
  function = to_numpy_return_fp_masks_wrapper(function)
354
- self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(name, function)
360
+ self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(
361
+ name, function,
362
+ float(operating_threshold) if operating_threshold is not None else None,
363
+ float(candidate_floor) if candidate_floor is not None else None)
364
+ declare_confidence_metadata_types(self.setup_container)
355
365
 
356
366
  def set_false_positive_empty_gt(self, function: Callable[..., Any], gt_name: str) -> None:
357
367
  """
@@ -1074,8 +1084,6 @@ class LeapBinder:
1074
1084
  # setting shape in setup for all encoders
1075
1085
  if isinstance(dataset_base_handler, (InputHandler, GroundTruthHandler)):
1076
1086
  dataset_base_handler.shape = result_shape
1077
- if isinstance(dataset_base_handler, InputHandler) and isinstance(raw_result, np.ndarray):
1078
- dataset_base_handler.dtype = str(raw_result.dtype)
1079
1087
  _warn_if_group_spans_multiple_files(test_result)
1080
1088
  return test_result
1081
1089
 
@@ -29,7 +29,7 @@ from code_loader.contract.datasetclasses import CustomCallableInterfaceMultiArgs
29
29
  ConfusionMatrixElement, SamplePreprocessResponse, PredictionTypeHandler, InstanceCallableInterface, ElementInstance, \
30
30
  is_sample_id_of_type, \
31
31
  InstanceLengthCallableInterface, InstanceSectionCallableInterface, AutoregressiveStepCallableInterface, \
32
- MAX_CUSTOM_LATENT_SPACE_DIM, CUSTOM_LATENT_SPACE_WARN_DIM, FoundationInput, masks_encoder_name_attribute
32
+ MAX_CUSTOM_LATENT_SPACE_DIM, CUSTOM_LATENT_SPACE_WARN_DIM
33
33
  from code_loader.contract.enums import MetricDirection, LeapDataType, DatasetMetadataType, DataStateType, \
34
34
  DataStateEnum, LatentSpaceReduction, CustomLatentSpaceComputedAt
35
35
  from code_loader import leap_binder, LeapLoader
@@ -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
@@ -3268,15 +3270,21 @@ def _register_builtin_instance_metadata() -> None:
3268
3270
  makes the engine produce instance samples.
3269
3271
  """
3270
3272
  if any(h.name == "builtin_instance_metadata" for h in leap_binder.setup_container.metadata):
3273
+ declare_confidence_metadata_types(leap_binder.setup_container)
3271
3274
  return
3272
3275
 
3273
- def builtin_instance_metadata(idx: str, preprocess: PreprocessResponse) -> Dict[str, str]:
3274
- result = {'is_instance': '0', 'original_sample_id': idx, 'instance_name': 'none'}
3275
- if leap_binder.setup_container.false_positive_instances is not None:
3276
+ def builtin_instance_metadata(idx: str, preprocess: PreprocessResponse) -> Dict[str, Optional[str]]:
3277
+ result: Dict[str, Optional[str]] = {'is_instance': '0', 'original_sample_id': idx, 'instance_name': 'none'}
3278
+ false_positive_instances = leap_binder.setup_container.false_positive_instances
3279
+ if false_positive_instances is not None:
3276
3280
  result['is_false_positive'] = '0'
3281
+ if false_positive_instances.operating_threshold is not None:
3282
+ result['confidence'] = None
3283
+ result['above_operating_threshold'] = None
3277
3284
  return result
3278
3285
 
3279
3286
  leap_binder.set_metadata(builtin_instance_metadata, "builtin_instance_metadata")
3287
+ declare_confidence_metadata_types(leap_binder.setup_container)
3280
3288
 
3281
3289
 
3282
3290
  def _register_builtin_instance_extra_metadata(metadata_types: Dict[str, DatasetMetadataType]) -> None:
@@ -3478,12 +3486,6 @@ def tensorleap_instances_masks_encoder(name: str):
3478
3486
  (f'tensorleap_instances_masks_encoder validation failed: '
3479
3487
  f'Unsupported return type. Should be a ElementInstance or None. Got {type(result)}.')
3480
3488
 
3481
- def _is_foundation_masks_encoder():
3482
- # Decided at call time: the FoundationInput naming this encoder is created after it.
3483
- return any(input_handler.foundation is not None
3484
- and input_handler.foundation.masks_encoder_name == name
3485
- for input_handler in leap_binder.setup_container.inputs)
3486
-
3487
3489
  def inner_without_validate(sample_id, preprocess_response, instance_id):
3488
3490
  global _called_from_inside_tl_decorator
3489
3491
  _called_from_inside_tl_decorator += 1
@@ -3493,11 +3495,6 @@ def tensorleap_instances_masks_encoder(name: str):
3493
3495
  finally:
3494
3496
  _called_from_inside_tl_decorator -= 1
3495
3497
 
3496
- if isinstance(result, np.ndarray) and _is_foundation_masks_encoder():
3497
- # Only the geometry is taken from a foundation masks encoder (instance identity and
3498
- # metadata come from the native one), so a bare H x W mask is the explicit form of
3499
- # that contract; wrap it, named after the encoder, with no metadata.
3500
- result = ElementInstance(name=name, mask=result)
3501
3498
  return result
3502
3499
 
3503
3500
  leap_binder.set_instance_masks(inner_without_validate, name)
@@ -3513,23 +3510,55 @@ def tensorleap_instances_masks_encoder(name: str):
3513
3510
  _validate_result(result)
3514
3511
  return result
3515
3512
 
3516
- # FoundationInput(masks=inner) verifies it was handed a registered masks encoder through this
3517
- # attribute and resolves it to the registered name (function object, not name: a typo fails at import).
3518
- setattr(inner, masks_encoder_name_attribute, name)
3519
3513
  return inner
3520
3514
 
3521
3515
  return decorating_function
3522
3516
 
3523
3517
 
3524
3518
  def tensorleap_false_positive_instances_encoder(
3525
- name: str, instance_metadata_types: Optional[Dict[str, DatasetMetadataType]] = None):
3519
+ name: str, instance_metadata_types: Optional[Dict[str, DatasetMetadataType]] = None,
3520
+ operating_threshold: Optional[float] = None, candidate_floor: Optional[float] = None):
3526
3521
  """Register the false-positive instances encoder.
3527
3522
 
3523
+ The decorated function receives (sample_id, preprocess_response, predictions) and returns a list of
3524
+ ElementInstance.
3525
+
3528
3526
  `instance_metadata_types` declares the keys (and types) of the `instance_metadata` the returned
3529
3527
  ElementInstances may carry. They become `builtin_instance_extra_metadata_<key>` columns, merged
3530
3528
  with any keys the element-instance preprocess declares; a key not declared here (or by the
3531
3529
  GT instances) is dropped from false-positive rows by the engine.
3530
+
3531
+ Without `operating_threshold`, return one ElementInstance per false-positive prediction (a prediction
3532
+ that matches no ground-truth instance), as the model is used.
3533
+
3534
+ Confidence mode: declaring `operating_threshold` lets Tensorleap add likely missed objects (predictions
3535
+ just below the threshold) to the unlabeled pool as labeling candidates.
3536
+
3537
+ - `operating_threshold`: the score the model is used at.
3538
+ - `candidate_floor`: required with `operating_threshold`, and strictly below it: the lowest score worth
3539
+ considering.
3540
+ - Return every candidate with score >= `candidate_floor`, on every state (training, validation and test
3541
+ included), matched ones too: not only the false positives, and not only those above the threshold.
3542
+ - Apply the floor after the model's usual post-processing (NMS, top-k / max_det caps): the candidates at
3543
+ or above `operating_threshold` must be exactly what the model produces at `operating_threshold`, and
3544
+ the ones below it are added to them. Lowering the confidence filter in front of NMS changes the
3545
+ candidates above the threshold unless the post-processing is plain greedy NMS without caps.
3546
+ - Each ElementInstance needs a finite `score`. On training, validation and test it also needs a bool
3547
+ `matched_gt`: whether it matches a ground-truth instance, by the integration's own rule (IoU threshold,
3548
+ class).
3549
+ - `mask` may be None only for a calibration-only candidate on training, validation or test (matched, or
3550
+ below `operating_threshold`). Every other candidate, and every candidate on unlabeled and additional,
3551
+ needs a mask.
3552
+ - Any order: Tensorleap sorts by score.
3553
+
3554
+ What Tensorleap does with them: on training, validation and test the unmatched candidates at or above
3555
+ `operating_threshold` become false-positive rows (as without confidence mode), and every candidate's
3556
+ (score, matched_gt) calibrates how far below the threshold to look. On unlabeled and additional the
3557
+ candidates at or above the threshold become rows, and so do the ones below it down to a cut chosen from
3558
+ that calibration.
3532
3559
  """
3560
+ validate_confidence_args(operating_threshold, candidate_floor)
3561
+
3533
3562
  def decorating_function(user_function: Callable):
3534
3563
  def _validate_input_args(sample_id, preprocess_response, predictions):
3535
3564
  assert isinstance(sample_id, (str, int)), \
@@ -3562,7 +3591,7 @@ def tensorleap_false_positive_instances_encoder(
3562
3591
 
3563
3592
  return result
3564
3593
 
3565
- leap_binder.set_false_positive_instances(inner_without_validate, name)
3594
+ leap_binder.set_false_positive_instances(inner_without_validate, name, operating_threshold, candidate_floor)
3566
3595
  _register_builtin_instance_metadata()
3567
3596
  if instance_metadata_types:
3568
3597
  _register_builtin_instance_extra_metadata(instance_metadata_types)
@@ -3576,6 +3605,8 @@ def tensorleap_false_positive_instances_encoder(
3576
3605
  result = inner_without_validate(sample_id, preprocess_response, predictions)
3577
3606
 
3578
3607
  _validate_result(result)
3608
+ validate_confidence_contract(result, preprocess_response.state,
3609
+ leap_binder.setup_container.false_positive_instances)
3579
3610
  return result
3580
3611
 
3581
3612
  return inner
@@ -3718,24 +3749,7 @@ def tensorleap_instances_length_encoder(name: str):
3718
3749
  return decorating_function
3719
3750
 
3720
3751
 
3721
- def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=None,
3722
- foundation: Optional[FoundationInput] = None):
3723
- """Register an input encoder: ``(sample_id, preprocess) -> np.ndarray`` (float32).
3724
-
3725
- ``channel_dim`` is the channel axis in the batched tensor (1 for NCHW, -1 for NHWC).
3726
- ``foundation=FoundationInput(range=..., rgb_channels=..., masks=...)`` marks this input as the
3727
- image the platform's foundation encoders (SigLIP 2, OWLv2) read -- exactly one input per
3728
- project. ``range`` is the tensor's convention (an ``ImageRange`` preset or a ``(min, max)``
3729
- tuple, theoretical, not the samples' min/max) and ``rgb_channels`` the R, G, B indices on the
3730
- channel axis. Put it on the image the integration test passes to the model and the platform
3731
- inverts that tensor back to pixels; put it on a separate encoder that is never passed to the
3732
- model and it is a dedicated image for the encoders alone -- uint8 at any size, with ``masks=``
3733
- naming a second ``@tensorleap_instances_masks_encoder`` in its coordinates for instance projects.
3734
- ``check_dataset`` verifies the declaration (one flag, wired vs dedicated, the declared range on a
3735
- few samples, the masks). See
3736
- https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code/input-encoder
3737
- (section "Foundation input").
3738
- """
3752
+ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=None):
3739
3753
  def decorating_function(user_function: SectionCallableInterface):
3740
3754
  for input_handler in leap_binder.setup_container.inputs:
3741
3755
  if input_handler.name == name:
@@ -3764,20 +3778,6 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3764
3778
  f"channel axis in the batched tensor (batch = axis 0), so 0 is invalid. Use 1 "
3765
3779
  f"for channel-first (NCHW) and -1 for channel-last (NHWC).")
3766
3780
 
3767
- if foundation is not None and not isinstance(foundation, FoundationInput):
3768
- raise Exception(
3769
- f"Invalid foundation for input '{name}': expected FoundationInput(range=..., "
3770
- f"rgb_channels=..., masks=...) or None, got {type(foundation).__name__}.")
3771
-
3772
- # Inputs feed float32 graph placeholders, so float32 is the rule. An encoder that carries
3773
- # foundation= may instead return uint8 pixels: a dedicated foundation input never reaches
3774
- # the graph (only the platform's foundation encoder reads it), and uint8 is a quarter of the
3775
- # payload. Whether THIS flagged encoder is wired to the model (and so must still be float32)
3776
- # is only known after the integration test's mapping pass; check_dataset applies that rule,
3777
- # the decorator only admits the dtype.
3778
- allowed_dtypes = (np.float32, np.uint8) if foundation is not None else (np.float32,)
3779
- allowed_dtypes_text = ' or '.join(np.dtype(d).name for d in allowed_dtypes)
3780
-
3781
3781
  def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
3782
3782
  _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
3783
3783
 
@@ -3785,9 +3785,9 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3785
3785
  assert isinstance(result, np.ndarray), \
3786
3786
  (f'{user_function.__name__}() validation failed: '
3787
3787
  f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
3788
- assert result.dtype in allowed_dtypes, \
3788
+ assert result.dtype == np.float32, \
3789
3789
  (f'{user_function.__name__}() validation failed: '
3790
- f'The return type should be a numpy array of type {allowed_dtypes_text}. Got {result.dtype}.')
3790
+ f'The return type should be a numpy array of type float32. Got {result.dtype}.')
3791
3791
  assert channel_dim - 1 <= len(result.shape), (f'{user_function.__name__}() validation failed: '
3792
3792
  f'The channel_dim ({channel_dim}) should be <= to the rank of the resulting input rank ({len(result.shape)}).')
3793
3793
 
@@ -3809,7 +3809,7 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3809
3809
 
3810
3810
  return result
3811
3811
 
3812
- leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim, foundation=foundation)
3812
+ leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim)
3813
3813
 
3814
3814
  def inner(*args, **kwargs):
3815
3815
  if not _call_from_tl_platform:
@@ -14,22 +14,24 @@ from typing import Dict, List, Iterable, Set, FrozenSet, Union, Any, Type, Optio
14
14
  import numpy as np
15
15
  import numpy.typing as npt
16
16
 
17
- from code_loader.contract.datasetclasses import DatasetSample, DatasetBaseHandler, GroundTruthHandler, InputHandler, \
17
+ from code_loader.contract.datasetclasses import DatasetSample, DatasetBaseHandler, GroundTruthHandler, \
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
- CustomLatentSpaceComputedAt, ImageRange
24
+ CustomLatentSpaceComputedAt
24
25
  from code_loader.contract.mapping import NodeMappingType
25
26
  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, FoundationInputInstance
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, \
@@ -429,9 +431,6 @@ class LeapLoader(LeapLoaderBase):
429
431
  test_payloads.append(model_ls_test_payload)
430
432
  handlers_test_payloads = self._check_handlers()
431
433
  test_payloads.extend(handlers_test_payloads)
432
- foundation_test_payload = self._check_foundation_input()
433
- if foundation_test_payload is not None:
434
- test_payloads.append(foundation_test_payload)
435
434
  simulation_test_payloads = self._check_simulations()
436
435
  test_payloads.extend(simulation_test_payloads)
437
436
  autoregressive_test_payload = self._check_autoregressive_step()
@@ -470,7 +469,15 @@ class LeapLoader(LeapLoaderBase):
470
469
  print_log=print_log,
471
470
  engine_file_contract=EngineFileContract(
472
471
  global_leap_binder.mapping_connections,
473
- 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)
474
481
 
475
482
  def _check_integration_test_exists(self) -> DatasetTestResultPayload:
476
483
  test_result = DatasetTestResultPayload('integration_test')
@@ -602,314 +609,6 @@ class LeapLoader(LeapLoaderBase):
602
609
  result_payloads.extend(test_result)
603
610
  return result_payloads
604
611
 
605
- def _check_foundation_input(self) -> Optional[DatasetTestResultPayload]:
606
- """Push-time checks for the input that carries foundation=FoundationInput(...). One payload,
607
- 'foundation_input', after the handlers were probed (it needs their shapes and dtypes); None
608
- (no payload) when no input is flagged.
609
-
610
- Structural rules (architecture §11): exactly one flagged input; a flagged input the
611
- integration test passes to the model is the native image (its tensor is inverted, float32,
612
- native masks), one it does not pass is a dedicated image for the encoder alone (uint8
613
- allowed, its own masks=); rgb_channels must index the channel axis; autoregressive
614
- integrations and simulations are refused in this version.
615
- """
616
- setup = global_leap_binder.setup_container
617
- flagged = [inp for inp in setup.inputs if inp.foundation is not None]
618
- if not flagged:
619
- return None
620
- test_result = DatasetTestResultPayload('foundation_input')
621
- errors: List[str] = []
622
- warnings: List[str] = []
623
- try:
624
- if len(flagged) > 1:
625
- names = ', '.join(f'`{inp.name}`' for inp in flagged)
626
- errors.append(
627
- f"More than one input encoder carries foundation=: {names}. Exactly one input per "
628
- f"project is the foundation image -- keep foundation= on one of them.")
629
- inp = flagged[0]
630
- wired = self._is_input_wired_to_model(inp.name)
631
- self._check_foundation_input_structure(inp, wired, errors)
632
- self._probe_foundation_range(inp, errors, warnings, test_result.display)
633
- self._check_foundation_masks(inp, wired, errors, warnings)
634
- except Exception as e:
635
- line_number, file_name, stacktrace = get_root_exception_file_and_line_number()
636
- errors.append(f"{repr(e)} in file {file_name}, line_number: {line_number}\nStacktrace:\n{stacktrace}")
637
- if warnings:
638
- test_result.display[TestingSectionEnum.Warnings.name] = "\n".join(warnings)
639
- if errors:
640
- test_result.is_passed = False
641
- test_result.display[TestingSectionEnum.Errors.name] = "\n".join(errors)
642
- return test_result
643
-
644
- def _check_foundation_input_structure(self, inp: InputHandler, wired: bool, errors: List[str]) -> None:
645
- setup = global_leap_binder.setup_container
646
- foundation = inp.foundation
647
- assert foundation is not None
648
- if setup.autoregressive_step is not None:
649
- errors.append(
650
- f"foundation= on input `{inp.name}` is not supported in an autoregressive integration "
651
- f"(tensorleap_autoregressive_step) in this version. Remove foundation=.")
652
- if setup.simulations:
653
- sim_names = ', '.join(f'`{sim.name}`' for sim in setup.simulations)
654
- errors.append(
655
- f"foundation= on input `{inp.name}` is not supported together with simulations "
656
- f"({sim_names}) in this version. Remove foundation= or the simulations.")
657
-
658
- if wired and foundation.masks is not None:
659
- errors.append(
660
- f"Input `{inp.name}` is passed to the model in the integration test, so it is the native "
661
- f"image and the native instance masks apply to it; masks= is only for a dedicated foundation "
662
- f"input that is not passed to the model. Remove masks={foundation.masks_encoder_name}.")
663
- if wired and inp.dtype != 'float32':
664
- errors.append(
665
- f"Input `{inp.name}` is passed to the model in the integration test, so it must return "
666
- f"float32 (got {inp.dtype}); uint8 is allowed only for a dedicated foundation input that "
667
- f"is not passed to the model.")
668
-
669
- if inp.shape is None:
670
- errors.append(
671
- f"Input `{inp.name}`: shape unknown (its handler check failed), rgb_channels not verified.")
672
- return
673
- channel_dim = inp.channel_dim if inp.channel_dim is not None else -1
674
- # channel_dim is the axis in the BATCHED tensor; the probe shape is per-sample.
675
- channel_axis = channel_dim - 1 if channel_dim > 0 else -1
676
- if len(inp.shape) == 0 or (channel_axis >= 0 and channel_axis >= len(inp.shape)):
677
- errors.append(
678
- f"Input `{inp.name}`: sample shape {inp.shape} has no channel axis at channel_dim={channel_dim}, "
679
- f"so rgb_channels={list(foundation.rgb_channels)} cannot be applied.")
680
- return
681
- channels = inp.shape[channel_axis]
682
- out_of_range = [index for index in foundation.rgb_channels if index >= channels]
683
- if out_of_range:
684
- errors.append(
685
- f"Input `{inp.name}`: rgb_channels={list(foundation.rgb_channels)} index "
686
- f"{out_of_range} out of range -- the input has {channels} channels on channel_dim={channel_dim} "
687
- f"(sample shape {inp.shape}).")
688
-
689
- # The declared-range probe: how many samples per state are inverted, and what counts as a
690
- # convention mismatch. Inverted pixels of a correctly declared tensor sit in [0, 255] up to
691
- # rounding and the global-vs-per-channel slack of IMAGENET/CLIP; a byte or signed tensor declared
692
- # UNIT lands far outside, a constant tensor spans nothing.
693
- # Two ways a declaration can be wrong, judged differently:
694
- # - the tensor is WIDER than declared: inverted values fall outside [-2, 257]. A correct
695
- # declaration cannot do that, so it is an error.
696
- # - the tensor is NARROWER than declared: the inverted values span few levels. Real images can
697
- # be narrow too (dark, foggy, low contrast), so this is only a suspicion -- a warning -- except
698
- # at a span no real image reaches (a [0, 1] tensor declared BYTE spans about 1 level), which
699
- # is an error.
700
- # Probe samples are drawn at random (fixed seed, so a run is reproducible) rather than taken from
701
- # the head of the list, which is often one class or scene (e.g. dark aggressor samples).
702
- _FOUNDATION_PROBE_SAMPLES = 5
703
- _FOUNDATION_PROBE_SEED = 0
704
- _FOUNDATION_INVERTED_MIN = -2.0
705
- _FOUNDATION_INVERTED_MAX = 257.0
706
- _FOUNDATION_ERROR_SPAN = 4.0 # at or below: error
707
- _FOUNDATION_WARN_SPAN = 32.0 # below: warning
708
- _FOUNDATION_BGR_GAP = 20.0
709
-
710
- def _foundation_probe_rows(self, inp: InputHandler, preprocess_response: PreprocessResponse) -> List[Any]:
711
- """Up to _FOUNDATION_PROBE_SAMPLES per-sample arrays from the handler, drawn at random with a
712
- fixed seed: rows of the first group when grouped, else original sample ids (instance ids,
713
- which an element-instance preprocess appends after the originals, are skipped)."""
714
- assert preprocess_response.sample_ids is not None
715
- rng = np.random.default_rng(self._FOUNDATION_PROBE_SEED)
716
- if preprocess_response.is_grouped:
717
- rows = list(inp.function(preprocess_response.sample_ids[0], preprocess_response))
718
- picked = rng.choice(len(rows), size=min(self._FOUNDATION_PROBE_SAMPLES, len(rows)), replace=False)
719
- return [rows[i] for i in sorted(picked)]
720
- instance_ids = preprocess_response.instance_to_sample_ids_mappings or {}
721
- originals = [sample_id for sample_id in preprocess_response.sample_ids if sample_id not in instance_ids]
722
- picked = rng.choice(len(originals), size=min(self._FOUNDATION_PROBE_SAMPLES, len(originals)), replace=False)
723
- return [inp.function(originals[i], preprocess_response) for i in sorted(picked)]
724
-
725
- def _probe_foundation_range(self, inp: InputHandler, errors: List[str], warnings: List[str],
726
- display: Dict[str, str]) -> None:
727
- """Invert the declared range on a few samples per state: `uint8 = a*x + b` with one global
728
- (a, b) from bounds(). A correct declaration lands in [-2, 257] and spans more than a narrow
729
- band; a byte or signed tensor declared UNIT does not (the silent catastrophe: embeddings look
730
- normal, zero-shot is at chance). The observed inverted range is shown for every state.
731
- Channel order is not detectable from statistics; the one hint, red far below blue on the
732
- probe, is a warning."""
733
- foundation = inp.foundation
734
- assert foundation is not None
735
- low, high = foundation.bounds()
736
- scale = 255.0 / (high - low)
737
- offset = -low * scale
738
- channel_dim = inp.channel_dim if inp.channel_dim is not None else -1
739
- channel_axis = channel_dim - 1 if channel_dim > 0 else -1
740
- declared = (foundation.range.name if isinstance(foundation.range, ImageRange)
741
- else f'({low:g}, {high:g})')
742
-
743
- red_means: List[float] = []
744
- blue_means: List[float] = []
745
- probe_dtype: Optional[str] = None
746
- for state in sorted(self._preprocess_result(), key=lambda s: s.value):
747
- rows = self._foundation_probe_rows(inp, self._preprocess_result()[state])
748
- if not rows:
749
- continue
750
- observed_min, observed_max = float('inf'), float('-inf')
751
- for row in rows:
752
- row = np.asarray(row)
753
- probe_dtype = probe_dtype or str(row.dtype)
754
- if channel_axis >= len(row.shape) or row.shape[channel_axis] <= max(foundation.rgb_channels):
755
- return # the structural check reported the channel axis already
756
- selected = np.take(row, list(foundation.rgb_channels), axis=channel_axis).astype(np.float64)
757
- inverted = selected * scale + offset
758
- observed_min = min(observed_min, float(inverted.min()))
759
- observed_max = max(observed_max, float(inverted.max()))
760
- red_means.append(float(np.take(inverted, 0, axis=channel_axis).mean()))
761
- blue_means.append(float(np.take(inverted, 2, axis=channel_axis).mean()))
762
- outside = observed_min < self._FOUNDATION_INVERTED_MIN or observed_max > self._FOUNDATION_INVERTED_MAX
763
- span = observed_max - observed_min
764
- collapsed = span <= self._FOUNDATION_ERROR_SPAN
765
- narrow = not collapsed and span < self._FOUNDATION_WARN_SPAN
766
- mark = '\u2717' if (outside or collapsed) else ('!' if narrow else '\u2713')
767
- display[state.name] = (f"foundation input `{inp.name}`: inverted range "
768
- f"{observed_min:.1f}\u2013{observed_max:.1f} {mark}")
769
- observed = (f"Input `{inp.name}` ({state.name}): range={declared} inverts "
770
- f"{len(rows)} random probe samples to {observed_min:.1f}\u2013{observed_max:.1f}")
771
- if outside:
772
- errors.append(
773
- f"{observed}, outside 0\u2013255: the tensor's values are wider than the declared range, "
774
- f"which a correct declaration cannot produce (e.g. byte values declared UNIT, or [-1, 1] "
775
- f"values declared UNIT). range is the convention's theoretical [min, max], not the "
776
- f"samples' min/max. Fix range=.")
777
- elif collapsed:
778
- errors.append(
779
- f"{observed}, a span of {span:.1f} of 256 levels: the tensor is nearly constant under the "
780
- f"declared range, narrower than any real image (e.g. [0, 1] values declared BYTE -- "
781
- f"declare UNIT). Fix range=.")
782
- elif narrow:
783
- warnings.append(
784
- f"{observed}, a span of {span:.1f} of 256 levels: narrower than typical images. Fine for "
785
- f"dark or low-contrast data; otherwise the declared range may be wider than the tensor "
786
- f"(e.g. a /255 tensor declared BYTE -> UNIT, or [0, 1] values declared SIGNED -> UNIT).")
787
- if probe_dtype is not None:
788
- inp.dtype = probe_dtype
789
- if red_means and np.mean(red_means) + self._FOUNDATION_BGR_GAP < np.mean(blue_means):
790
- warnings.append(
791
- f"Input `{inp.name}`: the selected red channel averages {np.mean(red_means):.0f} against "
792
- f"{np.mean(blue_means):.0f} for blue on the probe samples -- natural images rarely do; if the "
793
- f"tensor is BGR, set rgb_channels=(2, 1, 0) (channel order cannot be verified from statistics).")
794
-
795
- @staticmethod
796
- def _foundation_image_hw(inp: InputHandler, row: Any) -> Tuple[int, int]:
797
- """H x W of a per-sample foundation image: the last two axes once the channel axis is removed."""
798
- channel_dim = inp.channel_dim if inp.channel_dim is not None else -1
799
- channel_axis = channel_dim - 1 if channel_dim > 0 else -1
800
- spatial = list(np.asarray(row).shape)
801
- del spatial[channel_axis]
802
- return int(spatial[-2]), int(spatial[-1])
803
-
804
- def _foundation_instance_probes(self, inp: InputHandler) -> List[Tuple[str, PreprocessResponse, Any, Tuple[int, int]]]:
805
- """Up to _FOUNDATION_PROBE_SAMPLES (state, response, original sample id, image H x W) for
806
- samples that have element instances, training first."""
807
- probes: List[Tuple[str, PreprocessResponse, Any, Tuple[int, int]]] = []
808
- for state in sorted(self._preprocess_result(), key=lambda s: s.value):
809
- preprocess_response = self._preprocess_result()[state]
810
- mappings = preprocess_response.sample_ids_to_instance_mappings or {}
811
- for sample_id, instance_ids in mappings.items():
812
- if not instance_ids:
813
- continue
814
- row = inp.function(sample_id, preprocess_response)
815
- probes.append((state.name, preprocess_response, sample_id, self._foundation_image_hw(inp, row)))
816
- if len(probes) >= self._FOUNDATION_PROBE_SAMPLES:
817
- return probes
818
- return probes
819
-
820
- def _check_foundation_masks(self, inp: InputHandler, wired: bool, errors: List[str], warnings: List[str]) -> None:
821
- """Masks rules for a dedicated foundation input (one not passed to the model); a wired input
822
- uses the native masks and `masks=` on it is the structural error above. The project kind
823
- decides: no element instances -> `masks=` is ignored (warning); an instance project without
824
- `masks=` uses the native encoder's masks, nearest-scaled when their H x W differs from the
825
- foundation image's (warning); with `masks=` the named encoder is probed against the native
826
- one on instance 0 of a few samples. "Native" is the registered masks encoder that is not the
827
- foundation one -- the engine takes instance identity and metadata from it and only the
828
- geometry from the foundation one."""
829
- foundation = inp.foundation
830
- assert foundation is not None
831
- if wired:
832
- return
833
- masks_name = foundation.masks_encoder_name
834
- if not self._has_element_instances():
835
- if masks_name is not None:
836
- warnings.append(
837
- f"Input `{inp.name}`: masks={masks_name} is ignored -- this project has no element instances "
838
- f"(no tensorleap_element_instance_preprocess), so there are no instances to mask.")
839
- return
840
- handlers = global_leap_binder.setup_container.instance_masks
841
- native = next((handler for handler in handlers if handler.name != masks_name), None)
842
- if native is None:
843
- errors.append(
844
- f"Input `{inp.name}`: masks={masks_name} is the only registered masks encoder; an instance "
845
- f"project needs the native one too (the encoder bound through "
846
- f"tensorleap_element_instance_preprocess), which defines the instances.")
847
- return
848
- probes = self._foundation_instance_probes(inp)
849
- if masks_name is None:
850
- warnings.append(
851
- f"Input `{inp.name}` names no masks=; the native masks encoder `{native.name}` is used for it, "
852
- f"assuming the native framing.")
853
- for state_name, preprocess_response, sample_id, (image_h, image_w) in probes:
854
- native_instance = native.function(sample_id, preprocess_response, 0)
855
- if native_instance is None:
856
- continue
857
- mask_shape = tuple(np.asarray(native_instance.mask).shape)
858
- if mask_shape != (image_h, image_w):
859
- warnings.append(
860
- f"Input `{inp.name}` ({state_name}): the native mask is {'x'.join(map(str, mask_shape))} "
861
- f"and the foundation image {image_h}x{image_w}; the mask will be nearest-scaled to the "
862
- f"foundation image, assuming the native framing. If the framing differs (crop, letterbox, "
863
- f"tile), add masks= with a masks encoder drawing in the foundation image's coordinates.")
864
- break
865
- return
866
- foundation_handler = next((handler for handler in handlers if handler.name == masks_name), None)
867
- if foundation_handler is None:
868
- errors.append(
869
- f"Input `{inp.name}`: masks={masks_name} is not a registered masks encoder; pass the function "
870
- f"returned by a @tensorleap_instances_masks_encoder decorator.")
871
- return
872
- for state_name, preprocess_response, sample_id, (image_h, image_w) in probes:
873
- native_instance = native.function(sample_id, preprocess_response, 0)
874
- foundation_instance = foundation_handler.function(sample_id, preprocess_response, 0)
875
- where = f"instance 0 of sample {sample_id!r} ({state_name})"
876
- if foundation_instance is None:
877
- if native_instance is not None:
878
- errors.append(
879
- f"Input `{inp.name}`: masks encoder `{masks_name}` returned None for {where} where the "
880
- f"native encoder `{native.name}` returned a mask -- every instance the native encoder "
881
- f"creates needs a foundation mask, or its row has no vector.")
882
- continue
883
- if isinstance(foundation_instance, np.ndarray):
884
- foundation_instance = ElementInstance(name=masks_name, mask=foundation_instance)
885
- mask = np.asarray(foundation_instance.mask)
886
- if mask.ndim != 2:
887
- errors.append(
888
- f"Input `{inp.name}`: masks encoder `{masks_name}` returned a mask of shape "
889
- f"{tuple(mask.shape)} for {where}; a foundation mask is a 2-D H x W array.")
890
- continue
891
- mask_h, mask_w = int(mask.shape[0]), int(mask.shape[1])
892
- if (mask_h, mask_w) != (image_h, image_w) and not (image_h % mask_h == 0 and image_w % mask_w == 0):
893
- errors.append(
894
- f"Input `{inp.name}`: the mask from `{masks_name}` is {mask_h}x{mask_w} for {where} but the "
895
- f"foundation image is {image_h}x{image_w}; the mask must be the image's H x W or an integer "
896
- f"divisor of it.")
897
- if native_instance is None:
898
- continue # a mask where the native encoder returned None is ignored (no row)
899
- geometry_only = foundation_instance.name == masks_name and foundation_instance.instance_metadata is None
900
- if geometry_only:
901
- continue # a bare array wrapped by the decorator: nothing declared to compare
902
- if foundation_instance.name != native_instance.name:
903
- warnings.append(
904
- f"Input `{inp.name}`: masks encoder `{masks_name}` names {where} {foundation_instance.name!r} "
905
- f"while the native encoder `{native.name}` names it {native_instance.name!r}; only the "
906
- f"geometry is taken from `{masks_name}`, the name comes from the native encoder.")
907
- if foundation_instance.instance_metadata != native_instance.instance_metadata:
908
- warnings.append(
909
- f"Input `{inp.name}`: masks encoder `{masks_name}` returns instance_metadata for {where} "
910
- f"that differs from the native encoder `{native.name}`'s; only the geometry is taken from "
911
- f"`{masks_name}`, the metadata comes from the native encoder.")
912
-
913
612
  def _check_simulations(self):
914
613
  # type: () -> List[DatasetTestResultPayload]
915
614
  result_payloads = []
@@ -1295,8 +994,7 @@ class LeapLoader(LeapLoaderBase):
1295
994
  for inp in setup.inputs:
1296
995
  if inp.shape is None:
1297
996
  raise Exception(f"cant calculate shape for input, input name:{inp.name}")
1298
- inputs.append(DatasetInputInstance(name=inp.name, shape=inp.shape, channel_dim=inp.channel_dim,
1299
- foundation=self._foundation_input_instance(inp)))
997
+ inputs.append(DatasetInputInstance(name=inp.name, shape=inp.shape, channel_dim=inp.channel_dim))
1300
998
 
1301
999
  if setup.autoregressive_step is not None:
1302
1000
  # The hook is the sole input source; report its step-0 inputs as the dataset inputs so
@@ -1381,36 +1079,6 @@ class LeapLoader(LeapLoaderBase):
1381
1079
  custom_losses=custom_losses, metrics=metrics, simulations=simulations,
1382
1080
  has_element_instances=self._has_element_instances())
1383
1081
 
1384
- def _foundation_input_instance(self, inp: InputHandler) -> Optional[FoundationInputInstance]:
1385
- if inp.foundation is None:
1386
- return None
1387
- if inp.dtype is None:
1388
- raise Exception(f"cant determine dtype for input, input name:{inp.name}")
1389
- low, high = inp.foundation.bounds()
1390
- return FoundationInputInstance(range=[low, high], rgb_channels=list(inp.foundation.rgb_channels),
1391
- dtype=inp.dtype, wired_to_model=self._is_input_wired_to_model(inp.name),
1392
- masks_encoder=inp.foundation.masks_encoder_name)
1393
-
1394
- def _is_input_wired_to_model(self, name: str) -> bool:
1395
- """Does the integration test pass this input to the model?
1396
-
1397
- exec_script runs the integration test in mapping mode before any handler is probed. An input
1398
- encoder called there appends a connection of type `Input`; passing its result to the model
1399
- re-tags that node `Input0..9` (`model_input_index=` tags it at decoration). So after
1400
- exec_script: `InputN` -> wired, `Input` or no connection at all -> not wired. An input tagged
1401
- with `model_input_index=` but never called in the integration test has no connection and is
1402
- not wired either -- the engine would not bind it, so the two views agree. A legacy script
1403
- without an integration test wires every input through the mapping file, so all count as wired.
1404
- """
1405
- self.exec_script()
1406
- if global_leap_binder.integration_test_func is None:
1407
- return True
1408
- return any(connection.node is not None
1409
- and connection.node.name == name
1410
- and connection.node.type is not NodeMappingType.Input
1411
- and connection.node.type.name.startswith('Input')
1412
- for connection in global_leap_binder.mapping_connections)
1413
-
1414
1082
  def _has_element_instances(self) -> bool:
1415
1083
  """Does this dataset have element instances? Both halves, because either alone lies.
1416
1084
 
@@ -2144,7 +1812,8 @@ class LeapLoader(LeapLoaderBase):
2144
1812
  return self.get_sample_id_type()(sample_id)
2145
1813
 
2146
1814
  def get_false_positive_instances(self, state: DataStateEnum, sample_ids: List[Union[str, int]],
2147
- predictions: Dict[str, npt.NDArray[np.float32]]
1815
+ predictions: Dict[str, npt.NDArray[np.float32]],
1816
+ raise_errors: bool = False
2148
1817
  ) -> List[Optional[List[ElementInstance]]]:
2149
1818
  """Run the false-positive encoder once per sample. `predictions` arrays carry a leading
2150
1819
  batch axis of len(sample_ids); row i is handed to the user function for sample_ids[i].
@@ -2154,6 +1823,7 @@ class LeapLoader(LeapLoaderBase):
2154
1823
  returned something that is not a list of ElementInstance. A failed sample does not fail
2155
1824
  the others; its error is printed with the sample id. A batch-size mismatch between
2156
1825
  `predictions` and `sample_ids`, or a missing encoder, still raises: those are caller errors.
1826
+ With `raise_errors`, the first failing sample re-raises instead.
2157
1827
  """
2158
1828
  self.exec_script()
2159
1829
  handler = global_leap_binder.setup_container.false_positive_instances
@@ -2170,8 +1840,11 @@ class LeapLoader(LeapLoaderBase):
2170
1840
  row = {name: array[i] for name, array in predictions.items()}
2171
1841
  try:
2172
1842
  instances = handler.function(self._native_sample_id(sample_id), preprocess_response, row)
2173
- self._validate_false_positive_instances(instances, set(self._instance_metric_handler_by_name()))
1843
+ self._validate_false_positive_instances(instances, set(self._instance_metric_handler_by_name()),
1844
+ preprocess_response.state, handler)
2174
1845
  except Exception as e:
1846
+ if raise_errors:
1847
+ raise
2175
1848
  print(f"tensorleap_false_positive_instances_encoder failed for sample {sample_id!r} "
2176
1849
  f"(state {state.name}): {e!r}")
2177
1850
  results.append(None)
@@ -2180,7 +1853,9 @@ class LeapLoader(LeapLoaderBase):
2180
1853
  return results
2181
1854
 
2182
1855
  @staticmethod
2183
- def _validate_false_positive_instances(instances: Any, registered_instance_metrics: Set[str]) -> None:
1856
+ def _validate_false_positive_instances(instances: Any, registered_instance_metrics: Set[str],
1857
+ state: Optional[DataStateType],
1858
+ handler: FalsePositiveInstancesHandler) -> None:
2184
1859
  prefix = "tensorleap_false_positive_instances_encoder validation failed: "
2185
1860
  if not isinstance(instances, list):
2186
1861
  raise Exception(f"{prefix}The return type should be a list of ElementInstance. "
@@ -2204,6 +1879,7 @@ class LeapLoader(LeapLoaderBase):
2204
1879
  except (TypeError, ValueError):
2205
1880
  raise Exception(f"{prefix}instance_metrics[{key!r}] of element {j} should be castable to "
2206
1881
  f"float. Got {type(value)}.")
1882
+ validate_confidence_contract(instances, state, handler)
2207
1883
 
2208
1884
  def get_false_positive_empty_gt(self, state: DataStateEnum,
2209
1885
  sample_id: Union[str, int]) -> Dict[str, npt.NDArray[np.float32]]:
@@ -61,7 +61,8 @@ def to_numpy_return_fp_masks_wrapper(encoder_function: Callable[..., Any]) -> Ca
61
61
  for instance in result:
62
62
  if not isinstance(instance, ElementInstance):
63
63
  continue
64
- instance.mask = np.array(instance.mask)
64
+ if instance.mask is not None:
65
+ instance.mask = np.array(instance.mask)
65
66
  if instance.instance_metadata is not None and instance.instance_metadata_is_none is None:
66
67
  instance.instance_metadata_is_none = {
67
68
  k: is_absent_metadata_value(v) for k, v in instance.instance_metadata.items()}
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "code-loader"
3
- version = "1.0.219rc1"
3
+ version = "1.0.220"
4
4
  description = ""
5
5
  authors = ["dorhar <doron.harnoy@tensorleap.ai>"]
6
6
  license = "MIT"
File without changes