code-loader 1.0.218.dev0__tar.gz → 1.0.219rc1__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.218.dev0 → code_loader-1.0.219rc1}/PKG-INFO +4 -3
  2. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/datasetclasses.py +79 -6
  3. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/enums.py +14 -0
  4. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/responsedataclasses.py +16 -8
  5. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/inner_leap_binder/leapbinder.py +9 -17
  6. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/inner_leap_binder/leapbinder_decorators.py +91 -43
  7. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/leaploader.py +351 -28
  8. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/mixpanel_tracker.py +81 -1
  9. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/pyproject.toml +1 -1
  10. code_loader-1.0.218.dev0/code_loader/inner_leap_binder/fp_confidence_contract.py +0 -88
  11. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/LICENSE +0 -0
  12. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/README.md +0 -0
  13. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/__init__.py +0 -0
  14. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/__init__.py +0 -0
  15. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/exceptions.py +0 -0
  16. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/mapping.py +0 -0
  17. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/sim_config.py +0 -0
  18. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/contract/visualizer_classes.py +0 -0
  19. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/default_losses.py +0 -0
  20. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/default_metrics.py +0 -0
  21. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/__init__.py +0 -0
  22. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/api.py +0 -0
  23. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/cli_config_utils.py +0 -0
  24. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/client.py +0 -0
  25. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/epoch.py +0 -0
  26. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/experiment.py +0 -0
  27. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/experiment_context.py +0 -0
  28. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/types.py +0 -0
  29. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/utils.py +0 -0
  30. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/experiment_api/workingspace_config_utils.py +0 -0
  31. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/inner_leap_binder/__init__.py +0 -0
  32. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/leaploaderbase.py +0 -0
  33. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/plot_functions/__init__.py +0 -0
  34. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/plot_functions/plot_functions.py +0 -0
  35. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/plot_functions/visualize.py +0 -0
  36. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/utils.py +0 -0
  37. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/visualizers/__init__.py +0 -0
  38. {code_loader-1.0.218.dev0 → code_loader-1.0.219rc1}/code_loader/visualizers/default_visualizers.py +0 -0
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: code-loader
3
- Version: 1.0.218.dev0
3
+ Version: 1.0.219rc1
4
4
  Summary:
5
- Home-page: https://github.com/tensorleap/code-loader
6
5
  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,6 +20,7 @@ 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
23
24
  Project-URL: Repository, https://github.com/tensorleap/code-loader
24
25
  Description-Content-Type: text/markdown
25
26
 
@@ -6,12 +6,15 @@ 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
9
+ MetricDirection, DatasetMetadataType, LatentSpaceReduction, CustomLatentSpaceComputedAt, ImageRange
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"
15
18
 
16
19
  # Hard cap on a custom latent space's per-sample width, applied AFTER any reduction. The
17
20
  # soft threshold only warns. MAX_CUSTOM_LATENT_SPACES mirrors the engine's
@@ -179,8 +182,6 @@ class ElementInstance:
179
182
  # Per-instance metric values keyed by the registered name of a tensorleap_custom_instances_metric.
180
183
  # Only meaningful on false-positive instances (they have no ground-truth row for the metric to run on).
181
184
  instance_metrics: Optional[Dict[str, float]] = None
182
- score: Optional[float] = None
183
- matched_gt: Optional[bool] = None
184
185
 
185
186
  SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
186
187
  InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse, int], Optional[ElementInstance]]
@@ -323,10 +324,85 @@ class DatasetBaseHandler:
323
324
  function: SectionCallableInterface
324
325
 
325
326
 
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
+
326
398
  @dataclass
327
399
  class InputHandler(DatasetBaseHandler):
328
400
  shape: Optional[List[int]] = None
329
401
  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
330
406
 
331
407
  @dataclass
332
408
  class ElementInstanceMasksHandler:
@@ -337,9 +413,6 @@ class ElementInstanceMasksHandler:
337
413
  class FalsePositiveInstancesHandler:
338
414
  name: str
339
415
  function: Callable[..., Any]
340
- operating_threshold: Optional[float] = None
341
- candidate_floor: Optional[float] = None
342
- max_candidates_per_image: int = 30
343
416
 
344
417
  @dataclass
345
418
  class GroundTruthHandler(DatasetBaseHandler):
@@ -79,3 +79,17 @@ 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,10 +19,26 @@ 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
+
22
35
  @dataclass
23
36
  class DatasetInputInstance(DatasetBaseSectionInstance):
24
37
  shape: List[int]
25
38
  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
26
42
 
27
43
 
28
44
  @dataclass
@@ -171,18 +187,10 @@ class LeapAnalysisConfiguration:
171
187
  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
188
 
173
189
 
174
- @dataclass
175
- class FalsePositiveConfidenceConfig:
176
- operating_threshold: float
177
- candidate_floor: float
178
- max_candidates_per_image: int
179
-
180
-
181
190
  @dataclass
182
191
  class EngineFileContract:
183
192
  node_connections: Optional[List[NodeConnection]] = None
184
193
  leap_analysis_configuration: Optional[LeapAnalysisConfiguration] = None
185
- false_positive_confidence: Optional[FalsePositiveConfidenceConfig] = None
186
194
 
187
195
 
188
196
  @dataclass
@@ -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, \
20
+ CustomLatentSpaceHandler, InstanceMetricHandler, MAX_CUSTOM_LATENT_SPACES, FoundationInput, \
21
21
  SimulationHandler, _simulation_context, AutoregressiveStepHandler, AutoregressiveStepCallableInterface, \
22
22
  AUTOREGRESSIVE_LATENT_SPACE_AGGREGATIONS, AUTOREGRESSIVE_IMPLICIT_ARG_NAMES, \
23
23
  AutoregressiveMetricHandler, AutoregressiveLossHandler, AutoregressiveVisualizerHandler
@@ -31,8 +31,6 @@ 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
36
34
  from code_loader.visualizers.default_visualizers import DefaultVisualizer, \
37
35
  default_graph_visualizer, \
38
36
  default_image_visualizer, default_horizontal_bar_visualizer, default_word_visualizer, \
@@ -303,7 +301,8 @@ class LeapBinder:
303
301
  SimulationHandler(name=name, function=function, sim_config=sim_config)
304
302
  )
305
303
 
306
- def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1) -> None:
304
+ def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1,
305
+ foundation: Optional[FoundationInput] = None) -> None:
307
306
  """
308
307
  Set the input handler function.
309
308
 
@@ -311,6 +310,7 @@ class LeapBinder:
311
310
  function (SectionCallableInterface): The input handler function.
312
311
  name (str): The name of the input section.
313
312
  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))
326
+ self.setup_container.inputs.append(InputHandler(name, function, channel_dim=channel_dim, foundation=foundation))
327
327
 
328
328
  self._encoder_names.append(name)
329
329
 
@@ -343,24 +343,15 @@ 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,
347
- operating_threshold: Optional[float] = None,
348
- candidate_floor: Optional[float] = None,
349
- max_candidates_per_image: int = 30) -> None:
346
+ def set_false_positive_instances(self, function: Callable[..., Any], name: str) -> None:
350
347
  """
351
348
  Set the false-positive instances handler. It receives (sample_id, preprocess, predictions)
352
349
  and returns a list of ElementInstance, one per false-positive prediction.
353
350
  """
354
351
  if self.setup_container.false_positive_instances is not None:
355
352
  raise Exception("only one tensorleap_false_positive_instances_encoder can be defined")
356
- validate_confidence_args(operating_threshold, candidate_floor, max_candidates_per_image)
357
353
  function = to_numpy_return_fp_masks_wrapper(function)
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)
354
+ self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(name, function)
364
355
 
365
356
  def set_false_positive_empty_gt(self, function: Callable[..., Any], gt_name: str) -> None:
366
357
  """
@@ -1083,6 +1074,8 @@ class LeapBinder:
1083
1074
  # setting shape in setup for all encoders
1084
1075
  if isinstance(dataset_base_handler, (InputHandler, GroundTruthHandler)):
1085
1076
  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)
1086
1079
  _warn_if_group_spans_multiple_files(test_result)
1087
1080
  return test_result
1088
1081
 
@@ -1145,7 +1138,6 @@ class LeapBinder:
1145
1138
  self.check_simulations()
1146
1139
  self.validate_ignore_latent_spaces()
1147
1140
  self.validate_use_additional_set_as_unlabeled_candidate()
1148
- print("Successful!")
1149
1141
 
1150
1142
  def validate_autoregressive_setup(self) -> None:
1151
1143
  """Structural rules for autoregressive integrations (no-op when the hook is absent).
@@ -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
32
+ MAX_CUSTOM_LATENT_SPACE_DIM, CUSTOM_LATENT_SPACE_WARN_DIM, FoundationInput, masks_encoder_name_attribute
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,8 +39,6 @@ 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
44
42
  from code_loader.mixpanel_tracker import clear_integration_events, AnalyticsEvent, emit_integration_event_once
45
43
 
46
44
  _called_from_inside_tl_decorator = 0
@@ -52,6 +50,12 @@ _integration_test_started = False
52
50
  _mapping_dataset_is_grouped = False
53
51
  _call_from_tl_platform = os.environ.get('IS_TENSORLEAP_PLATFORM') == 'true'
54
52
 
53
+ # Verdicts of the local status table, and the exit status of a run that was clean but left a
54
+ # mandatory part out of the integration test (0 = ready to push, 1 = crash, as Python reports it).
55
+ INTEGRATION_READY = "ready"
56
+ INTEGRATION_INCOMPLETE = "incomplete"
57
+ EXIT_CODE_INTEGRATION_INCOMPLETE = 3
58
+
55
59
  # ---- warnings store (module-level) ----
56
60
  _UNSET = object()
57
61
  _STORED_WARNINGS: List[Dict[str, Any]] = []
@@ -3264,21 +3268,15 @@ def _register_builtin_instance_metadata() -> None:
3264
3268
  makes the engine produce instance samples.
3265
3269
  """
3266
3270
  if any(h.name == "builtin_instance_metadata" for h in leap_binder.setup_container.metadata):
3267
- declare_confidence_metadata_types(leap_binder.setup_container)
3268
3271
  return
3269
3272
 
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:
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:
3274
3276
  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
3278
3277
  return result
3279
3278
 
3280
3279
  leap_binder.set_metadata(builtin_instance_metadata, "builtin_instance_metadata")
3281
- declare_confidence_metadata_types(leap_binder.setup_container)
3282
3280
 
3283
3281
 
3284
3282
  def _register_builtin_instance_extra_metadata(metadata_types: Dict[str, DatasetMetadataType]) -> None:
@@ -3480,6 +3478,12 @@ def tensorleap_instances_masks_encoder(name: str):
3480
3478
  (f'tensorleap_instances_masks_encoder validation failed: '
3481
3479
  f'Unsupported return type. Should be a ElementInstance or None. Got {type(result)}.')
3482
3480
 
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
+
3483
3487
  def inner_without_validate(sample_id, preprocess_response, instance_id):
3484
3488
  global _called_from_inside_tl_decorator
3485
3489
  _called_from_inside_tl_decorator += 1
@@ -3489,6 +3493,11 @@ def tensorleap_instances_masks_encoder(name: str):
3489
3493
  finally:
3490
3494
  _called_from_inside_tl_decorator -= 1
3491
3495
 
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)
3492
3501
  return result
3493
3502
 
3494
3503
  leap_binder.set_instance_masks(inner_without_validate, name)
@@ -3504,15 +3513,16 @@ def tensorleap_instances_masks_encoder(name: str):
3504
3513
  _validate_result(result)
3505
3514
  return result
3506
3515
 
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)
3507
3519
  return inner
3508
3520
 
3509
3521
  return decorating_function
3510
3522
 
3511
3523
 
3512
3524
  def tensorleap_false_positive_instances_encoder(
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):
3525
+ name: str, instance_metadata_types: Optional[Dict[str, DatasetMetadataType]] = None):
3516
3526
  """Register the false-positive instances encoder.
3517
3527
 
3518
3528
  `instance_metadata_types` declares the keys (and types) of the `instance_metadata` the returned
@@ -3520,8 +3530,6 @@ def tensorleap_false_positive_instances_encoder(
3520
3530
  with any keys the element-instance preprocess declares; a key not declared here (or by the
3521
3531
  GT instances) is dropped from false-positive rows by the engine.
3522
3532
  """
3523
- validate_confidence_args(operating_threshold, candidate_floor, max_candidates_per_image)
3524
-
3525
3533
  def decorating_function(user_function: Callable):
3526
3534
  def _validate_input_args(sample_id, preprocess_response, predictions):
3527
3535
  assert isinstance(sample_id, (str, int)), \
@@ -3554,8 +3562,7 @@ def tensorleap_false_positive_instances_encoder(
3554
3562
 
3555
3563
  return result
3556
3564
 
3557
- leap_binder.set_false_positive_instances(inner_without_validate, name, operating_threshold, candidate_floor,
3558
- max_candidates_per_image)
3565
+ leap_binder.set_false_positive_instances(inner_without_validate, name)
3559
3566
  _register_builtin_instance_metadata()
3560
3567
  if instance_metadata_types:
3561
3568
  _register_builtin_instance_extra_metadata(instance_metadata_types)
@@ -3569,8 +3576,6 @@ def tensorleap_false_positive_instances_encoder(
3569
3576
  result = inner_without_validate(sample_id, preprocess_response, predictions)
3570
3577
 
3571
3578
  _validate_result(result)
3572
- validate_confidence_contract(result, preprocess_response.state,
3573
- leap_binder.setup_container.false_positive_instances)
3574
3579
  return result
3575
3580
 
3576
3581
  return inner
@@ -3713,7 +3718,24 @@ def tensorleap_instances_length_encoder(name: str):
3713
3718
  return decorating_function
3714
3719
 
3715
3720
 
3716
- def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=None):
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
+ """
3717
3739
  def decorating_function(user_function: SectionCallableInterface):
3718
3740
  for input_handler in leap_binder.setup_container.inputs:
3719
3741
  if input_handler.name == name:
@@ -3742,6 +3764,20 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3742
3764
  f"channel axis in the batched tensor (batch = axis 0), so 0 is invalid. Use 1 "
3743
3765
  f"for channel-first (NCHW) and -1 for channel-last (NHWC).")
3744
3766
 
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
+
3745
3781
  def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
3746
3782
  _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
3747
3783
 
@@ -3749,9 +3785,9 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3749
3785
  assert isinstance(result, np.ndarray), \
3750
3786
  (f'{user_function.__name__}() validation failed: '
3751
3787
  f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
3752
- assert result.dtype == np.float32, \
3788
+ assert result.dtype in allowed_dtypes, \
3753
3789
  (f'{user_function.__name__}() validation failed: '
3754
- f'The return type should be a numpy array of type float32. Got {result.dtype}.')
3790
+ f'The return type should be a numpy array of type {allowed_dtypes_text}. Got {result.dtype}.')
3755
3791
  assert channel_dim - 1 <= len(result.shape), (f'{user_function.__name__}() validation failed: '
3756
3792
  f'The channel_dim ({channel_dim}) should be <= to the rank of the resulting input rank ({len(result.shape)}).')
3757
3793
 
@@ -3773,7 +3809,7 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3773
3809
 
3774
3810
  return result
3775
3811
 
3776
- leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim)
3812
+ leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim, foundation=foundation)
3777
3813
 
3778
3814
  def inner(*args, **kwargs):
3779
3815
  if not _call_from_tl_platform:
@@ -4203,9 +4239,6 @@ def tensorleap_status_table():
4203
4239
  # printed, gate readiness, or be recommended as a next step.
4204
4240
  table[:] = [row for row in table if row["name"] != "tensorleap_input_encoder"]
4205
4241
 
4206
- ready_mess = "\nAll parts have been successfully set. If no errors accured, you can now push the project to the Tensorleap system."
4207
- not_ready_mess = "\nSome mandatory components have not yet been added to the Integration test. Recommended next interface to add is: "
4208
- mandatory_ready_mess = "\nAll mandatory parts have been successfully set. If no errors accured, you can now push the project to the Tensorleap system or continue to the next optional reccomeded interface,adding: "
4209
4242
  code_mapping_failure_mes = "Tensorleap_integration_test code flow failed, check raised exception."
4210
4243
 
4211
4244
  name_width = max(len(row["name"]) for row in table)
@@ -4220,18 +4253,9 @@ def tensorleap_status_table():
4220
4253
  for row in table:
4221
4254
  print(f"{row['name'].ljust(name_width)} | {row['Added to integration'].ljust(status_width)}")
4222
4255
 
4223
- # Determine next_step based on original table order (recommended integration order)
4224
- ready = True
4225
- next_step = None
4226
- for row in table:
4227
- if not _crashed["value"] and ready:
4228
- if row["Added to integration"] != CHECK:
4229
- ready = False
4230
- next_step = row["name"]
4231
-
4232
4256
  if code_mapping_failure[0]:
4233
4257
  print(f"\n{CROSS} {code_mapping_failure_mes}")
4234
- return
4258
+ return None
4235
4259
 
4236
4260
  if _crashed["value"]:
4237
4261
  crashed_at = _current_func['name']
@@ -4239,11 +4263,24 @@ def tensorleap_status_table():
4239
4263
  print(f"\nScript crashed before completing all steps. crashed at function '{crashed_at}'.")
4240
4264
  else:
4241
4265
  print("\nScript crashed before completing all steps.")
4242
- return
4266
+ return None
4243
4267
 
4244
- print(ready_mess) if ready else print(
4245
- mandatory_ready_mess + next_step
4246
- ) if (next_step and "optional" in next_step) else print(not_ready_mess + (next_step or ""))
4268
+ # The next step follows the table order (the recommended integration order), but every
4269
+ # mandatory row comes before any optional one: rows appended at registration time (e.g. the
4270
+ # autoregressive step) sit after the optional rows and must still gate readiness.
4271
+ missing = [row["name"] for row in table if row["Added to integration"] != CHECK]
4272
+ missing_mandatory = [name for name in missing if "optional" not in name]
4273
+ if missing_mandatory:
4274
+ next_step = missing_mandatory[0]
4275
+ what = "has not run yet" if next_step == "tensorleap_integration_test" \
4276
+ else "is not used in the integration test yet"
4277
+ print(f"\nThis integration is not ready to push: `{next_step}` {what}. Add it next.")
4278
+ return INTEGRATION_INCOMPLETE
4279
+
4280
+ print("\nReady to push: all mandatory parts are in the integration test.")
4281
+ if missing:
4282
+ print(f"Optional next: `{_remove_suffix(missing[0], ' (optional)')}`.")
4283
+ return INTEGRATION_READY
4247
4284
 
4248
4285
  def set_current(name: str):
4249
4286
  _current_func["name"] = name
@@ -4304,7 +4341,18 @@ def tensorleap_status_table():
4304
4341
  _mark_unknowns_as_cross()
4305
4342
  _resolve_sim_row()
4306
4343
 
4307
- _print_table()
4344
+ verdict = _print_table()
4345
+ if verdict == INTEGRATION_INCOMPLETE and not _crashed["value"]:
4346
+ # A clean run that leaves a mandatory row unexercised must not exit 0: helpers and
4347
+ # scripts read exit 0 as "ready to push". An atexit handler cannot change the exit
4348
+ # status with sys.exit (Python ignores SystemExit there), so flush and leave directly.
4349
+ # Exit handlers registered before code-loader was imported are skipped; logging, the
4350
+ # one that matters, is shut down explicitly.
4351
+ import logging
4352
+ sys.stdout.flush()
4353
+ sys.stderr.flush()
4354
+ logging.shutdown()
4355
+ os._exit(EXIT_CODE_INTEGRATION_INCOMPLETE)
4308
4356
 
4309
4357
  def handle_exception(exc_type, exc_value, exc_traceback):
4310
4358
  _crashed["value"] = True