code-loader 1.0.220__tar.gz → 1.0.222__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.
- {code_loader-1.0.220 → code_loader-1.0.222}/PKG-INFO +1 -1
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/datasetclasses.py +185 -2
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/enums.py +28 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/responsedataclasses.py +25 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/inner_leap_binder/leapbinder.py +29 -5
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/inner_leap_binder/leapbinder_decorators.py +92 -6
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/leaploader.py +465 -6
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/mixpanel_tracker.py +24 -4
- {code_loader-1.0.220 → code_loader-1.0.222}/pyproject.toml +1 -1
- {code_loader-1.0.220 → code_loader-1.0.222}/LICENSE +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/README.md +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/__init__.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/__init__.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/exceptions.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/mapping.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/sim_config.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/contract/visualizer_classes.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/default_losses.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/default_metrics.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/__init__.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/api.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/cli_config_utils.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/client.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/epoch.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/experiment.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/experiment_context.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/types.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/utils.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/workingspace_config_utils.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/inner_leap_binder/__init__.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/inner_leap_binder/fp_confidence_contract.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/leaploaderbase.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/plot_functions/__init__.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/plot_functions/plot_functions.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/plot_functions/visualize.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/utils.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/visualizers/__init__.py +0 -0
- {code_loader-1.0.220 → code_loader-1.0.222}/code_loader/visualizers/default_visualizers.py +0 -0
|
@@ -1,17 +1,22 @@
|
|
|
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
|
|
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"
|
|
18
|
+
# (min, max) per channel, in R, G, B order.
|
|
19
|
+
ChannelBounds = Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
|
|
15
20
|
|
|
16
21
|
# Hard cap on a custom latent space's per-sample width, applied AFTER any reduction. The
|
|
17
22
|
# soft threshold only warns. MAX_CUSTOM_LATENT_SPACES mirrors the engine's
|
|
@@ -327,10 +332,188 @@ class DatasetBaseHandler:
|
|
|
327
332
|
function: SectionCallableInterface
|
|
328
333
|
|
|
329
334
|
|
|
335
|
+
@dataclass
|
|
336
|
+
class FoundationInput:
|
|
337
|
+
"""Marks an input encoder as the image a foundation encoder (SigLIP 2, OWLv2) reads.
|
|
338
|
+
|
|
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.
|
|
353
|
+
`rgb_channels`: the three indices along the channel axis (`channel_dim`) that are R, G and B --
|
|
354
|
+
`(2, 1, 0)` for BGR, `(3, 2, 1)` for a multispectral true colour, `(0, 0, 0)` for grayscale.
|
|
355
|
+
`masks`: for a dedicated foundation input (an encoder not passed to the model) in an
|
|
356
|
+
element-instance project, the function returned by a second `@tensorleap_instances_masks_encoder`
|
|
357
|
+
that draws each instance in this image's coordinates. Pass the decorated function, not its name.
|
|
358
|
+
"""
|
|
359
|
+
rgb_range: Union[ImageRange, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]
|
|
360
|
+
rgb_channels: Tuple[int, int, int] = (0, 1, 2)
|
|
361
|
+
masks: Optional[Callable[..., Any]] = None
|
|
362
|
+
|
|
363
|
+
def __post_init__(self) -> None:
|
|
364
|
+
if not isinstance(self.rgb_range, ImageRange):
|
|
365
|
+
self.rgb_range = self._validated_range(self.rgb_range)
|
|
366
|
+
self.rgb_channels = self._validated_rgb_channels(self.rgb_channels)
|
|
367
|
+
if self.masks is not None and not isinstance(self.masks_encoder_name, str):
|
|
368
|
+
raise TypeError(
|
|
369
|
+
f'FoundationInput() validation failed: masks should be the function returned by a '
|
|
370
|
+
f'@tensorleap_instances_masks_encoder decorator -- pass the decorated function object, '
|
|
371
|
+
f'not the encoder name. Got {self.masks!r}.')
|
|
372
|
+
|
|
373
|
+
@staticmethod
|
|
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')
|
|
420
|
+
return low, high
|
|
421
|
+
|
|
422
|
+
@staticmethod
|
|
423
|
+
def _validated_rgb_channels(value: Any) -> Tuple[int, int, int]:
|
|
424
|
+
message = (f'FoundationInput() validation failed: rgb_channels should be three non-negative channel '
|
|
425
|
+
f'indices (R, G, B) along the channel axis. Got {value!r}.')
|
|
426
|
+
if isinstance(value, (str, bytes)) or not isinstance(value, (tuple, list)) or len(value) != 3:
|
|
427
|
+
raise TypeError(message)
|
|
428
|
+
if not all(isinstance(v, (int, np.integer)) and not isinstance(v, bool) for v in value):
|
|
429
|
+
raise TypeError(message)
|
|
430
|
+
if any(int(v) < 0 for v in value):
|
|
431
|
+
raise ValueError(message)
|
|
432
|
+
return int(value[0]), int(value[1]), int(value[2])
|
|
433
|
+
|
|
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) + ')'
|
|
452
|
+
|
|
453
|
+
@property
|
|
454
|
+
def masks_encoder_name(self) -> Optional[str]:
|
|
455
|
+
"""The registered name of the masks encoder behind `masks`, None when no `masks=` was given."""
|
|
456
|
+
if self.masks is None:
|
|
457
|
+
return None
|
|
458
|
+
name = getattr(self.masks, masks_encoder_name_attribute, None)
|
|
459
|
+
return name if isinstance(name, str) else None
|
|
460
|
+
|
|
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
|
+
|
|
330
506
|
@dataclass
|
|
331
507
|
class InputHandler(DatasetBaseHandler):
|
|
332
508
|
shape: Optional[List[int]] = None
|
|
333
509
|
channel_dim: Optional[int] = -1
|
|
510
|
+
# The probe result's dtype name ('float32', 'uint8'), recorded by check_handler next to shape.
|
|
511
|
+
dtype: Optional[str] = None
|
|
512
|
+
# Set when the encoder carries foundation=FoundationInput(...): the image a foundation encoder reads.
|
|
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
|
|
334
517
|
|
|
335
518
|
@dataclass
|
|
336
519
|
class ElementInstanceMasksHandler:
|
|
@@ -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):
|
|
@@ -79,3 +80,30 @@ class LatentSpaceReduction(Enum):
|
|
|
79
80
|
class CustomLatentSpaceComputedAt(Enum):
|
|
80
81
|
DATASET = 'dataset'
|
|
81
82
|
MODEL = 'model'
|
|
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
|
+
|
|
91
|
+
class ImageRange(Enum):
|
|
92
|
+
"""Theoretical per-channel (min, max) of an image tensor under a photometric convention.
|
|
93
|
+
|
|
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.
|
|
99
|
+
"""
|
|
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))
|
|
@@ -19,10 +19,35 @@ 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 (`rgb_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
|
+
|
|
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]]
|
|
33
|
+
rgb_channels: List[int]
|
|
34
|
+
dtype: str
|
|
35
|
+
wired_to_model: bool
|
|
36
|
+
masks_encoder: Optional[str] = None
|
|
37
|
+
|
|
38
|
+
|
|
22
39
|
@dataclass
|
|
23
40
|
class DatasetInputInstance(DatasetBaseSectionInstance):
|
|
24
41
|
shape: List[int]
|
|
25
42
|
channel_dim: Optional[int] = -1
|
|
43
|
+
# Set for the one input that carries foundation=FoundationInput(...). Default None so an old
|
|
44
|
+
# engine payload deserialises unchanged (same pattern as DatasetSetup.has_element_instances).
|
|
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
|
|
26
51
|
|
|
27
52
|
|
|
28
53
|
@dataclass
|
|
@@ -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, \
|
|
@@ -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
|
|
@@ -303,7 +303,8 @@ class LeapBinder:
|
|
|
303
303
|
SimulationHandler(name=name, function=function, sim_config=sim_config)
|
|
304
304
|
)
|
|
305
305
|
|
|
306
|
-
def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1
|
|
306
|
+
def set_input(self, function: SectionCallableInterface, name: str, channel_dim: int = -1,
|
|
307
|
+
foundation: Optional[FoundationInput] = None, frame_dim: Optional[int] = None) -> None:
|
|
307
308
|
"""
|
|
308
309
|
Set the input handler function.
|
|
309
310
|
|
|
@@ -311,6 +312,8 @@ class LeapBinder:
|
|
|
311
312
|
function (SectionCallableInterface): The input handler function.
|
|
312
313
|
name (str): The name of the input section.
|
|
313
314
|
channel_dim (int): The dimension of the channels axis
|
|
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
|
|
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
|
|
|
@@ -429,6 +433,16 @@ class LeapBinder:
|
|
|
429
433
|
if preprocess_result is not None:
|
|
430
434
|
self._check_false_positive_custom_latent_space_shapes(preprocess_result)
|
|
431
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
|
+
|
|
432
446
|
def _check_false_positive_custom_latent_space_shapes(
|
|
433
447
|
self, preprocess_result: Dict[DataStateEnum, PreprocessResponse]) -> None:
|
|
434
448
|
"""Call each FP latent-space hook with a real GT ElementInstance and compare its shape with
|
|
@@ -446,7 +460,10 @@ class LeapBinder:
|
|
|
446
460
|
if instance_ids), None)
|
|
447
461
|
if sample_id is None:
|
|
448
462
|
return
|
|
449
|
-
|
|
463
|
+
native = self.native_instance_masks()
|
|
464
|
+
if native is None:
|
|
465
|
+
return
|
|
466
|
+
gt_instance = native.function(sample_id, training, 0)
|
|
450
467
|
if gt_instance is None:
|
|
451
468
|
return
|
|
452
469
|
for name, fp_hook in fp_hooks.items():
|
|
@@ -1084,6 +1101,13 @@ class LeapBinder:
|
|
|
1084
1101
|
# setting shape in setup for all encoders
|
|
1085
1102
|
if isinstance(dataset_base_handler, (InputHandler, GroundTruthHandler)):
|
|
1086
1103
|
dataset_base_handler.shape = result_shape
|
|
1104
|
+
if isinstance(dataset_base_handler, InputHandler) and isinstance(raw_result, np.ndarray):
|
|
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}.")
|
|
1087
1111
|
_warn_if_group_spans_multiple_files(test_result)
|
|
1088
1112
|
return test_result
|
|
1089
1113
|
|
{code_loader-1.0.220 → code_loader-1.0.222}/code_loader/inner_leap_binder/leapbinder_decorators.py
RENAMED
|
@@ -27,9 +27,9 @@ from code_loader.contract.datasetclasses import CustomCallableInterfaceMultiArgs
|
|
|
27
27
|
CustomMultipleReturnCallableInterfaceMultiArgs, ConfusionMatrixCallableInterfaceMultiArgs, CustomCallableInterface, \
|
|
28
28
|
VisualizerCallableInterface, MetadataSectionCallableInterface, PreprocessResponse, SectionCallableInterface, \
|
|
29
29
|
ConfusionMatrixElement, SamplePreprocessResponse, PredictionTypeHandler, InstanceCallableInterface, ElementInstance, \
|
|
30
|
-
is_sample_id_of_type, \
|
|
30
|
+
is_sample_id_of_type, frame_dim_error, \
|
|
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
|
|
@@ -3465,6 +3465,15 @@ def tensorleap_unlabeled_preprocess():
|
|
|
3465
3465
|
|
|
3466
3466
|
|
|
3467
3467
|
def tensorleap_instances_masks_encoder(name: str):
|
|
3468
|
+
"""Register an element-instance masks encoder: ``(sample_id, preprocess, instance_id) ->
|
|
3469
|
+
ElementInstance``, or None when the sample has no such instance.
|
|
3470
|
+
|
|
3471
|
+
The encoder bound through ``tensorleap_element_instance_preprocess`` defines the project's
|
|
3472
|
+
instances. A second masks encoder, named by ``FoundationInput(masks=...)`` on a dedicated
|
|
3473
|
+
foundation input, draws the same instances in that image's coordinates. It returns either an
|
|
3474
|
+
``ElementInstance`` or just the H x W mask array: only the mask is used from it (the instance's
|
|
3475
|
+
name and metadata come from the first encoder).
|
|
3476
|
+
"""
|
|
3468
3477
|
def decorating_function(user_function: InstanceCallableInterface):
|
|
3469
3478
|
def _validate_input_args(sample_id: str, preprocess_response: PreprocessResponse, instance_id: int):
|
|
3470
3479
|
assert isinstance(sample_id, str), \
|
|
@@ -3486,6 +3495,12 @@ def tensorleap_instances_masks_encoder(name: str):
|
|
|
3486
3495
|
(f'tensorleap_instances_masks_encoder validation failed: '
|
|
3487
3496
|
f'Unsupported return type. Should be a ElementInstance or None. Got {type(result)}.')
|
|
3488
3497
|
|
|
3498
|
+
def _is_foundation_masks_encoder():
|
|
3499
|
+
# Decided at call time: the FoundationInput naming this encoder is created after it.
|
|
3500
|
+
return any(input_handler.foundation is not None
|
|
3501
|
+
and input_handler.foundation.masks_encoder_name == name
|
|
3502
|
+
for input_handler in leap_binder.setup_container.inputs)
|
|
3503
|
+
|
|
3489
3504
|
def inner_without_validate(sample_id, preprocess_response, instance_id):
|
|
3490
3505
|
global _called_from_inside_tl_decorator
|
|
3491
3506
|
_called_from_inside_tl_decorator += 1
|
|
@@ -3495,6 +3510,11 @@ def tensorleap_instances_masks_encoder(name: str):
|
|
|
3495
3510
|
finally:
|
|
3496
3511
|
_called_from_inside_tl_decorator -= 1
|
|
3497
3512
|
|
|
3513
|
+
if isinstance(result, np.ndarray) and _is_foundation_masks_encoder():
|
|
3514
|
+
# Only the geometry is taken from a foundation masks encoder (instance identity and
|
|
3515
|
+
# metadata come from the native one), so a bare H x W mask is the explicit form of
|
|
3516
|
+
# that contract; wrap it, named after the encoder, with no metadata.
|
|
3517
|
+
result = ElementInstance(name=name, mask=result)
|
|
3498
3518
|
return result
|
|
3499
3519
|
|
|
3500
3520
|
leap_binder.set_instance_masks(inner_without_validate, name)
|
|
@@ -3510,6 +3530,9 @@ def tensorleap_instances_masks_encoder(name: str):
|
|
|
3510
3530
|
_validate_result(result)
|
|
3511
3531
|
return result
|
|
3512
3532
|
|
|
3533
|
+
# FoundationInput(masks=inner) verifies it was handed a registered masks encoder through this
|
|
3534
|
+
# attribute and resolves it to the registered name (function object, not name: a typo fails at import).
|
|
3535
|
+
setattr(inner, masks_encoder_name_attribute, name)
|
|
3513
3536
|
return inner
|
|
3514
3537
|
|
|
3515
3538
|
return decorating_function
|
|
@@ -3749,12 +3772,53 @@ def tensorleap_instances_length_encoder(name: str):
|
|
|
3749
3772
|
return decorating_function
|
|
3750
3773
|
|
|
3751
3774
|
|
|
3752
|
-
def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=None
|
|
3775
|
+
def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=None,
|
|
3776
|
+
foundation: Optional[FoundationInput] = None, frame_dim: Optional[int] = None):
|
|
3777
|
+
"""Register an input encoder: ``(sample_id, preprocess) -> np.ndarray`` (float32).
|
|
3778
|
+
|
|
3779
|
+
``channel_dim`` is the channel axis in the batched tensor (1 for NCHW, -1 for NHWC).
|
|
3780
|
+
``frame_dim`` is the frame axis of a 4-D (multi-frame) sample, counted in the batched tensor like
|
|
3781
|
+
``channel_dim`` (1 for ``[T, H, W, C]``, 2 for ``[C, T, H, W]``); default None. Set it only on a
|
|
3782
|
+
4-D sample (any other rank is an error), on an axis other than ``channel_dim``.
|
|
3783
|
+
``foundation=FoundationInput(rgb_range=..., rgb_channels=..., masks=...)`` adds latent spaces
|
|
3784
|
+
computed by pretrained foundation encoders, independent of your model: an image latent space
|
|
3785
|
+
(SigLIP 2) on every project, and an instance latent space (OWLv2) on projects with element
|
|
3786
|
+
instances. The platform clusters them alongside your model's latent spaces when it looks for
|
|
3787
|
+
failure groups, so it can find groups your model's own embeddings don't separate. The flag marks
|
|
3788
|
+
this input as the image those encoders read -- exactly one input per project. ``rgb_range`` is the tensor's convention, theoretical, not the samples' min/max: an
|
|
3789
|
+
``ImageRange`` preset (IMAGENET and CLIP are per-channel), one ``(min, max)`` pair for all three
|
|
3790
|
+
channels, or three ``(min, max)`` pairs in R, G, B order for a custom per-channel normalisation.
|
|
3791
|
+
``rgb_channels`` is the R, G, B indices on the channel axis. Put it on the image the integration
|
|
3792
|
+
test passes to the model and the platform converts that tensor back to pixel values; put it on a separate
|
|
3793
|
+
encoder that is never passed to the model and it is a dedicated image for the encoders alone --
|
|
3794
|
+
float32, or uint8 with ``rgb_range=ImageRange.BYTE``, at any fixed size (the same for every sample),
|
|
3795
|
+
with ``masks=`` naming a second ``@tensorleap_instances_masks_encoder`` in its coordinates for
|
|
3796
|
+
instance projects. The sample is a 3-D image; a 2-D H x W sample is read as grayscale, and on a
|
|
3797
|
+
4-D sample the foundation encoders read the middle frame on ``frame_dim``. ``check_dataset``
|
|
3798
|
+
verifies the declaration (one flag, wired vs dedicated, the declared range on a few samples, one
|
|
3799
|
+
sample shape, the masks). Example -- the image the model reads, float32 [3, H, W] in [0, 1]::
|
|
3800
|
+
|
|
3801
|
+
from code_loader.contract.datasetclasses import FoundationInput
|
|
3802
|
+
from code_loader.contract.enums import ImageRange
|
|
3803
|
+
|
|
3804
|
+
@tensorleap_input_encoder('image', channel_dim=1,
|
|
3805
|
+
foundation=FoundationInput(rgb_range=ImageRange.UNIT))
|
|
3806
|
+
def input_encoder(sample_id, preprocess):
|
|
3807
|
+
...
|
|
3808
|
+
|
|
3809
|
+
See https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code/input-encoder
|
|
3810
|
+
"""
|
|
3753
3811
|
def decorating_function(user_function: SectionCallableInterface):
|
|
3754
3812
|
for input_handler in leap_binder.setup_container.inputs:
|
|
3755
3813
|
if input_handler.name == name:
|
|
3756
3814
|
raise Exception(f'Input with name {name} already exists. '
|
|
3757
3815
|
f'Please choose another')
|
|
3816
|
+
# check_dataset checks this too, but the local integration test never runs it: raise here
|
|
3817
|
+
# so a second foundation input fails before push, not at it.
|
|
3818
|
+
if foundation is not None and input_handler.foundation is not None:
|
|
3819
|
+
raise Exception(f"Input `{name}` carries foundation=, but `{input_handler.name}` already does -- "
|
|
3820
|
+
f"exactly one input per project is the foundation image; keep foundation= on "
|
|
3821
|
+
f"one of them.")
|
|
3758
3822
|
nonlocal channel_dim
|
|
3759
3823
|
|
|
3760
3824
|
channel_dim_was_provided = channel_dim is not _UNSET
|
|
@@ -3778,6 +3842,24 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
|
|
|
3778
3842
|
f"channel axis in the batched tensor (batch = axis 0), so 0 is invalid. Use 1 "
|
|
3779
3843
|
f"for channel-first (NCHW) and -1 for channel-last (NHWC).")
|
|
3780
3844
|
|
|
3845
|
+
frame_dim_problem = frame_dim_error(frame_dim, channel_dim)
|
|
3846
|
+
if frame_dim_problem is not None:
|
|
3847
|
+
raise Exception(f"Invalid frame_dim for input '{name}': {frame_dim_problem}.")
|
|
3848
|
+
|
|
3849
|
+
if foundation is not None and not isinstance(foundation, FoundationInput):
|
|
3850
|
+
raise Exception(
|
|
3851
|
+
f"Invalid foundation for input '{name}': expected FoundationInput(rgb_range=..., "
|
|
3852
|
+
f"rgb_channels=..., masks=...) or None, got {type(foundation).__name__}.")
|
|
3853
|
+
|
|
3854
|
+
# Inputs feed float32 graph placeholders, so float32 is the rule. An encoder that carries
|
|
3855
|
+
# foundation= may instead return uint8 pixels: a dedicated foundation input never reaches
|
|
3856
|
+
# the graph (only the platform's foundation encoder reads it), and uint8 is a quarter of the
|
|
3857
|
+
# payload. Whether THIS flagged encoder is wired to the model (and so must still be float32)
|
|
3858
|
+
# is only known after the integration test's mapping pass; check_dataset applies that rule,
|
|
3859
|
+
# the decorator only admits the dtype.
|
|
3860
|
+
allowed_dtypes = (np.float32, np.uint8) if foundation is not None else (np.float32,)
|
|
3861
|
+
allowed_dtypes_text = ' or '.join(np.dtype(d).name for d in allowed_dtypes)
|
|
3862
|
+
|
|
3781
3863
|
def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
|
|
3782
3864
|
_validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
|
|
3783
3865
|
|
|
@@ -3785,11 +3867,14 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
|
|
|
3785
3867
|
assert isinstance(result, np.ndarray), \
|
|
3786
3868
|
(f'{user_function.__name__}() validation failed: '
|
|
3787
3869
|
f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
|
|
3788
|
-
assert result.dtype
|
|
3870
|
+
assert result.dtype in allowed_dtypes, \
|
|
3789
3871
|
(f'{user_function.__name__}() validation failed: '
|
|
3790
|
-
f'The return type should be a numpy array of type
|
|
3872
|
+
f'The return type should be a numpy array of type {allowed_dtypes_text}. Got {result.dtype}.')
|
|
3791
3873
|
assert channel_dim - 1 <= len(result.shape), (f'{user_function.__name__}() validation failed: '
|
|
3792
3874
|
f'The channel_dim ({channel_dim}) should be <= to the rank of the resulting input rank ({len(result.shape)}).')
|
|
3875
|
+
frame_dim_problem = frame_dim_error(frame_dim, channel_dim, result.shape)
|
|
3876
|
+
assert frame_dim_problem is None, (f'{user_function.__name__}() validation failed: '
|
|
3877
|
+
f'{frame_dim_problem}.')
|
|
3793
3878
|
|
|
3794
3879
|
def _validate_result(result, grouped=False, group_size=None):
|
|
3795
3880
|
if not grouped:
|
|
@@ -3809,7 +3894,8 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
|
|
|
3809
3894
|
|
|
3810
3895
|
return result
|
|
3811
3896
|
|
|
3812
|
-
leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim
|
|
3897
|
+
leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim, foundation=foundation,
|
|
3898
|
+
frame_dim=frame_dim)
|
|
3813
3899
|
|
|
3814
3900
|
def inner(*args, **kwargs):
|
|
3815
3901
|
if not _call_from_tl_platform:
|
|
@@ -9,25 +9,25 @@ from contextlib import redirect_stdout
|
|
|
9
9
|
from functools import lru_cache
|
|
10
10
|
from pathlib import Path
|
|
11
11
|
from types import TracebackType
|
|
12
|
-
from typing import Dict, List, Iterable, Set, FrozenSet, Union, Any, Type, Optional, Callable, Tuple
|
|
12
|
+
from typing import Dict, List, Iterable, Set, FrozenSet, Union, Any, Type, Optional, Callable, Tuple, Sequence
|
|
13
13
|
|
|
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, \
|
|
17
|
+
from code_loader.contract.datasetclasses import DatasetSample, DatasetBaseHandler, GroundTruthHandler, InputHandler, \
|
|
18
18
|
PreprocessResponse, VisualizerHandler, LeapData, \
|
|
19
19
|
PredictionTypeHandler, MetadataHandler, CustomLayerHandler, MetricHandler, VisualizerHandlerData, MetricHandlerData, \
|
|
20
20
|
MetricCallableReturnType, CustomLossHandlerData, CustomLossHandler, RawInputsForHeatmap, SamplePreprocessResponse, \
|
|
21
21
|
ElementInstance, custom_latent_space_attribute, DatasetIntegrationSetup, InstanceMetricHandler, _simulation_context, \
|
|
22
|
-
FalsePositiveInstancesHandler
|
|
22
|
+
FalsePositiveInstancesHandler, FRAME_SAMPLE_RANK, sample_axis
|
|
23
23
|
from code_loader.contract.enums import DataStateEnum, TestingSectionEnum, DataStateType, DatasetMetadataType, \
|
|
24
|
-
CustomLatentSpaceComputedAt
|
|
24
|
+
CustomLatentSpaceComputedAt, ImageRange
|
|
25
25
|
from code_loader.contract.mapping import NodeMappingType
|
|
26
26
|
from code_loader.contract.exceptions import DatasetScriptException
|
|
27
27
|
from code_loader.contract.responsedataclasses import DatasetIntegParseResult, DatasetTestResultPayload, \
|
|
28
28
|
DatasetPreprocess, DatasetSetup, DatasetInputInstance, DatasetOutputInstance, DatasetMetadataInstance, \
|
|
29
29
|
VisualizerInstance, PredictionTypeInstance, ModelSetup, CustomLayerInstance, MetricInstance, CustomLossInstance, \
|
|
30
|
-
EngineFileContract, SimulationInstance, FalsePositiveConfidenceConfig
|
|
30
|
+
EngineFileContract, SimulationInstance, FalsePositiveConfidenceConfig, FoundationInputInstance
|
|
31
31
|
from code_loader.contract.sim_config import FloatBounds, IntBounds, CategoricalBounds, sample_sim_params
|
|
32
32
|
from code_loader.inner_leap_binder import global_leap_binder
|
|
33
33
|
from code_loader.inner_leap_binder.leapbinder import mapping_runtime_mode_env_var_mame
|
|
@@ -85,6 +85,10 @@ def _serialize_sim_bounds(bounds) -> dict:
|
|
|
85
85
|
|
|
86
86
|
|
|
87
87
|
|
|
88
|
+
# (frame axis, channel axis, frame axis inferred) of a foundation input's sample, as axes of the
|
|
89
|
+
# unbatched sample; None for an axis the sample does not have (see LeapLoader._foundation_layout).
|
|
90
|
+
FoundationLayout = Tuple[Optional[int], Optional[int], bool]
|
|
91
|
+
|
|
88
92
|
class LeapLoader(LeapLoaderBase):
|
|
89
93
|
# Opt-in ceiling (env var) on samples materialized per get_samples call — the engine sets it to
|
|
90
94
|
# turn a mistaken whole-group ask into a clear error instead of a silent worker OOM. Unset => no
|
|
@@ -431,6 +435,9 @@ class LeapLoader(LeapLoaderBase):
|
|
|
431
435
|
test_payloads.append(model_ls_test_payload)
|
|
432
436
|
handlers_test_payloads = self._check_handlers()
|
|
433
437
|
test_payloads.extend(handlers_test_payloads)
|
|
438
|
+
foundation_test_payload = self._check_foundation_input()
|
|
439
|
+
if foundation_test_payload is not None:
|
|
440
|
+
test_payloads.append(foundation_test_payload)
|
|
434
441
|
simulation_test_payloads = self._check_simulations()
|
|
435
442
|
test_payloads.extend(simulation_test_payloads)
|
|
436
443
|
autoregressive_test_payload = self._check_autoregressive_step()
|
|
@@ -609,6 +616,414 @@ class LeapLoader(LeapLoaderBase):
|
|
|
609
616
|
result_payloads.extend(test_result)
|
|
610
617
|
return result_payloads
|
|
611
618
|
|
|
619
|
+
def _check_foundation_input(self) -> Optional[DatasetTestResultPayload]:
|
|
620
|
+
"""Push-time checks for the input that carries foundation=FoundationInput(...). One payload,
|
|
621
|
+
'foundation_input', after the handlers were probed (it needs their shapes and dtypes); None
|
|
622
|
+
(no payload) when no input is flagged.
|
|
623
|
+
|
|
624
|
+
Structural rules (architecture §11): exactly one flagged input; a flagged input the
|
|
625
|
+
integration test passes to the model is the native image (its tensor is inverted, float32,
|
|
626
|
+
native masks), one it does not pass is a dedicated image for the encoder alone (uint8
|
|
627
|
+
allowed, its own masks=); rgb_channels must index the channel axis; autoregressive
|
|
628
|
+
integrations and simulations are refused in this version. The sample is a 3-D image, a 2-D
|
|
629
|
+
H x W (grayscale, repeated to R, G, B) or a 4-D multi-frame sample (the middle frame on
|
|
630
|
+
frame_dim is read); the range probe and the masks rules run on that image.
|
|
631
|
+
"""
|
|
632
|
+
setup = global_leap_binder.setup_container
|
|
633
|
+
flagged = [inp for inp in setup.inputs if inp.foundation is not None]
|
|
634
|
+
if not flagged:
|
|
635
|
+
return None
|
|
636
|
+
test_result = DatasetTestResultPayload('foundation_input')
|
|
637
|
+
errors: List[str] = []
|
|
638
|
+
warnings: List[str] = []
|
|
639
|
+
try:
|
|
640
|
+
if len(flagged) > 1:
|
|
641
|
+
names = ', '.join(f'`{inp.name}`' for inp in flagged)
|
|
642
|
+
errors.append(
|
|
643
|
+
f"More than one input encoder carries foundation=: {names}. Exactly one input per "
|
|
644
|
+
f"project is the foundation image -- keep foundation= on one of them.")
|
|
645
|
+
inp = flagged[0]
|
|
646
|
+
wired = self._is_input_wired_to_model(inp.name)
|
|
647
|
+
test_result.display['input'] = (
|
|
648
|
+
f"foundation input `{inp.name}`: the model's own input -- its tensor is converted back to pixels "
|
|
649
|
+
f"for the foundation encoders" if wired else
|
|
650
|
+
f"foundation input `{inp.name}`: dedicated -- not passed to the model, read only by the foundation "
|
|
651
|
+
f"encoders")
|
|
652
|
+
layout = self._check_foundation_input_structure(inp, wired, errors, warnings, test_result.display)
|
|
653
|
+
if layout is not None:
|
|
654
|
+
self._probe_foundation_range(inp, layout, errors, warnings, test_result.display)
|
|
655
|
+
self._check_foundation_masks(inp, layout, wired, errors, warnings)
|
|
656
|
+
except Exception as e:
|
|
657
|
+
line_number, file_name, stacktrace = get_root_exception_file_and_line_number()
|
|
658
|
+
errors.append(f"{repr(e)} in file {file_name}, line_number: {line_number}\nStacktrace:\n{stacktrace}")
|
|
659
|
+
if warnings:
|
|
660
|
+
test_result.display[TestingSectionEnum.Warnings.name] = "\n".join(warnings)
|
|
661
|
+
if errors:
|
|
662
|
+
test_result.is_passed = False
|
|
663
|
+
test_result.display[TestingSectionEnum.Errors.name] = "\n".join(errors)
|
|
664
|
+
return test_result
|
|
665
|
+
|
|
666
|
+
def _check_foundation_input_structure(self, inp: InputHandler, wired: bool, errors: List[str],
|
|
667
|
+
warnings: List[str], display: Dict[str, str]) -> Optional[FoundationLayout]:
|
|
668
|
+
"""The structural rules; returns the sample's layout (see _foundation_layout) when the image can
|
|
669
|
+
be read from it, None when an error already says why not."""
|
|
670
|
+
setup = global_leap_binder.setup_container
|
|
671
|
+
foundation = inp.foundation
|
|
672
|
+
assert foundation is not None
|
|
673
|
+
if setup.autoregressive_step is not None:
|
|
674
|
+
errors.append(
|
|
675
|
+
f"foundation= on input `{inp.name}` is not supported in an autoregressive integration "
|
|
676
|
+
f"(tensorleap_autoregressive_step) in this version. Remove foundation=.")
|
|
677
|
+
if setup.simulations:
|
|
678
|
+
sim_names = ', '.join(f'`{sim.name}`' for sim in setup.simulations)
|
|
679
|
+
errors.append(
|
|
680
|
+
f"foundation= on input `{inp.name}` is not supported together with simulations "
|
|
681
|
+
f"({sim_names}) in this version. Remove foundation= or the simulations.")
|
|
682
|
+
|
|
683
|
+
if wired and foundation.masks is not None:
|
|
684
|
+
errors.append(
|
|
685
|
+
f"Input `{inp.name}` is passed to the model in the integration test, so it is the native "
|
|
686
|
+
f"image and the native instance masks apply to it; masks= is only for a dedicated foundation "
|
|
687
|
+
f"input that is not passed to the model. Remove masks={foundation.masks_encoder_name}.")
|
|
688
|
+
if wired and inp.dtype != 'float32':
|
|
689
|
+
errors.append(
|
|
690
|
+
f"Input `{inp.name}` is passed to the model in the integration test, so it must return "
|
|
691
|
+
f"float32 (got {inp.dtype}); uint8 is allowed only for a dedicated foundation input that "
|
|
692
|
+
f"is not passed to the model.")
|
|
693
|
+
|
|
694
|
+
if inp.shape is None:
|
|
695
|
+
errors.append(
|
|
696
|
+
f"Input `{inp.name}`: shape unknown (its handler check failed), rgb_channels not verified.")
|
|
697
|
+
return None
|
|
698
|
+
rank = len(inp.shape)
|
|
699
|
+
if rank not in (2, 3, FRAME_SAMPLE_RANK):
|
|
700
|
+
errors.append(
|
|
701
|
+
f"Input `{inp.name}`: sample shape {inp.shape} has {rank} axes; a foundation input is a 3-D image "
|
|
702
|
+
f"(H, W and the channel axis on channel_dim), a 2-D H x W grayscale image, or a 4-D multi-frame "
|
|
703
|
+
f"sample (frames on frame_dim).")
|
|
704
|
+
return None
|
|
705
|
+
if rank == 2:
|
|
706
|
+
grayscale = (f"2-D sample {inp.shape} read as a grayscale H x W image, repeated to R, G, B "
|
|
707
|
+
f"(rgb_channels is not used)")
|
|
708
|
+
display['input'] = f"{display['input']}; {grayscale}" if 'input' in display else \
|
|
709
|
+
f"foundation input `{inp.name}`: {grayscale}"
|
|
710
|
+
return None, None, False
|
|
711
|
+
channel_dim = inp.channel_dim if inp.channel_dim is not None else -1
|
|
712
|
+
layout = self._foundation_layout(inp, inp.shape)
|
|
713
|
+
if layout is None:
|
|
714
|
+
errors.append(
|
|
715
|
+
f"Input `{inp.name}`: sample shape {inp.shape} has no channel axis at channel_dim={channel_dim} "
|
|
716
|
+
f"(counted in the batched tensor), so rgb_channels={list(foundation.rgb_channels)} cannot be "
|
|
717
|
+
f"applied.")
|
|
718
|
+
return None
|
|
719
|
+
frame_axis, channel_axis, inferred = layout
|
|
720
|
+
if frame_axis is not None:
|
|
721
|
+
frames = inp.shape[frame_axis]
|
|
722
|
+
message = (f"Input `{inp.name}`: 4-D sample {inp.shape}; the foundation encoders read its middle frame, "
|
|
723
|
+
f"index {frames // 2} of {frames} on frame_dim={frame_axis + 1} "
|
|
724
|
+
f"(axis {frame_axis} of the sample)")
|
|
725
|
+
if inferred:
|
|
726
|
+
message += (f" -- frame_dim is not set, so the frame axis was inferred as frame_dim={frame_axis + 1} "
|
|
727
|
+
f"(axis {frame_axis} of the sample), the axis that is neither channel_dim={channel_dim} "
|
|
728
|
+
f"(axis {channel_axis} of the sample) nor one of the last two (spatial) "
|
|
729
|
+
f"axes; set frame_dim= on the encoder to state it")
|
|
730
|
+
warnings.append(message + ".")
|
|
731
|
+
assert channel_axis is not None
|
|
732
|
+
channels = inp.shape[channel_axis]
|
|
733
|
+
out_of_range = [index for index in foundation.rgb_channels if index >= channels]
|
|
734
|
+
if out_of_range:
|
|
735
|
+
errors.append(
|
|
736
|
+
f"Input `{inp.name}`: rgb_channels={list(foundation.rgb_channels)} index "
|
|
737
|
+
f"{out_of_range} out of range -- the input has {channels} channels on channel_dim={channel_dim} "
|
|
738
|
+
f"(axis {channel_axis} of the sample; sample shape {inp.shape}).")
|
|
739
|
+
return None
|
|
740
|
+
return layout
|
|
741
|
+
|
|
742
|
+
@staticmethod
|
|
743
|
+
def _foundation_layout(inp: InputHandler, shape: Sequence[int]) -> Optional[FoundationLayout]:
|
|
744
|
+
"""(frame axis, channel axis, frame axis inferred) of a foundation sample, as axes of the unbatched
|
|
745
|
+
sample: 2-D -> (None, None, False), grayscale H x W; 3-D -> (None, channel, False); 4-D -> (frame,
|
|
746
|
+
channel, inferred), the frame axis from frame_dim or, unset, the axis that is neither the channel
|
|
747
|
+
axis nor one of the last two (spatial) ones. None for another rank or an axis outside the sample."""
|
|
748
|
+
rank = len(shape)
|
|
749
|
+
if rank == 2:
|
|
750
|
+
return None, None, False
|
|
751
|
+
if rank not in (3, FRAME_SAMPLE_RANK):
|
|
752
|
+
return None
|
|
753
|
+
channel = sample_axis(inp.channel_dim if inp.channel_dim is not None else -1, rank)
|
|
754
|
+
if not 0 <= channel < rank:
|
|
755
|
+
return None
|
|
756
|
+
if rank == 3:
|
|
757
|
+
return None, channel, False
|
|
758
|
+
if inp.frame_dim is not None:
|
|
759
|
+
frame = sample_axis(inp.frame_dim, rank)
|
|
760
|
+
if not 0 <= frame < rank or frame == channel:
|
|
761
|
+
return None
|
|
762
|
+
return frame, channel, False
|
|
763
|
+
return next(axis for axis in range(rank) if axis != channel), channel, True
|
|
764
|
+
|
|
765
|
+
@staticmethod
|
|
766
|
+
def _foundation_rgb(rgb_channels: Tuple[int, int, int], layout: FoundationLayout, row: Any) -> np.ndarray:
|
|
767
|
+
"""The image the foundation encoders read from one sample, H x W x 3 (R, G, B last) as float64:
|
|
768
|
+
the middle frame of a 4-D sample, the rgb_channels on the channel axis, a 2-D sample repeated."""
|
|
769
|
+
frame_axis, channel_axis, _ = layout
|
|
770
|
+
image = np.asarray(row)
|
|
771
|
+
if frame_axis is not None:
|
|
772
|
+
image = np.take(image, image.shape[frame_axis] // 2, axis=frame_axis)
|
|
773
|
+
if channel_axis is not None and channel_axis > frame_axis:
|
|
774
|
+
channel_axis -= 1
|
|
775
|
+
if channel_axis is None:
|
|
776
|
+
return np.repeat(image[..., np.newaxis], 3, axis=-1).astype(np.float64)
|
|
777
|
+
return np.take(np.moveaxis(image, channel_axis, -1), list(rgb_channels), axis=-1).astype(np.float64)
|
|
778
|
+
|
|
779
|
+
@staticmethod
|
|
780
|
+
def _foundation_image_hw(layout: FoundationLayout, shape: Sequence[int]) -> Tuple[int, int]:
|
|
781
|
+
"""H x W of a foundation sample: the two axes left once the frame and channel axes are removed."""
|
|
782
|
+
frame_axis, channel_axis, _ = layout
|
|
783
|
+
spatial = [int(n) for axis, n in enumerate(shape) if axis not in (frame_axis, channel_axis)]
|
|
784
|
+
return spatial[-2], spatial[-1]
|
|
785
|
+
|
|
786
|
+
# The declared-range probe: how many samples per state are inverted, and what counts as a
|
|
787
|
+
# convention mismatch. Inverted pixels of a correctly declared tensor sit in [0, 255] up to
|
|
788
|
+
# rounding (each channel inverted with its own bounds); a byte or signed tensor declared
|
|
789
|
+
# UNIT lands far outside, a constant tensor spans nothing.
|
|
790
|
+
# Two ways a declaration can be wrong, judged differently:
|
|
791
|
+
# - the tensor is WIDER than declared: inverted values fall outside [-2, 257]. A correct
|
|
792
|
+
# declaration cannot do that, so it is an error.
|
|
793
|
+
# - the tensor is NARROWER than declared: the inverted values span few levels. Real images can
|
|
794
|
+
# be narrow too (dark, foggy, low contrast), so this is only a suspicion -- a warning -- except
|
|
795
|
+
# at a span no real image reaches (a [0, 1] tensor declared BYTE spans about 1 level), which
|
|
796
|
+
# is an error.
|
|
797
|
+
# Probe samples are drawn at random (fixed seed, so a run is reproducible) rather than taken from
|
|
798
|
+
# the head of the list, which is often one class or scene (e.g. dark aggressor samples).
|
|
799
|
+
_FOUNDATION_PROBE_SAMPLES = 5
|
|
800
|
+
_FOUNDATION_PROBE_SEED = 0
|
|
801
|
+
_FOUNDATION_INVERTED_MIN = -2.0
|
|
802
|
+
_FOUNDATION_INVERTED_MAX = 257.0
|
|
803
|
+
_FOUNDATION_ERROR_SPAN = 4.0 # at or below: error
|
|
804
|
+
_FOUNDATION_WARN_SPAN = 32.0 # below: warning
|
|
805
|
+
_FOUNDATION_BGR_GAP = 20.0
|
|
806
|
+
|
|
807
|
+
def _foundation_probe_rows(self, inp: InputHandler, preprocess_response: PreprocessResponse) -> List[Any]:
|
|
808
|
+
"""Up to _FOUNDATION_PROBE_SAMPLES per-sample arrays from the handler, drawn at random with a
|
|
809
|
+
fixed seed. Flat: original sample ids (instance ids, which an element-instance preprocess
|
|
810
|
+
appends after the originals, are skipped). Grouped: up to that many groups, each loaded once,
|
|
811
|
+
one random row from each; with fewer groups, the rest are extra random rows of the loaded ones."""
|
|
812
|
+
assert preprocess_response.sample_ids is not None
|
|
813
|
+
rng = np.random.default_rng(self._FOUNDATION_PROBE_SEED)
|
|
814
|
+
wanted = self._FOUNDATION_PROBE_SAMPLES
|
|
815
|
+
if preprocess_response.is_grouped:
|
|
816
|
+
groups = preprocess_response.sample_ids
|
|
817
|
+
picked_groups = sorted(rng.choice(len(groups), size=min(wanted, len(groups)), replace=False))
|
|
818
|
+
loaded = [list(inp.function(groups[g], preprocess_response)) for g in picked_groups]
|
|
819
|
+
chosen = [(g, int(rng.integers(len(rows)))) for g, rows in enumerate(loaded) if rows]
|
|
820
|
+
rest = [(g, r) for g, rows in enumerate(loaded) for r in range(len(rows)) if (g, r) not in chosen]
|
|
821
|
+
extra = min(wanted - len(chosen), len(rest))
|
|
822
|
+
if extra > 0:
|
|
823
|
+
chosen += [rest[k] for k in rng.choice(len(rest), size=extra, replace=False)]
|
|
824
|
+
return [loaded[g][r] for g, r in sorted(chosen)]
|
|
825
|
+
instance_ids = preprocess_response.instance_to_sample_ids_mappings or {}
|
|
826
|
+
originals = [sample_id for sample_id in preprocess_response.sample_ids if sample_id not in instance_ids]
|
|
827
|
+
picked = rng.choice(len(originals), size=min(wanted, len(originals)), replace=False)
|
|
828
|
+
return [inp.function(originals[i], preprocess_response) for i in sorted(picked)]
|
|
829
|
+
|
|
830
|
+
def _probe_foundation_range(self, inp: InputHandler, layout: FoundationLayout, errors: List[str],
|
|
831
|
+
warnings: List[str], display: Dict[str, str]) -> None:
|
|
832
|
+
"""Invert the declared range on a few samples per state: `uint8 = a_c*x + b_c` with one
|
|
833
|
+
(a, b) per channel from bounds(). A correct declaration lands in [-2, 257] and spans more than a narrow
|
|
834
|
+
band; a byte or signed tensor declared UNIT does not (the silent catastrophe: embeddings look
|
|
835
|
+
normal, zero-shot is at chance). The observed inverted range is shown for every state.
|
|
836
|
+
Channel order is not detectable from statistics; the one hint, red far below blue on the
|
|
837
|
+
probe, is a warning. A uint8 input must declare BYTE (the platform reads its pixels as they
|
|
838
|
+
are), and the probed samples must share one shape (the platform batches them)."""
|
|
839
|
+
foundation = inp.foundation
|
|
840
|
+
assert foundation is not None
|
|
841
|
+
channel_bounds = foundation.bounds()
|
|
842
|
+
scale = np.array([255.0 / (high - low) for low, high in channel_bounds])
|
|
843
|
+
offset = np.array([-low for low, _ in channel_bounds]) * scale
|
|
844
|
+
declared = foundation.describe_range()
|
|
845
|
+
if inp.dtype == 'uint8' and channel_bounds != ImageRange.BYTE.value:
|
|
846
|
+
errors.append(
|
|
847
|
+
f"Input `{inp.name}`: a uint8 foundation input must declare rgb_range=ImageRange.BYTE (got "
|
|
848
|
+
f"rgb_range={declared}). uint8 holds 0\u2013255 pixels, which the platform reads as they are; "
|
|
849
|
+
f"UNIT, SIGNED, IMAGENET, CLIP or a custom range never fit it.")
|
|
850
|
+
return
|
|
851
|
+
shapes = {tuple(inp.shape)} if inp.shape is not None else set()
|
|
852
|
+
|
|
853
|
+
red_means: List[float] = []
|
|
854
|
+
blue_means: List[float] = []
|
|
855
|
+
probe_dtype: Optional[str] = None
|
|
856
|
+
for state in sorted(self._preprocess_result(), key=lambda s: s.value):
|
|
857
|
+
rows = self._foundation_probe_rows(inp, self._preprocess_result()[state])
|
|
858
|
+
if not rows:
|
|
859
|
+
continue
|
|
860
|
+
rows = [np.asarray(row) for row in rows]
|
|
861
|
+
shapes.update(tuple(row.shape) for row in rows)
|
|
862
|
+
if len(shapes) > 1:
|
|
863
|
+
listed = ', '.join(str(list(shape)) for shape in sorted(shapes))
|
|
864
|
+
errors.append(
|
|
865
|
+
f"Input `{inp.name}`: the probed samples differ in shape ({listed}). A foundation input "
|
|
866
|
+
f"must have one fixed size, the same for every sample: the platform batches its samples, "
|
|
867
|
+
f"which needs equal shapes. Resize, crop or pad to one size.")
|
|
868
|
+
return
|
|
869
|
+
observed_min, observed_max = float('inf'), float('-inf')
|
|
870
|
+
for row in rows:
|
|
871
|
+
probe_dtype = probe_dtype or str(row.dtype)
|
|
872
|
+
# H x W x 3 (R, G, B last), each channel inverted with its own (a, b).
|
|
873
|
+
inverted = self._foundation_rgb(foundation.rgb_channels, layout, row) * scale + offset
|
|
874
|
+
observed_min = min(observed_min, float(inverted.min()))
|
|
875
|
+
observed_max = max(observed_max, float(inverted.max()))
|
|
876
|
+
red_means.append(float(inverted[..., 0].mean()))
|
|
877
|
+
blue_means.append(float(inverted[..., 2].mean()))
|
|
878
|
+
outside = observed_min < self._FOUNDATION_INVERTED_MIN or observed_max > self._FOUNDATION_INVERTED_MAX
|
|
879
|
+
span = observed_max - observed_min
|
|
880
|
+
collapsed = span <= self._FOUNDATION_ERROR_SPAN
|
|
881
|
+
narrow = not collapsed and span < self._FOUNDATION_WARN_SPAN
|
|
882
|
+
mark = '\u2717' if (outside or collapsed) else ('!' if narrow else '\u2713')
|
|
883
|
+
display[state.name] = (f"foundation input `{inp.name}`: pixel values "
|
|
884
|
+
f"{observed_min:.1f}\u2013{observed_max:.1f} {mark}")
|
|
885
|
+
observed = (f"Input `{inp.name}` ({state.name}): rgb_range={declared} converts "
|
|
886
|
+
f"{len(rows)} random samples back to pixel values "
|
|
887
|
+
f"{observed_min:.1f}\u2013{observed_max:.1f}")
|
|
888
|
+
if outside:
|
|
889
|
+
errors.append(
|
|
890
|
+
f"{observed}, outside 0\u2013255: the tensor's values are wider than the declared range, "
|
|
891
|
+
f"which a correct declaration cannot produce (e.g. byte values declared UNIT, or [-1, 1] "
|
|
892
|
+
f"values declared UNIT). rgb_range is the convention's theoretical [min, max], not the "
|
|
893
|
+
f"samples' min/max. Fix rgb_range=.")
|
|
894
|
+
elif collapsed:
|
|
895
|
+
errors.append(
|
|
896
|
+
f"{observed}, a span of {span:.1f} of 256 levels: the tensor is nearly constant under the "
|
|
897
|
+
f"declared range, narrower than any real image (e.g. [0, 1] values declared BYTE -- "
|
|
898
|
+
f"declare UNIT). Fix rgb_range=.")
|
|
899
|
+
elif narrow:
|
|
900
|
+
warnings.append(
|
|
901
|
+
f"{observed}, a span of {span:.1f} of 256 levels: narrower than typical images. Fine for "
|
|
902
|
+
f"dark or low-contrast data; otherwise the declared range may be wider than the tensor "
|
|
903
|
+
f"(e.g. a /255 tensor declared BYTE -> UNIT, or [0, 1] values declared SIGNED -> UNIT).")
|
|
904
|
+
if probe_dtype is not None:
|
|
905
|
+
inp.dtype = probe_dtype
|
|
906
|
+
if red_means and np.mean(red_means) + self._FOUNDATION_BGR_GAP < np.mean(blue_means):
|
|
907
|
+
warnings.append(
|
|
908
|
+
f"Input `{inp.name}`: the selected red channel averages {np.mean(red_means):.0f} against "
|
|
909
|
+
f"{np.mean(blue_means):.0f} for blue on the sampled images -- natural images rarely do; if the "
|
|
910
|
+
f"tensor is BGR, set rgb_channels=(2, 1, 0) (channel order cannot be verified from statistics).")
|
|
911
|
+
|
|
912
|
+
def _foundation_instance_probes(self, inp: InputHandler, layout: FoundationLayout
|
|
913
|
+
) -> List[Tuple[str, PreprocessResponse, Any, Tuple[int, int]]]:
|
|
914
|
+
"""Up to _FOUNDATION_PROBE_SAMPLES (state, response, original sample id, image H x W), drawn at
|
|
915
|
+
random (same fixed seed as the range probe) among the samples with element instances across all
|
|
916
|
+
states, in state then sample order."""
|
|
917
|
+
candidates: List[Tuple[DataStateEnum, PreprocessResponse, Any]] = []
|
|
918
|
+
for state in sorted(self._preprocess_result(), key=lambda s: s.value):
|
|
919
|
+
preprocess_response = self._preprocess_result()[state]
|
|
920
|
+
mappings = preprocess_response.sample_ids_to_instance_mappings or {}
|
|
921
|
+
candidates.extend((state, preprocess_response, sample_id)
|
|
922
|
+
for sample_id, instance_ids in mappings.items() if instance_ids)
|
|
923
|
+
rng = np.random.default_rng(self._FOUNDATION_PROBE_SEED)
|
|
924
|
+
picked = rng.choice(len(candidates), size=min(self._FOUNDATION_PROBE_SAMPLES, len(candidates)),
|
|
925
|
+
replace=False)
|
|
926
|
+
probes: List[Tuple[str, PreprocessResponse, Any, Tuple[int, int]]] = []
|
|
927
|
+
for index in sorted(picked):
|
|
928
|
+
state, preprocess_response, sample_id = candidates[index]
|
|
929
|
+
row = np.asarray(inp.function(sample_id, preprocess_response))
|
|
930
|
+
probes.append((state.name, preprocess_response, sample_id, self._foundation_image_hw(layout, row.shape)))
|
|
931
|
+
return probes
|
|
932
|
+
|
|
933
|
+
def _check_foundation_masks(self, inp: InputHandler, layout: FoundationLayout, wired: bool, errors: List[str],
|
|
934
|
+
warnings: List[str]) -> None:
|
|
935
|
+
"""Masks rules for a dedicated foundation input (one not passed to the model); a wired input
|
|
936
|
+
uses the native masks and `masks=` on it is the structural error above. The project kind
|
|
937
|
+
decides: no element instances -> `masks=` is ignored (warning); an instance project without
|
|
938
|
+
`masks=` uses the native encoder's masks, nearest-scaled when their H x W differs from the
|
|
939
|
+
foundation image's (warning); with `masks=` the named encoder is probed against the native
|
|
940
|
+
one on instance 0 of a few samples. "Native" is the registered masks encoder that is not the
|
|
941
|
+
foundation one -- the engine takes instance identity and metadata from it and only the
|
|
942
|
+
geometry from the foundation one."""
|
|
943
|
+
foundation = inp.foundation
|
|
944
|
+
assert foundation is not None
|
|
945
|
+
if wired:
|
|
946
|
+
return
|
|
947
|
+
masks_name = foundation.masks_encoder_name
|
|
948
|
+
if not self._has_element_instances():
|
|
949
|
+
if masks_name is not None:
|
|
950
|
+
warnings.append(
|
|
951
|
+
f"Input `{inp.name}`: masks={masks_name} is ignored -- this project has no element instances "
|
|
952
|
+
f"(no tensorleap_element_instance_preprocess), so there are no instances to mask.")
|
|
953
|
+
return
|
|
954
|
+
handlers = global_leap_binder.setup_container.instance_masks
|
|
955
|
+
native = global_leap_binder.native_instance_masks()
|
|
956
|
+
if native is None:
|
|
957
|
+
errors.append(
|
|
958
|
+
f"Input `{inp.name}`: masks={masks_name} is the only registered masks encoder; an instance "
|
|
959
|
+
f"project needs the native one too (the encoder bound through "
|
|
960
|
+
f"tensorleap_element_instance_preprocess), which defines the instances.")
|
|
961
|
+
return
|
|
962
|
+
probes = self._foundation_instance_probes(inp, layout)
|
|
963
|
+
if masks_name is None:
|
|
964
|
+
warnings.append(
|
|
965
|
+
f"Input `{inp.name}` names no masks=; the masks of encoder `{native.name}` are used for it, "
|
|
966
|
+
f"assuming this image shows the same view as the model's input (same crop and padding).")
|
|
967
|
+
for state_name, preprocess_response, sample_id, (image_h, image_w) in probes:
|
|
968
|
+
native_instance = native.function(sample_id, preprocess_response, 0)
|
|
969
|
+
if native_instance is None:
|
|
970
|
+
continue
|
|
971
|
+
mask_shape = tuple(np.asarray(native_instance.mask).shape)
|
|
972
|
+
if mask_shape != (image_h, image_w):
|
|
973
|
+
warnings.append(
|
|
974
|
+
f"Input `{inp.name}` ({state_name}): the native mask is {'x'.join(map(str, mask_shape))} "
|
|
975
|
+
f"and the foundation image {image_h}x{image_w}; the mask will be resized to the "
|
|
976
|
+
f"foundation image's size, assuming it shows the same view. If the view differs (crop, letterbox, "
|
|
977
|
+
f"tile), add masks= with a masks encoder drawing in the foundation image's coordinates.")
|
|
978
|
+
break
|
|
979
|
+
return
|
|
980
|
+
foundation_handler = next((handler for handler in handlers if handler.name == masks_name), None)
|
|
981
|
+
if foundation_handler is None:
|
|
982
|
+
errors.append(
|
|
983
|
+
f"Input `{inp.name}`: masks={masks_name} is not a registered masks encoder; pass the function "
|
|
984
|
+
f"returned by a @tensorleap_instances_masks_encoder decorator.")
|
|
985
|
+
return
|
|
986
|
+
for state_name, preprocess_response, sample_id, (image_h, image_w) in probes:
|
|
987
|
+
native_instance = native.function(sample_id, preprocess_response, 0)
|
|
988
|
+
foundation_instance = foundation_handler.function(sample_id, preprocess_response, 0)
|
|
989
|
+
where = f"instance 0 of sample {sample_id!r} ({state_name})"
|
|
990
|
+
if foundation_instance is None:
|
|
991
|
+
if native_instance is not None:
|
|
992
|
+
errors.append(
|
|
993
|
+
f"Input `{inp.name}`: masks encoder `{masks_name}` returned None for {where} where the "
|
|
994
|
+
f"native encoder `{native.name}` returned a mask -- every instance the native encoder "
|
|
995
|
+
f"creates needs a foundation mask, otherwise that instance gets no foundation embedding.")
|
|
996
|
+
continue
|
|
997
|
+
if isinstance(foundation_instance, np.ndarray):
|
|
998
|
+
foundation_instance = ElementInstance(name=masks_name, mask=foundation_instance)
|
|
999
|
+
mask = np.asarray(foundation_instance.mask)
|
|
1000
|
+
if mask.ndim != 2:
|
|
1001
|
+
errors.append(
|
|
1002
|
+
f"Input `{inp.name}`: masks encoder `{masks_name}` returned a mask of shape "
|
|
1003
|
+
f"{tuple(mask.shape)} for {where}; a foundation mask is a 2-D H x W array.")
|
|
1004
|
+
continue
|
|
1005
|
+
mask_h, mask_w = int(mask.shape[0]), int(mask.shape[1])
|
|
1006
|
+
if (mask_h, mask_w) != (image_h, image_w) and not (image_h % mask_h == 0 and image_w % mask_w == 0):
|
|
1007
|
+
errors.append(
|
|
1008
|
+
f"Input `{inp.name}`: the mask from `{masks_name}` is {mask_h}x{mask_w} for {where} but the "
|
|
1009
|
+
f"foundation image is {image_h}x{image_w}; the mask must be the image's H x W or an integer "
|
|
1010
|
+
f"divisor of it.")
|
|
1011
|
+
if native_instance is None:
|
|
1012
|
+
continue # a mask where the native encoder returned None is ignored (no row)
|
|
1013
|
+
geometry_only = foundation_instance.name == masks_name and foundation_instance.instance_metadata is None
|
|
1014
|
+
if geometry_only:
|
|
1015
|
+
continue # a bare array wrapped by the decorator: nothing declared to compare
|
|
1016
|
+
if foundation_instance.name != native_instance.name:
|
|
1017
|
+
warnings.append(
|
|
1018
|
+
f"Input `{inp.name}`: masks encoder `{masks_name}` names {where} {foundation_instance.name!r} "
|
|
1019
|
+
f"while the native encoder `{native.name}` names it {native_instance.name!r}; only the "
|
|
1020
|
+
f"geometry is taken from `{masks_name}`, the name comes from the native encoder.")
|
|
1021
|
+
if foundation_instance.instance_metadata != native_instance.instance_metadata:
|
|
1022
|
+
warnings.append(
|
|
1023
|
+
f"Input `{inp.name}`: masks encoder `{masks_name}` returns instance_metadata for {where} "
|
|
1024
|
+
f"that differs from the native encoder `{native.name}`'s; only the geometry is taken from "
|
|
1025
|
+
f"`{masks_name}`, the metadata comes from the native encoder.")
|
|
1026
|
+
|
|
612
1027
|
def _check_simulations(self):
|
|
613
1028
|
# type: () -> List[DatasetTestResultPayload]
|
|
614
1029
|
result_payloads = []
|
|
@@ -994,7 +1409,9 @@ class LeapLoader(LeapLoaderBase):
|
|
|
994
1409
|
for inp in setup.inputs:
|
|
995
1410
|
if inp.shape is None:
|
|
996
1411
|
raise Exception(f"cant calculate shape for input, input name:{inp.name}")
|
|
997
|
-
inputs.append(DatasetInputInstance(name=inp.name, shape=inp.shape, channel_dim=inp.channel_dim
|
|
1412
|
+
inputs.append(DatasetInputInstance(name=inp.name, shape=inp.shape, channel_dim=inp.channel_dim,
|
|
1413
|
+
foundation=self._foundation_input_instance(inp),
|
|
1414
|
+
frame_dim=self._resolved_frame_dim(inp)))
|
|
998
1415
|
|
|
999
1416
|
if setup.autoregressive_step is not None:
|
|
1000
1417
|
# The hook is the sole input source; report its step-0 inputs as the dataset inputs so
|
|
@@ -1079,6 +1496,48 @@ class LeapLoader(LeapLoaderBase):
|
|
|
1079
1496
|
custom_losses=custom_losses, metrics=metrics, simulations=simulations,
|
|
1080
1497
|
has_element_instances=self._has_element_instances())
|
|
1081
1498
|
|
|
1499
|
+
def _resolved_frame_dim(self, inp: InputHandler) -> Optional[int]:
|
|
1500
|
+
"""The frame axis of a 4-D sample in the batched tensor, non-negative: the declared frame_dim
|
|
1501
|
+
resolved, or, for the foundation input with frame_dim unset, the inferred one. None otherwise."""
|
|
1502
|
+
if inp.shape is None or len(inp.shape) != FRAME_SAMPLE_RANK:
|
|
1503
|
+
return None
|
|
1504
|
+
if inp.frame_dim is None and inp.foundation is None:
|
|
1505
|
+
return None
|
|
1506
|
+
layout = self._foundation_layout(inp, inp.shape)
|
|
1507
|
+
if layout is None or layout[0] is None:
|
|
1508
|
+
return None
|
|
1509
|
+
return layout[0] + 1
|
|
1510
|
+
|
|
1511
|
+
def _foundation_input_instance(self, inp: InputHandler) -> Optional[FoundationInputInstance]:
|
|
1512
|
+
if inp.foundation is None:
|
|
1513
|
+
return None
|
|
1514
|
+
if inp.dtype is None:
|
|
1515
|
+
raise Exception(f"cant determine dtype for input, input name:{inp.name}")
|
|
1516
|
+
return FoundationInputInstance(rgb_range=[[low, high] for low, high in inp.foundation.bounds()],
|
|
1517
|
+
rgb_channels=list(inp.foundation.rgb_channels),
|
|
1518
|
+
dtype=inp.dtype, wired_to_model=self._is_input_wired_to_model(inp.name),
|
|
1519
|
+
masks_encoder=inp.foundation.masks_encoder_name)
|
|
1520
|
+
|
|
1521
|
+
def _is_input_wired_to_model(self, name: str) -> bool:
|
|
1522
|
+
"""Does the integration test pass this input to the model?
|
|
1523
|
+
|
|
1524
|
+
exec_script runs the integration test in mapping mode before any handler is probed. An input
|
|
1525
|
+
encoder called there appends a connection of type `Input`; passing its result to the model
|
|
1526
|
+
re-tags that node `Input0..9` (`model_input_index=` tags it at decoration). So after
|
|
1527
|
+
exec_script: `InputN` -> wired, `Input` or no connection at all -> not wired. An input tagged
|
|
1528
|
+
with `model_input_index=` but never called in the integration test has no connection and is
|
|
1529
|
+
not wired either -- the engine would not bind it, so the two views agree. A legacy script
|
|
1530
|
+
without an integration test wires every input through the mapping file, so all count as wired.
|
|
1531
|
+
"""
|
|
1532
|
+
self.exec_script()
|
|
1533
|
+
if global_leap_binder.integration_test_func is None:
|
|
1534
|
+
return True
|
|
1535
|
+
return any(connection.node is not None
|
|
1536
|
+
and connection.node.name == name
|
|
1537
|
+
and connection.node.type is not NodeMappingType.Input
|
|
1538
|
+
and connection.node.type.name.startswith('Input')
|
|
1539
|
+
for connection in global_leap_binder.mapping_connections)
|
|
1540
|
+
|
|
1082
1541
|
def _has_element_instances(self) -> bool:
|
|
1083
1542
|
"""Does this dataset have element instances? Both halves, because either alone lies.
|
|
1084
1543
|
|
|
@@ -9,9 +9,15 @@ import logging
|
|
|
9
9
|
from enum import Enum
|
|
10
10
|
from pathlib import Path
|
|
11
11
|
from typing import Optional, Dict, Any, Set, Union, TypedDict
|
|
12
|
-
import mixpanel # type: ignore[import]
|
|
13
12
|
import requests
|
|
14
13
|
|
|
14
|
+
try:
|
|
15
|
+
import mixpanel # type: ignore[import]
|
|
16
|
+
except ImportError:
|
|
17
|
+
# mixpanel is optional: without it (e.g. an offline install with `pip install --no-deps`)
|
|
18
|
+
# no analytics are sent and everything else in code-loader works as usual.
|
|
19
|
+
mixpanel = None
|
|
20
|
+
|
|
15
21
|
logger = logging.getLogger(__name__)
|
|
16
22
|
|
|
17
23
|
TRACKING_VERSION = '2'
|
|
@@ -300,19 +306,33 @@ def _is_analytics_disabled() -> bool:
|
|
|
300
306
|
return bool(os.environ.get(TL_DISABLE_ANALYTICS_ENV_VAR))
|
|
301
307
|
|
|
302
308
|
|
|
309
|
+
_logged_mixpanel_missing = False
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _is_mixpanel_missing() -> bool:
|
|
313
|
+
"""True when the mixpanel package isn't installed; says so once in the debug log."""
|
|
314
|
+
global _logged_mixpanel_missing
|
|
315
|
+
if mixpanel is not None:
|
|
316
|
+
return False
|
|
317
|
+
if not _logged_mixpanel_missing:
|
|
318
|
+
_logged_mixpanel_missing = True
|
|
319
|
+
logger.debug("mixpanel is not installed: code-loader analytics are not sent")
|
|
320
|
+
return True
|
|
321
|
+
|
|
322
|
+
|
|
303
323
|
def disable_analytics() -> None:
|
|
304
324
|
"""Programmatically disable all analytics/Mixpanel tracking."""
|
|
305
325
|
os.environ[TL_DISABLE_ANALYTICS_ENV_VAR] = 'true'
|
|
306
326
|
|
|
307
327
|
|
|
308
328
|
def track_code_loader_loaded(event_properties: Optional[Dict[str, Any]] = None) -> None:
|
|
309
|
-
if _is_analytics_disabled():
|
|
329
|
+
if _is_analytics_disabled() or _is_mixpanel_missing():
|
|
310
330
|
return
|
|
311
331
|
get_tracker().track_code_loader_loaded(event_properties)
|
|
312
332
|
|
|
313
333
|
|
|
314
334
|
def track_integration_test_event(event_name: Union[str, AnalyticsEvent], event_properties: Optional[Dict[str, Any]] = None) -> None:
|
|
315
|
-
if _is_analytics_disabled():
|
|
335
|
+
if _is_analytics_disabled() or _is_mixpanel_missing():
|
|
316
336
|
return
|
|
317
337
|
get_tracker().track_integration_test_event(event_name, event_properties)
|
|
318
338
|
|
|
@@ -323,7 +343,7 @@ _integration_events_emitted: Set[str] = set()
|
|
|
323
343
|
|
|
324
344
|
def emit_integration_event_once(event_name: Union[str, AnalyticsEvent], props: Dict[str, Any]) -> None:
|
|
325
345
|
"""Emit an integration test event only once per test run."""
|
|
326
|
-
if _is_analytics_disabled():
|
|
346
|
+
if _is_analytics_disabled() or _is_mixpanel_missing():
|
|
327
347
|
return
|
|
328
348
|
event_name_str = str(event_name)
|
|
329
349
|
if event_name_str in _integration_events_emitted:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/experiment_context.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{code_loader-1.0.220 → code_loader-1.0.222}/code_loader/experiment_api/workingspace_config_utils.py
RENAMED
|
File without changes
|
|
File without changes
|
{code_loader-1.0.220 → code_loader-1.0.222}/code_loader/inner_leap_binder/fp_confidence_contract.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|