code-loader 1.0.219rc1__tar.gz → 1.0.221__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.221}/PKG-INFO +1 -1
  2. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/datasetclasses.py +140 -27
  3. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/enums.py +23 -9
  4. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/responsedataclasses.py +19 -3
  5. code_loader-1.0.221/code_loader/inner_leap_binder/fp_confidence_contract.py +95 -0
  6. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/inner_leap_binder/leapbinder.py +39 -7
  7. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/inner_leap_binder/leapbinder_decorators.py +107 -21
  8. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/leaploader.py +221 -86
  9. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/utils.py +2 -1
  10. {code_loader-1.0.219rc1 → code_loader-1.0.221}/pyproject.toml +1 -1
  11. {code_loader-1.0.219rc1 → code_loader-1.0.221}/LICENSE +0 -0
  12. {code_loader-1.0.219rc1 → code_loader-1.0.221}/README.md +0 -0
  13. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/__init__.py +0 -0
  14. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/__init__.py +0 -0
  15. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/exceptions.py +0 -0
  16. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/mapping.py +0 -0
  17. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/sim_config.py +0 -0
  18. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/contract/visualizer_classes.py +0 -0
  19. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/default_losses.py +0 -0
  20. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/default_metrics.py +0 -0
  21. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/__init__.py +0 -0
  22. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/api.py +0 -0
  23. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/cli_config_utils.py +0 -0
  24. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/client.py +0 -0
  25. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/epoch.py +0 -0
  26. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/experiment.py +0 -0
  27. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/experiment_context.py +0 -0
  28. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/types.py +0 -0
  29. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/utils.py +0 -0
  30. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/experiment_api/workingspace_config_utils.py +0 -0
  31. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/inner_leap_binder/__init__.py +0 -0
  32. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/leaploaderbase.py +0 -0
  33. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/mixpanel_tracker.py +0 -0
  34. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/plot_functions/__init__.py +0 -0
  35. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/plot_functions/plot_functions.py +0 -0
  36. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/plot_functions/visualize.py +0 -0
  37. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/visualizers/__init__.py +0 -0
  38. {code_loader-1.0.219rc1 → code_loader-1.0.221}/code_loader/visualizers/default_visualizers.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-loader
3
- Version: 1.0.219rc1
3
+ Version: 1.0.221
4
4
  Summary:
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  import warnings
2
2
  from dataclasses import dataclass, field
3
- from typing import Any, Callable, List, Optional, Dict, Union, Type, Literal, Tuple, cast
3
+ from typing import Any, Callable, List, Optional, Dict, Sequence, Union, Type, Literal, Tuple, cast
4
4
  import re
5
5
  import numpy as np
6
6
  import numpy.typing as npt
@@ -15,6 +15,8 @@ custom_latent_space_attribute = "custom_latent_space"
15
15
  # Stamped by @tensorleap_instances_masks_encoder on the function it returns, so FoundationInput(masks=fn)
16
16
  # can verify it was handed a registered masks encoder and resolve it to the registered name.
17
17
  masks_encoder_name_attribute = "tensorleap_masks_encoder_name"
18
+ # (min, max) per channel, in R, G, B order.
19
+ ChannelBounds = Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
18
20
 
19
21
  # Hard cap on a custom latent space's per-sample width, applied AFTER any reduction. The
20
22
  # soft threshold only warns. MAX_CUSTOM_LATENT_SPACES mirrors the engine's
@@ -173,7 +175,7 @@ class PreprocessResponse:
173
175
  @dataclass
174
176
  class ElementInstance:
175
177
  name: str
176
- mask: npt.NDArray[np.float32]
178
+ mask: Optional[npt.NDArray[np.float32]]
177
179
  instance_metadata: Optional[Dict[str, Union[Optional[str], int, bool, Optional[float]]]] = None
178
180
  # Per-key "this value is absent", the same pair shape DatasetSample carries. Populated at the
179
181
  # masks funnel (utils.to_numpy_return_masks_wrapper) so the engine copies flags rather than
@@ -182,6 +184,12 @@ class ElementInstance:
182
184
  # Per-instance metric values keyed by the registered name of a tensorleap_custom_instances_metric.
183
185
  # Only meaningful on false-positive instances (they have no ground-truth row for the metric to run on).
184
186
  instance_metrics: Optional[Dict[str, float]] = None
187
+ # Confidence mode (the FP encoder declares operating_threshold): the candidate's score, required on every
188
+ # candidate. Ignored (may stay None) when no threshold is declared.
189
+ score: Optional[float] = None
190
+ # Confidence mode, training / validation / test only: whether this candidate matches a ground-truth instance,
191
+ # by the integration's own rule (IoU threshold, class). Ignored on unlabeled / additional.
192
+ matched_gt: Optional[bool] = None
185
193
 
186
194
  SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
187
195
  InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse, int], Optional[ElementInstance]]
@@ -328,25 +336,33 @@ class DatasetBaseHandler:
328
336
  class FoundationInput:
329
337
  """Marks an input encoder as the image a foundation encoder (SigLIP 2, OWLv2) reads.
330
338
 
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)`).
339
+ Exactly one input encoder per project carries it. The platform converts the tensor back to uint8
340
+ pixel values with one fixed affine map per channel resolved from `rgb_range` -- never from per-image
341
+ statistics -- and feeds the result to the encoder's own preprocessing.
342
+
343
+ `rgb_range`: the convention's theoretical [min, max] of the tensor, not the observed min/max of the
344
+ samples. One of:
345
+ - an `ImageRange` preset (per-channel where the convention is: IMAGENET, CLIP);
346
+ - one `(min, max)` pair, the same for all three channels (e.g. `(0, 1)`, `(-1, 1)`);
347
+ - three `(min, max)` pairs in R, G, B order, for a custom per-channel normalisation
348
+ `(x / 255 - mean_c) / std_c`: `((-m_r / s_r, (1 - m_r) / s_r), (...G...), (...B...))`.
349
+ Any other count of pairs is rejected. E.g. `UNIT` for a `/255` tensor, `IMAGENET` for
350
+ torchvision-style normalisation, `CLIP` for CLIP-style models. A BGR tensor (OpenCV, caffe) also
351
+ needs `rgb_channels=(2, 1, 0)`; the pairs stay in R, G, B order -- they apply after `rgb_channels`
352
+ picks the channels.
337
353
  `rgb_channels`: the three indices along the channel axis (`channel_dim`) that are R, G and B --
338
354
  `(2, 1, 0)` for BGR, `(3, 2, 1)` for a multispectral true colour, `(0, 0, 0)` for grayscale.
339
355
  `masks`: for a dedicated foundation input (an encoder not passed to the model) in an
340
356
  element-instance project, the function returned by a second `@tensorleap_instances_masks_encoder`
341
357
  that draws each instance in this image's coordinates. Pass the decorated function, not its name.
342
358
  """
343
- range: Union[ImageRange, Tuple[float, float]]
359
+ rgb_range: Union[ImageRange, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]
344
360
  rgb_channels: Tuple[int, int, int] = (0, 1, 2)
345
361
  masks: Optional[Callable[..., Any]] = None
346
362
 
347
363
  def __post_init__(self) -> None:
348
- if not isinstance(self.range, ImageRange):
349
- self.range = self._validated_range(self.range)
364
+ if not isinstance(self.rgb_range, ImageRange):
365
+ self.rgb_range = self._validated_range(self.rgb_range)
350
366
  self.rgb_channels = self._validated_rgb_channels(self.rgb_channels)
351
367
  if self.masks is not None and not isinstance(self.masks_encoder_name, str):
352
368
  raise TypeError(
@@ -355,16 +371,52 @@ class FoundationInput:
355
371
  f'not the encoder name. Got {self.masks!r}.')
356
372
 
357
373
  @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)
374
+ def _is_number(value: Any) -> bool:
375
+ return isinstance(value, (int, float, np.integer, np.floating)) and not isinstance(value, bool)
376
+
377
+ @staticmethod
378
+ def _is_sequence(value: Any) -> bool:
379
+ return isinstance(value, (tuple, list, np.ndarray)) and not isinstance(value, (str, bytes))
380
+
381
+ @classmethod
382
+ def _validated_range(cls, value: Any) -> Union[Tuple[float, float], ChannelBounds]:
383
+ """One (min, max) pair -> `(min, max)`; three pairs -> `((min, max),) * 3` in R, G, B order, as
384
+ floats. `((min, max),)` is one pair too. Anything else -- 0, 2 or 4+ pairs, a pair that is not two
385
+ finite numbers, min >= max -- raises, naming what is wrong."""
386
+ def fail(error: Type[Exception], reason: str) -> Exception:
387
+ return error(f'FoundationInput() validation failed: rgb_range should be an ImageRange preset, one '
388
+ f'(min, max) pair, or three (min, max) pairs in R, G, B order, each with min < max. '
389
+ f'Got {value!r}: {reason}.')
390
+
391
+ if not cls._is_sequence(value):
392
+ kind = "a preset's name, not the preset" if isinstance(value, str) else type(value).__name__
393
+ raise fail(TypeError, f'not a pair or a sequence of pairs ({kind})')
394
+ items = list(value)
395
+ if items and not any(cls._is_sequence(item) for item in items):
396
+ if len(items) == 2:
397
+ return cls._validated_pair(value, None, fail)
398
+ raise fail(TypeError, f'{len(items)} number(s) -- a pair is two numbers')
399
+ if not all(cls._is_sequence(item) for item in items):
400
+ raise fail(TypeError, 'a mix of numbers and pairs')
401
+ if len(items) not in (1, 3):
402
+ raise fail(ValueError, f'{len(items)} pairs -- give exactly one (the same for R, G, B) or three')
403
+ pairs = [cls._validated_pair(item, index if len(items) == 3 else None, fail)
404
+ for index, item in enumerate(items)]
405
+ if len(pairs) == 1:
406
+ return pairs[0]
407
+ return pairs[0], pairs[1], pairs[2]
408
+
409
+ @classmethod
410
+ def _validated_pair(cls, pair: Any, index: Optional[int],
411
+ fail: Callable[[Type[Exception], str], Exception]) -> Tuple[float, float]:
412
+ which = 'the pair' if index is None else f'pair {index} ({"RGB"[index]})'
413
+ if not cls._is_sequence(pair) or len(pair) != 2 or not all(cls._is_number(v) for v in pair):
414
+ raise fail(TypeError, f'{which} {pair!r} is not two numbers')
415
+ low, high = float(pair[0]), float(pair[1])
416
+ if not (np.isfinite(low) and np.isfinite(high)):
417
+ raise fail(ValueError, f'{which} {pair!r} is not finite')
418
+ if not low < high:
419
+ raise fail(ValueError, f'{which} {pair!r} has min >= max')
368
420
  return low, high
369
421
 
370
422
  @staticmethod
@@ -379,12 +431,24 @@ class FoundationInput:
379
431
  raise ValueError(message)
380
432
  return int(value[0]), int(value[1]), int(value[2])
381
433
 
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
434
+ def bounds(self) -> ChannelBounds:
435
+ """The declared (min, max) per channel, in R, G, B order, as floats: a preset's pairs, one pair
436
+ repeated for all three channels, or the three pairs given."""
437
+ value: Any = self.rgb_range.value if isinstance(self.rgb_range, ImageRange) else self.rgb_range
438
+ if len(value) == 2 and all(self._is_number(v) for v in value):
439
+ pair = (float(value[0]), float(value[1]))
440
+ return pair, pair, pair
441
+ r, g, b = ((float(low), float(high)) for low, high in value)
442
+ return r, g, b
443
+
444
+ def describe_range(self) -> str:
445
+ """The declaration as written, for messages: the preset's name or the pair(s)."""
446
+ if isinstance(self.rgb_range, ImageRange):
447
+ return self.rgb_range.name
448
+ value: Any = self.rgb_range
449
+ if len(value) == 2 and all(self._is_number(v) for v in value):
450
+ return f'({value[0]:g}, {value[1]:g})'
451
+ return '(' + ', '.join(f'({low:g}, {high:g})' for low, high in value) + ')'
388
452
 
389
453
  @property
390
454
  def masks_encoder_name(self) -> Optional[str]:
@@ -395,6 +459,50 @@ class FoundationInput:
395
459
  return name if isinstance(name, str) else None
396
460
 
397
461
 
462
+ # frame_dim, like channel_dim, counts axes of the BATCHED tensor (the platform adds the batch axis at
463
+ # 0 to the one sample an encoder returns). It is the frame axis of a 4-D (multi-frame) sample, so it is
464
+ # only valid when the sample has this rank.
465
+ FRAME_SAMPLE_RANK = 4
466
+
467
+
468
+ def sample_axis(batched_dim: int, sample_rank: int) -> int:
469
+ """A batched-tensor axis (channel_dim, frame_dim) as an axis of the unbatched sample: 1 -> 0,
470
+ 2 -> 1, ..., -1 -> the last axis, -2 -> the one before."""
471
+ return batched_dim - 1 if batched_dim > 0 else sample_rank + batched_dim
472
+
473
+
474
+ def sample_axis_note(batched_dim: int, sample_rank: int) -> str:
475
+ """' (axis k of the sample)' for a batched-tensor axis that falls inside a sample of `sample_rank`
476
+ axes, '' when it falls outside -- for messages that print channel_dim/frame_dim (batched) next to
477
+ a sample shape (unbatched)."""
478
+ axis = sample_axis(int(batched_dim), sample_rank)
479
+ return f" (axis {axis} of the sample)" if 0 <= axis < sample_rank else ""
480
+
481
+
482
+ def frame_dim_error(frame_dim: Any, channel_dim: Optional[int],
483
+ sample_shape: Optional[Sequence[int]] = None) -> Optional[str]:
484
+ """Why `frame_dim` is invalid for an input, None when it is unset or fine. Without a sample shape
485
+ only what holds for every 4-D sample is checked (decoration time); with one, the rank too."""
486
+ if frame_dim is None:
487
+ return None
488
+ if isinstance(frame_dim, bool) or not isinstance(frame_dim, (int, np.integer)):
489
+ return f"frame_dim should be an int (the frame axis in the batched tensor) or None, got {frame_dim!r}"
490
+ if sample_shape is not None and len(sample_shape) != FRAME_SAMPLE_RANK:
491
+ return (f"frame_dim={frame_dim}{sample_axis_note(int(frame_dim), len(sample_shape))} is set but the sample "
492
+ f"has {len(sample_shape)} axes (shape "
493
+ f"{list(sample_shape)}); frame_dim is the frame axis of a 4-D (multi-frame) sample -- remove "
494
+ f"frame_dim, or return a 4-D sample")
495
+ if frame_dim == 0 or not -FRAME_SAMPLE_RANK <= frame_dim <= FRAME_SAMPLE_RANK:
496
+ return (f"frame_dim={frame_dim} is not a frame axis of a 4-D sample: it counts axes of the batched "
497
+ f"tensor (batch = axis 0), so use 1..4 or -4..-1")
498
+ channel = sample_axis(channel_dim if channel_dim is not None else -1, FRAME_SAMPLE_RANK)
499
+ if sample_axis(int(frame_dim), FRAME_SAMPLE_RANK) == channel:
500
+ return (f"frame_dim={frame_dim} and channel_dim={channel_dim} are the same axis of a 4-D sample "
501
+ f"(axis {channel} of the sample); "
502
+ f"the frame axis must differ from the channel axis")
503
+ return None
504
+
505
+
398
506
  @dataclass
399
507
  class InputHandler(DatasetBaseHandler):
400
508
  shape: Optional[List[int]] = None
@@ -403,6 +511,9 @@ class InputHandler(DatasetBaseHandler):
403
511
  dtype: Optional[str] = None
404
512
  # Set when the encoder carries foundation=FoundationInput(...): the image a foundation encoder reads.
405
513
  foundation: Optional[FoundationInput] = None
514
+ # The frame axis of a 4-D (multi-frame) sample, in the batched tensor like channel_dim; None when
515
+ # not declared. See frame_dim_error for the rules.
516
+ frame_dim: Optional[int] = None
406
517
 
407
518
  @dataclass
408
519
  class ElementInstanceMasksHandler:
@@ -413,6 +524,8 @@ class ElementInstanceMasksHandler:
413
524
  class FalsePositiveInstancesHandler:
414
525
  name: str
415
526
  function: Callable[..., Any]
527
+ operating_threshold: Optional[float] = None
528
+ candidate_floor: Optional[float] = None
416
529
 
417
530
  @dataclass
418
531
  class GroundTruthHandler(DatasetBaseHandler):
@@ -1,4 +1,5 @@
1
1
  from enum import Enum, IntEnum
2
+ from typing import Tuple
2
3
 
3
4
 
4
5
  class MetricEnum(Enum):
@@ -81,15 +82,28 @@ class CustomLatentSpaceComputedAt(Enum):
81
82
  MODEL = 'model'
82
83
 
83
84
 
85
+ def _normalised_channel_bounds(mean: Tuple[float, float, float],
86
+ std: Tuple[float, float, float]) -> Tuple[Tuple[float, float], ...]:
87
+ """((min, max) per channel, R, G, B) of `(x / 255 - mean) / std` for x in [0, 255]."""
88
+ return tuple(((0.0 - m) / s, (1.0 - m) / s) for m, s in zip(mean, std))
89
+
90
+
84
91
  class ImageRange(Enum):
85
- """Theoretical (min, max) of an image tensor under a photometric convention.
92
+ """Theoretical per-channel (min, max) of an image tensor under a photometric convention.
86
93
 
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.
94
+ Used by `FoundationInput.rgb_range` to describe a model's input encoder so the platform can invert
95
+ it back to uint8 pixels for a foundation encoder. Each value is three (min, max) pairs in R, G, B
96
+ order: the conventions' bounds, not the observed min/max of any sample. BYTE, UNIT and SIGNED
97
+ are the same for every channel; IMAGENET and CLIP normalise each channel with its own mean and
98
+ std, so each channel has its own bounds.
90
99
  """
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
100
+ BYTE = ((0.0, 255.0),) * 3 # raw 8-bit pixels
101
+ UNIT = ((0.0, 1.0),) * 3 # x / 255
102
+ SIGNED = ((-1.0, 1.0),) * 3 # x / 127.5 - 1
103
+ # (x / 255 - mean) / std with the ImageNet mean/std:
104
+ # ((-2.118, 2.249), (-2.036, 2.429), (-1.804, 2.640))
105
+ IMAGENET = _normalised_channel_bounds((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
106
+ # (x / 255 - mean) / std with the CLIP mean/std:
107
+ # ((-1.792, 1.930), (-1.752, 2.075), (-1.480, 2.146))
108
+ CLIP = _normalised_channel_bounds((0.48145466, 0.4578275, 0.40821073),
109
+ (0.26862954, 0.26130258, 0.27577711))
@@ -22,10 +22,14 @@ class DatasetBaseSectionInstance:
22
22
  @dataclass
23
23
  class FoundationInputInstance:
24
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
25
+ convention (`rgb_range`, `rgb_channels`), the probe's dtype, whether the integration test wires the
26
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]
27
+ encoder frame) and, for a dedicated input in an instance project, its own masks encoder.
28
+
29
+ `rgb_range` is always three [min, max] pairs, R, G, B order (`[[r_min, r_max], [g_min, g_max],
30
+ [b_min, b_max]]`), also when the integration declared one pair. In the 1.0.219 release
31
+ candidate it was one flat [min, max] under `range`."""
32
+ rgb_range: List[List[float]]
29
33
  rgb_channels: List[int]
30
34
  dtype: str
31
35
  wired_to_model: bool
@@ -39,6 +43,11 @@ class DatasetInputInstance(DatasetBaseSectionInstance):
39
43
  # Set for the one input that carries foundation=FoundationInput(...). Default None so an old
40
44
  # engine payload deserialises unchanged (same pattern as DatasetSetup.has_element_instances).
41
45
  foundation: Optional[FoundationInputInstance] = None
46
+ # The frame axis of a 4-D (multi-frame) sample, in the batched tensor (1..4, always non-negative):
47
+ # the declared frame_dim resolved against the sample's rank, or, for the foundation input with
48
+ # frame_dim unset, the inferred one (the axis that is neither the channel axis nor one of the two
49
+ # spatial axes). None for every other input.
50
+ frame_dim: Optional[int] = None
42
51
 
43
52
 
44
53
  @dataclass
@@ -187,10 +196,17 @@ class LeapAnalysisConfiguration:
187
196
  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
197
 
189
198
 
199
+ @dataclass
200
+ class FalsePositiveConfidenceConfig:
201
+ operating_threshold: float
202
+ candidate_floor: float
203
+
204
+
190
205
  @dataclass
191
206
  class EngineFileContract:
192
207
  node_connections: Optional[List[NodeConnection]] = None
193
208
  leap_analysis_configuration: Optional[LeapAnalysisConfiguration] = None
209
+ false_positive_confidence: Optional[FalsePositiveConfidenceConfig] = None
194
210
 
195
211
 
196
212
  @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.")
@@ -9,7 +9,7 @@ from typing import Callable, List, Optional, Dict, Any, Type, Union, get_args, c
9
9
  import numpy as np
10
10
  import numpy.typing as npt
11
11
 
12
- from code_loader.contract.datasetclasses import SectionCallableInterface, InputHandler, \
12
+ from code_loader.contract.datasetclasses import SectionCallableInterface, InputHandler, frame_dim_error, \
13
13
  GroundTruthHandler, MetadataHandler, DatasetIntegrationSetup, VisualizerHandler, PreprocessResponse, \
14
14
  PreprocessHandler, VisualizerCallableInterface, CustomLossHandler, CustomCallableInterface, PredictionTypeHandler, \
15
15
  MetadataSectionCallableInterface, UnlabeledDataPreprocessHandler, CustomLayerHandler, MetricHandler, \
@@ -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, \
@@ -302,7 +304,7 @@ class LeapBinder:
302
304
  )
303
305
 
304
306
  def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1,
305
- foundation: Optional[FoundationInput] = None) -> None:
307
+ foundation: Optional[FoundationInput] = None, frame_dim: Optional[int] = None) -> None:
306
308
  """
307
309
  Set the input handler function.
308
310
 
@@ -311,6 +313,7 @@ class LeapBinder:
311
313
  name (str): The name of the input section.
312
314
  channel_dim (int): The dimension of the channels axis
313
315
  foundation (Optional[FoundationInput]): marks this input as the image a foundation encoder reads
316
+ frame_dim (Optional[int]): the frame axis of a 4-D (multi-frame) sample, in the batched tensor
314
317
 
315
318
  Example:
316
319
  def input_encoder(subset: PreprocessResponse, index: int) -> np.ndarray:
@@ -323,7 +326,8 @@ class LeapBinder:
323
326
  leap_binder.set_input(input_encoder, name='input_encoder', channel_dim=-1)
324
327
  """
325
328
  function = to_numpy_return_wrapper(function)
326
- self.setup_container.inputs.append(InputHandler(name, function, channel_dim=channel_dim, foundation=foundation))
329
+ self.setup_container.inputs.append(InputHandler(name, function, channel_dim=channel_dim, foundation=foundation,
330
+ frame_dim=frame_dim))
327
331
 
328
332
  self._encoder_names.append(name)
329
333
 
@@ -343,15 +347,25 @@ class LeapBinder:
343
347
  self.setup_container.instance_masks.append(ElementInstanceMasksHandler(name, function))
344
348
 
345
349
 
346
- def set_false_positive_instances(self, function: Callable[..., Any], name: str) -> None:
350
+ def set_false_positive_instances(self, function: Callable[..., Any], name: str,
351
+ operating_threshold: Optional[float] = None,
352
+ candidate_floor: Optional[float] = None) -> None:
347
353
  """
348
354
  Set the false-positive instances handler. It receives (sample_id, preprocess, predictions)
349
- and returns a list of ElementInstance, one per false-positive prediction.
355
+ and returns a list of ElementInstance: one per false-positive prediction, or, when
356
+ `operating_threshold` is declared, one per candidate down to `candidate_floor` (matched ones
357
+ included), each with a score. The full contract is in the docstring of
358
+ `tensorleap_false_positive_instances_encoder`.
350
359
  """
351
360
  if self.setup_container.false_positive_instances is not None:
352
361
  raise Exception("only one tensorleap_false_positive_instances_encoder can be defined")
362
+ validate_confidence_args(operating_threshold, candidate_floor)
353
363
  function = to_numpy_return_fp_masks_wrapper(function)
354
- self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(name, function)
364
+ self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(
365
+ name, function,
366
+ float(operating_threshold) if operating_threshold is not None else None,
367
+ float(candidate_floor) if candidate_floor is not None else None)
368
+ declare_confidence_metadata_types(self.setup_container)
355
369
 
356
370
  def set_false_positive_empty_gt(self, function: Callable[..., Any], gt_name: str) -> None:
357
371
  """
@@ -419,6 +433,16 @@ class LeapBinder:
419
433
  if preprocess_result is not None:
420
434
  self._check_false_positive_custom_latent_space_shapes(preprocess_result)
421
435
 
436
+ def native_instance_masks(self) -> Optional[ElementInstanceMasksHandler]:
437
+ """The native masks encoder: the first registered `@tensorleap_instances_masks_encoder` that is
438
+ not a foundation input's `masks=` encoder. It defines the element instances; a foundation masks
439
+ encoder only redraws them in the dedicated image's coordinates, and may be registered first, so
440
+ never read `instance_masks[0]`. None when no native one is registered."""
441
+ foundation_masks = {inp.foundation.masks_encoder_name for inp in self.setup_container.inputs
442
+ if inp.foundation is not None and inp.foundation.masks_encoder_name is not None}
443
+ return next((handler for handler in self.setup_container.instance_masks
444
+ if handler.name not in foundation_masks), None)
445
+
422
446
  def _check_false_positive_custom_latent_space_shapes(
423
447
  self, preprocess_result: Dict[DataStateEnum, PreprocessResponse]) -> None:
424
448
  """Call each FP latent-space hook with a real GT ElementInstance and compare its shape with
@@ -436,7 +460,10 @@ class LeapBinder:
436
460
  if instance_ids), None)
437
461
  if sample_id is None:
438
462
  return
439
- gt_instance = self.setup_container.instance_masks[0].function(sample_id, training, 0)
463
+ native = self.native_instance_masks()
464
+ if native is None:
465
+ return
466
+ gt_instance = native.function(sample_id, training, 0)
440
467
  if gt_instance is None:
441
468
  return
442
469
  for name, fp_hook in fp_hooks.items():
@@ -1076,6 +1103,11 @@ class LeapBinder:
1076
1103
  dataset_base_handler.shape = result_shape
1077
1104
  if isinstance(dataset_base_handler, InputHandler) and isinstance(raw_result, np.ndarray):
1078
1105
  dataset_base_handler.dtype = str(raw_result.dtype)
1106
+ if isinstance(dataset_base_handler, InputHandler):
1107
+ error = frame_dim_error(dataset_base_handler.frame_dim, dataset_base_handler.channel_dim,
1108
+ result_shape)
1109
+ if error is not None:
1110
+ raise Exception(f"Input `{dataset_base_handler.name}`: {error}.")
1079
1111
  _warn_if_group_spans_multiple_files(test_result)
1080
1112
  return test_result
1081
1113