code-loader 1.0.196.dev0__py3-none-any.whl → 1.0.197.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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, Union, Type, Literal, Tuple
4
4
  import re
5
5
  import numpy as np
6
6
  import numpy.typing as npt
@@ -15,8 +15,6 @@ custom_latent_space_attribute = "custom_latent_space"
15
15
 
16
16
  _simulation_context: Dict[str, bool] = {"active": False}
17
17
 
18
- SampleId = Union[int, str]
19
-
20
18
 
21
19
  @dataclass
22
20
  class PreprocessResponse:
@@ -41,46 +39,27 @@ class PreprocessResponse:
41
39
  """
42
40
  length: Optional[int] = None # Deprecated. Please use sample_ids instead
43
41
  data: Any = None
44
- sample_ids: Optional[Union[List[SampleId], List[List[SampleId]]]] = None
42
+ sample_ids: Optional[Union[List[str], List[int]]] = None
45
43
  state: Optional[DataStateType] = None
46
44
  sample_id_type: Optional[Union[Type[str], Type[int]]] = None
47
45
  sample_ids_to_instance_mappings: Optional[Dict[str, List[str]]] = None # in use only for element instance
48
46
  instance_to_sample_ids_mappings: Optional[Dict[str, str]] = None # in use only for element instance
49
47
  tl_generated: bool = False
50
- _grouped: bool = field(default=False, init=False, repr=False, compare=False)
51
- _group_pos_cache: Optional[Dict[SampleId, Tuple[List[SampleId], int]]] = field(
52
- default=None, init=False, repr=False, compare=False)
53
48
 
54
49
  def __post_init__(self) -> None:
55
50
  assert self.sample_ids_to_instance_mappings is None, f"Keep sample_ids_to_instance_mappings None when initializing PreprocessResponse"
56
51
  assert self.instance_to_sample_ids_mappings is None, f"Keep instance_to_sample_ids_mappings None when initializing PreprocessResponse"
57
52
 
58
53
  if self.length is not None and self.sample_ids is None:
59
- self.sample_ids = cast(List[SampleId], [i for i in range(self.length)])
54
+ self.sample_ids = [i for i in range(self.length)]
60
55
  self.sample_id_type = int
61
- self._grouped = False
62
56
  elif self.length is None and self.sample_ids is not None:
63
- self._grouped = len(self.sample_ids) > 0 and isinstance(self.sample_ids[0], list)
64
- if self._grouped:
65
- groups = cast(List[List[SampleId]], self.sample_ids)
66
- assert len(groups) >= 1, "Grouped PreprocessResponse must have at least one group."
67
- for group in groups:
68
- assert isinstance(group, list) and len(group) > 0, \
69
- "Each group in a grouped PreprocessResponse must be a non-empty list."
70
- self.sample_id_type = type(groups[0][0])
71
- for group in groups:
72
- for sample_id in group:
73
- assert isinstance(sample_id, self.sample_id_type), \
74
- f"Sample id should be of type {self.sample_id_type.__name__}. Got: {type(sample_id)}"
75
- self.length = sum(len(group) for group in groups)
76
- else:
77
- flat_ids = cast(List[SampleId], self.sample_ids)
78
- self.length = len(flat_ids)
79
- if self.sample_id_type is None:
80
- self.sample_id_type = str
81
- if self.sample_id_type == str:
82
- for sample_id in flat_ids:
83
- assert isinstance(sample_id, str), f"Sample id should be of type str. Got: {type(sample_id)}"
57
+ self.length = len(self.sample_ids)
58
+ if self.sample_id_type is None:
59
+ self.sample_id_type = str
60
+ if self.sample_id_type == str:
61
+ for sample_id in self.sample_ids:
62
+ assert isinstance(sample_id, str), f"Sample id should be of type str. Got: {type(sample_id)}"
84
63
  else:
85
64
  raise Exception("length is deprecated, please use sample_ids instead.")
86
65
 
@@ -100,36 +79,9 @@ class PreprocessResponse:
100
79
  return id(self)
101
80
 
102
81
  def __len__(self) -> int:
103
- assert self.length is not None
104
- return self.length
105
-
106
- @property
107
- def is_grouped(self) -> bool:
108
- return self._grouped
109
-
110
- @property
111
- def num_groups(self) -> int:
112
- # Grouped: the number of groups. Flat: the (flat) sample count, since sample_ids is the
113
- # flat id list and there is one sample per "group".
114
82
  assert self.sample_ids is not None
115
83
  return len(self.sample_ids)
116
84
 
117
- @property
118
- def groups(self) -> Optional[List[List[SampleId]]]:
119
- # The nested list of groups when grouped, otherwise None. Callers should
120
- # branch on is_grouped before relying on this.
121
- return cast(List[List[SampleId]], self.sample_ids) if self._grouped else None
122
-
123
- @property
124
- def flat_sample_ids(self) -> List[SampleId]:
125
- # All sample ids in order: concatenation of the groups when grouped,
126
- # otherwise the flat sample_ids list as-is.
127
- assert self.sample_ids is not None
128
- if self._grouped:
129
- groups = cast(List[List[SampleId]], self.sample_ids)
130
- return [sample_id for group in groups for sample_id in group]
131
- return cast(List[SampleId], self.sample_ids)
132
-
133
85
  @dataclass
134
86
  class ElementInstance:
135
87
  name: str
@@ -382,7 +334,7 @@ class DatasetIntegrationSetup:
382
334
  metrics: List[MetricHandler] = field(default_factory=list)
383
335
  instance_metrics: List[InstanceMetricHandler] = field(default_factory=list)
384
336
  custom_layers: Dict[str, CustomLayerHandler] = field(default_factory=dict)
385
- custom_latent_space: Optional[CustomLatentSpaceHandler] = None
337
+ custom_latent_spaces: Dict[str, CustomLatentSpaceHandler] = field(default_factory=dict)
386
338
  simulations: List[SimulationHandler] = field(default_factory=list)
387
339
  autoregressive_step: Optional[AutoregressiveStepHandler] = None
388
340
  autoregressive_metrics: List[AutoregressiveMetricHandler] = field(default_factory=list)
@@ -398,6 +350,6 @@ class DatasetSample:
398
350
  metadata_is_none: Dict[str, bool]
399
351
  index: Union[int, str]
400
352
  state: DataStateEnum
401
- custom_latent_space: Optional[npt.NDArray[np.float32]] = None
353
+ custom_latent_spaces: Optional[Dict[str, npt.NDArray[np.float32]]] = None
402
354
  instance_masks: Optional[Dict[str, ElementInstance]] = None
403
355
 
@@ -1,6 +1,6 @@
1
1
 
2
2
  import inspect
3
- from typing import Callable, List, Optional, Dict, Any, Type, Union, get_args, cast
3
+ from typing import Callable, List, Optional, Dict, Any, Type, Union, get_args
4
4
 
5
5
  import numpy as np
6
6
  import numpy.typing as npt
@@ -513,18 +513,34 @@ class LeapBinder:
513
513
  """
514
514
  self.setup_container.metadata.append(MetadataHandler(name, function, metadata_type))
515
515
 
516
- def set_custom_latent_space(self, function: SectionCallableInterface) -> None:
516
+ def set_custom_latent_space(self, function: SectionCallableInterface,
517
+ name: Optional[str] = None) -> None:
517
518
  """
518
- Set a custom latent space function.
519
+ Register a custom latent space function.
520
+
521
+ Multiple custom latent spaces may be registered as long as each has a
522
+ unique name. They are stored name-keyed (insertion order preserved), so a
523
+ later registration no longer overrides an earlier one.
519
524
 
520
525
  Args:
521
- function (SectionCallableInterface): The metadata handler function.
526
+ function (SectionCallableInterface): The latent-space handler function.
522
527
  This function receives:
523
528
  subset (PreprocessResponse): The subset of the data.
524
529
  index (int): The index of the sample within the subset.
525
- This function should numpy float32 array contains the latent space vec of the sample.
530
+ This function should return a numpy float32 array containing the latent
531
+ space vec of the sample.
532
+ name (Optional[str]): Unique name for this custom latent space. Defaults to
533
+ the reserved single-LS name for backward compatibility.
526
534
  """
527
- self.setup_container.custom_latent_space = CustomLatentSpaceHandler(function)
535
+ if name is None:
536
+ name = custom_latent_space_attribute
537
+ if name in self.setup_container.custom_latent_spaces:
538
+ raise Exception(
539
+ f"A custom latent space named '{name}' is already registered. Each "
540
+ f"@tensorleap_custom_latent_space must have a unique name "
541
+ f"(pass name='...' to distinguish them)."
542
+ )
543
+ self.setup_container.custom_latent_spaces[name] = CustomLatentSpaceHandler(function, name)
528
544
 
529
545
  def set_autoregressive_step(self, function: AutoregressiveStepCallableInterface,
530
546
  latent_space_aggregation: str = 'last_step') -> None:
@@ -549,9 +565,7 @@ class LeapBinder:
549
565
  # Builtin chain metadata, declared at parse time so it survives the reporter's
550
566
  # metadata type mapping; the placeholder values are overwritten by the engine when a
551
567
  # chain finalizes (realized length, truncated-by-safety-cap flag).
552
- def builtin_chain_metadata(idx: Any, preprocess: PreprocessResponse) -> Any:
553
- if isinstance(idx, list):
554
- return [{'length': -1, 'truncated': False} for _ in idx]
568
+ def builtin_chain_metadata(idx: Any, preprocess: PreprocessResponse) -> Dict[str, Any]:
555
569
  return {'length': -1, 'truncated': False}
556
570
 
557
571
  self.set_metadata(builtin_chain_metadata, 'builtin_chain')
@@ -715,15 +729,6 @@ class LeapBinder:
715
729
  if state_enum in preprocess_result_dict:
716
730
  preprocess_result_dict_in_correct_order[state_enum] = preprocess_result_dict[state_enum]
717
731
 
718
- # All-or-none: every state must agree on grouped (nested sample_ids) vs flat.
719
- if len({r.is_grouped for r in preprocess_result_dict_in_correct_order.values()}) > 1:
720
- shapes = ', '.join(
721
- f"{state.name}={'grouped' if r.is_grouped else 'flat'}"
722
- for state, r in preprocess_result_dict_in_correct_order.items())
723
- raise Exception(
724
- "All preprocess states must be either all grouped (nested sample_ids) or all flat, "
725
- f"but got a mix: {shapes}.")
726
-
727
732
  return preprocess_result_dict_in_correct_order
728
733
 
729
734
  def get_preprocess_unlabeled_result(self) -> Optional[PreprocessResponse]:
@@ -744,15 +749,7 @@ class LeapBinder:
744
749
  preprocess_response: PreprocessResponse, test_result: List[DatasetTestResultPayload],
745
750
  dataset_base_handler: Union[DatasetBaseHandler, MetadataHandler], state: DataStateEnum) -> List[DatasetTestResultPayload]:
746
751
  assert preprocess_response.sample_ids is not None
747
- if preprocess_response.is_grouped:
748
- # Grouped: probe with the first group, then reduce to a single sample's result so the
749
- # recorded shape/type is per-sample (matching the flat case), not the (B, *) batch.
750
- # (casts: sample_ids[0] is a group list here, and the grouped result is a per-sample list.)
751
- group = preprocess_response.sample_ids[0]
752
- raw_result = cast(Any, dataset_base_handler.function(cast(Any, group), preprocess_response))[0]
753
- else:
754
- raw_result = dataset_base_handler.function(
755
- cast(Union[int, str], preprocess_response.sample_ids[0]), preprocess_response)
752
+ raw_result = dataset_base_handler.function(preprocess_response.sample_ids[0], preprocess_response)
756
753
  handler_type = 'metadata' if isinstance(dataset_base_handler, MetadataHandler) else None
757
754
  if isinstance(dataset_base_handler, MetadataHandler):
758
755
  if isinstance(raw_result, dict):
@@ -848,11 +845,10 @@ class LeapBinder:
848
845
  preprocess_response.tl_generated = True
849
846
  if not preprocess_response.length or preprocess_response.length < 1:
850
847
  raise Exception("Simulation '{}' returned PreprocessResponse with length < 1".format(sim.name))
851
- preprocess_response.sample_ids = cast(List[Union[int, str]], [0])
852
- sim_sample_ids = cast(List[Union[int, str]], preprocess_response.sample_ids)
848
+ preprocess_response.sample_ids = [0]
853
849
  for handler in self.setup_container.inputs:
854
- out1 = handler.function(sim_sample_ids[0], preprocess_response)
855
- out2 = handler.function(sim_sample_ids[0], preprocess_response)
850
+ out1 = handler.function(preprocess_response.sample_ids[0], preprocess_response)
851
+ out2 = handler.function(preprocess_response.sample_ids[0], preprocess_response)
856
852
  if not np.allclose(out1, out2):
857
853
  raise Exception(
858
854
  "Simulation '{}': encoder '{}' is non-deterministic — consecutive calls with seed=0 returned different outputs".format(
@@ -40,7 +40,6 @@ _called_from_inside_tl_integration_test_decorator = False
40
40
  # to tell a raise in the test body (report as code-flow failure) from a module-level crash
41
41
  # before any test ran (report as a plain script crash).
42
42
  _integration_test_started = False
43
- _mapping_dataset_is_grouped = False
44
43
  _call_from_tl_platform = os.environ.get('IS_TENSORLEAP_PLATFORM') == 'true'
45
44
 
46
45
  # ---- warnings store (module-level) ----
@@ -214,53 +213,6 @@ def batch_warning(result, func_name):
214
213
  )
215
214
 
216
215
 
217
- def _validate_id_or_group(sample_id, preprocess_response, func_name):
218
- """Accept either a single sample id (flat dataset) or a group — a list of ids (grouped
219
- dataset). The argument shape must match the dataset: a group requires a grouped
220
- PreprocessResponse and a single id requires a flat one. Every id must match the declared
221
- sample_id_type."""
222
- is_group = isinstance(sample_id, list)
223
- if is_group and not preprocess_response.is_grouped:
224
- raise AssertionError(
225
- f'{func_name}() validation failed: got a group (list of sample ids) but the '
226
- f'PreprocessResponse is not grouped. Pass a single sample id for a flat dataset.')
227
- if not is_group and preprocess_response.is_grouped:
228
- raise AssertionError(
229
- f'{func_name}() validation failed: got a single sample id but the PreprocessResponse '
230
- f'is grouped. Pass a group (list of sample ids) for a grouped dataset.')
231
- ids = sample_id if is_group else [sample_id]
232
- for sid in ids:
233
- assert type(sid) == preprocess_response.sample_id_type, \
234
- (f'{func_name}() validation failed: '
235
- f'Argument sample_id should be as the same type as defined in the preprocess response '
236
- f'{preprocess_response.sample_id_type}. Got {type(sid)}.')
237
-
238
-
239
- def _validate_grouped_result(result, group_size, func_name, validate_single):
240
- """A grouped (group) encoder result must be either a single ndarray with leading dim
241
- == group_size, or a list of `group_size` per-sample results (each validated by
242
- validate_single). Metadata validates its grouped result separately (list only).
243
- An `(B, *)` array is validated per-sample slice (not as the whole batched array) so
244
- per-sample checks (e.g. channel_dim <= rank) use the sample shape, not the batch shape."""
245
- if isinstance(result, np.ndarray):
246
- assert len(result.shape) > 0 and result.shape[0] == group_size, \
247
- (f'{func_name}() validation failed: expected a grouped output for a group of '
248
- f'{group_size}: an array with leading dim {group_size}, got shape {result.shape}.')
249
- for single in result:
250
- validate_single(single)
251
- elif isinstance(result, list):
252
- assert len(result) == group_size, \
253
- (f'{func_name}() validation failed: expected a grouped output for a group of '
254
- f'{group_size}: a list of {group_size} arrays, got {len(result)}.')
255
- for r in result:
256
- validate_single(r)
257
- else:
258
- raise AssertionError(
259
- f'{func_name}() validation failed: expected a grouped output for a group of '
260
- f'{group_size}: either an array with leading dim {group_size} or a list of '
261
- f'{group_size} arrays, got {type(result)}.')
262
-
263
-
264
216
  def _add_mapping_connection(user_unique_name, connection_destinations, arg_names, name, node_mapping_type):
265
217
  connection_destinations = [connection_destination for connection_destination in connection_destinations
266
218
  if not isinstance(connection_destination, SamplePreprocessResponse)]
@@ -338,7 +290,11 @@ def tensorleap_integration_test():
338
290
 
339
291
  def _validate_input_args(*args, **kwargs):
340
292
  sample_id, preprocess_response = args
341
- _validate_id_or_group(sample_id, preprocess_response, 'tensorleap_integration_test')
293
+ assert type(sample_id) == preprocess_response.sample_id_type, (
294
+ f"tensorleap_integration_test validation failed: "
295
+ f"sample_id type ({type(sample_id).__name__}) does not match the expected "
296
+ f"type ({preprocess_response.sample_id_type}) from the PreprocessResponse."
297
+ )
342
298
 
343
299
  def inner(*args, **kwargs):
344
300
  if not _call_from_tl_platform:
@@ -349,7 +305,7 @@ def tensorleap_integration_test():
349
305
  expected_names = inspect.getfullargspec(integration_test_function)[0][:2]
350
306
  if len(expected_names) < 2:
351
307
  expected_names = ['idx', 'preprocess']
352
- validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
308
+ validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
353
309
  func_name='integration_test', expected_names=expected_names,
354
310
  **kwargs)
355
311
  sample_id, preprocess_response = (
@@ -373,8 +329,6 @@ def tensorleap_integration_test():
373
329
  _reset_model_loop_state()
374
330
  ret = integration_test_function(*args, **kwargs)
375
331
 
376
- global _mapping_dataset_is_grouped
377
- _mapping_dataset_is_grouped = args[1].is_grouped
378
332
  try:
379
333
  os.environ[mapping_runtime_mode_env_var_mame] = 'True'
380
334
  _reset_model_loop_state()
@@ -395,7 +349,6 @@ def tensorleap_integration_test():
395
349
  f'Integration test is only allowed to call Tensorleap decorators. '
396
350
  f'Ensure any arithmetics, external library use, Python logic is placed within Tensorleap decoders')
397
351
  finally:
398
- _mapping_dataset_is_grouped = False
399
352
  if mapping_runtime_mode_env_var_mame in os.environ:
400
353
  del os.environ[mapping_runtime_mode_env_var_mame]
401
354
  finally:
@@ -1608,10 +1561,13 @@ def tensorleap_metadata(
1608
1561
  raise Exception(f'Metadata with name {name} already exists. '
1609
1562
  f'Please choose another')
1610
1563
 
1611
- def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
1612
- _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
1564
+ def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
1565
+ assert type(sample_id) == preprocess_response.sample_id_type, \
1566
+ (f'{user_function.__name__}() validation failed: '
1567
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
1568
+ f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
1613
1569
 
1614
- def _validate_single(result):
1570
+ def _validate_result(result):
1615
1571
  supported_result_types = (type(None), int, str, bool, float, dict, np.floating,
1616
1572
  np.bool_, np.unsignedinteger, np.signedinteger, np.integer)
1617
1573
  if isinstance(result, tuple):
@@ -1629,20 +1585,6 @@ def tensorleap_metadata(
1629
1585
  (f'{user_function.__name__}() validation failed: '
1630
1586
  f'Values in the return dict should be of type {str(supported_result_types)}. Got {type(value)}.')
1631
1587
 
1632
- def _validate_result(result, grouped=False, group_size=None):
1633
- if not grouped:
1634
- _validate_single(result)
1635
- return
1636
- # Grouped metadata: a list of `group_size` per-sample scalars/dicts.
1637
- assert isinstance(result, list), \
1638
- (f'{user_function.__name__}() validation failed: expected a grouped output for a group '
1639
- f'of {group_size}: a list of {group_size} metadata values, got {type(result)}.')
1640
- assert len(result) == group_size, \
1641
- (f'{user_function.__name__}() validation failed: expected a grouped output for a group '
1642
- f'of {group_size}: a list of {group_size} metadata values, got {len(result)}.')
1643
- for value in result:
1644
- _validate_single(value)
1645
-
1646
1588
  def inner_without_validate(sample_id, preprocess_response):
1647
1589
 
1648
1590
  global _called_from_inside_tl_decorator
@@ -1662,16 +1604,14 @@ def tensorleap_metadata(
1662
1604
  set_current('tensorleap_metadata')
1663
1605
  if os.environ.get(mapping_runtime_mode_env_var_mame):
1664
1606
  return None
1665
- validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
1607
+ validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
1666
1608
  func_name=user_function.__name__, expected_names=["idx", "preprocess"], **kwargs)
1667
1609
  sample_id, preprocess_response = args if len(args) != 0 else kwargs.values()
1668
1610
  _validate_input_args(sample_id, preprocess_response)
1669
1611
 
1670
- grouped = isinstance(sample_id, list)
1671
- group_size = len(sample_id) if grouped else None
1672
1612
  result = inner_without_validate(sample_id, preprocess_response)
1673
1613
 
1674
- _validate_result(result, grouped, group_size)
1614
+ _validate_result(result)
1675
1615
  if not _call_from_tl_platform:
1676
1616
  update_env_params_func("tensorleap_metadata", "v")
1677
1617
  return result
@@ -1681,52 +1621,38 @@ def tensorleap_metadata(
1681
1621
  return decorating_function
1682
1622
 
1683
1623
 
1684
- def tensorleap_custom_latent_space():
1624
+ def tensorleap_custom_latent_space(name: Optional[str] = None):
1685
1625
  def decorating_function(user_function: SectionCallableInterface):
1686
- def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
1687
- _validate_id_or_group(sample_id, preprocess_response, 'tensorleap_custom_latent_space')
1626
+ ls_name = name if name is not None else user_function.__name__
1627
+ def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
1628
+ assert isinstance(sample_id, (int, str)), \
1629
+ (f'tensorleap_custom_latent_space validation failed: '
1630
+ f'Argument sample_id should be either int or str. Got {type(sample_id)}.')
1631
+ assert isinstance(preprocess_response, PreprocessResponse), \
1632
+ (f'tensorleap_custom_latent_space validation failed: '
1633
+ f'Argument preprocess_response should be a PreprocessResponse. Got {type(preprocess_response)}.')
1634
+ assert type(sample_id) == preprocess_response.sample_id_type, \
1635
+ (f'tensorleap_custom_latent_space validation failed: '
1636
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
1637
+ f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
1688
1638
 
1689
- def _validate_single(single_result):
1690
- assert isinstance(single_result, np.ndarray), \
1639
+ def _validate_result(result):
1640
+ assert isinstance(result, np.ndarray), \
1691
1641
  (f'tensorleap_custom_latent_space validation failed: '
1692
- f'The return type should be a numpy array. Got {type(single_result)}.')
1693
- if single_result.ndim > 1:
1694
- flat_dim = int(np.prod(single_result.shape))
1642
+ f'The return type should be a numpy array. Got {type(result)}.')
1643
+ if result.ndim > 1:
1644
+ flat_dim = int(np.prod(result.shape))
1695
1645
  store_general_warning(
1696
- key=("tensorleap_custom_latent_space_flatten", tuple(single_result.shape)),
1646
+ key=("tensorleap_custom_latent_space_flatten", ls_name, tuple(result.shape)),
1697
1647
  message=(
1698
- f"tensorleap_custom_latent_space returned per-sample shape {tuple(single_result.shape)} "
1699
- f"(ndim={single_result.ndim}). Tensorleap assumes per-sample shape (d, ...) and will "
1648
+ f"tensorleap_custom_latent_space '{ls_name}' returned per-sample shape {tuple(result.shape)} "
1649
+ f"(ndim={result.ndim}). Tensorleap assumes per-sample shape (d, ...) and will "
1700
1650
  f"flatten to ({flat_dim},) before downstream visualization and clustering. "
1701
1651
  f"If you want a different aggregation (e.g. global average pooling), do it "
1702
1652
  f"inside your function."
1703
1653
  ),
1704
1654
  )
1705
1655
 
1706
- def _validate_result(result, grouped=False, group_size=None):
1707
- if not grouped:
1708
- _validate_single(result)
1709
- return
1710
- # Grouped: (B, *) array or list of B per-sample arrays. Validate each per-sample slice so
1711
- # the per-sample flatten check/warning uses the sample shape, not the (B, *) batch shape.
1712
- if isinstance(result, np.ndarray):
1713
- assert result.ndim >= 1 and result.shape[0] == group_size, \
1714
- (f'tensorleap_custom_latent_space validation failed: expected a grouped output for a '
1715
- f'group of {group_size}: an array with leading dim {group_size}, got shape {result.shape}.')
1716
- for single in result:
1717
- _validate_single(single)
1718
- elif isinstance(result, list):
1719
- assert len(result) == group_size, \
1720
- (f'tensorleap_custom_latent_space validation failed: expected a grouped output for a '
1721
- f'group of {group_size}: a list of {group_size} arrays, got {len(result)}.')
1722
- for single in result:
1723
- _validate_single(single)
1724
- else:
1725
- raise AssertionError(
1726
- f'tensorleap_custom_latent_space validation failed: expected a grouped output for a '
1727
- f'group of {group_size}: either an array with leading dim {group_size} or a list of '
1728
- f'{group_size} arrays, got {type(result)}.')
1729
-
1730
1656
  def inner_without_validate(sample_id, preprocess_response):
1731
1657
  global _called_from_inside_tl_decorator
1732
1658
  _called_from_inside_tl_decorator += 1
@@ -1738,7 +1664,7 @@ def tensorleap_custom_latent_space():
1738
1664
 
1739
1665
  return result
1740
1666
 
1741
- leap_binder.set_custom_latent_space(inner_without_validate)
1667
+ leap_binder.set_custom_latent_space(inner_without_validate, ls_name)
1742
1668
 
1743
1669
  def inner(sample_id, preprocess_response):
1744
1670
  if os.environ.get(mapping_runtime_mode_env_var_mame):
@@ -1746,11 +1672,9 @@ def tensorleap_custom_latent_space():
1746
1672
 
1747
1673
  _validate_input_args(sample_id, preprocess_response)
1748
1674
 
1749
- grouped = isinstance(sample_id, list)
1750
- group_size = len(sample_id) if grouped else None
1751
1675
  result = inner_without_validate(sample_id, preprocess_response)
1752
1676
 
1753
- _validate_result(result, grouped, group_size)
1677
+ _validate_result(result)
1754
1678
  return result
1755
1679
 
1756
1680
  return inner
@@ -2010,9 +1934,10 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2010
1934
  state returned by the previous call, and return the next step's full input dict together with
2011
1935
  the updated state; returning (None, state) ends the chain — the terminating call still
2012
1936
  returns state, so the final step participates in state aggregation. State is never fed to
2013
- the model; it may be any nest of dicts/lists holding numpy arrays, numbers, strings or bools,
2014
- and it rides the platform queue on every step accumulate reductions, not raw per-step
2015
- tensors. The hook must be stateless and deterministically seeded (seed stochasticity from
1937
+ the model; any picklable nest of builtin/numpy values works (dicts, lists, tuples, sets,
1938
+ numbers, strings, arrays not user-defined classes, lambdas or open resources, since the
1939
+ platform deserializes state without the integration code), and it rides the platform queue
1940
+ on every step — accumulate reductions, not raw per-step tensors. The hook must be stateless and deterministically seeded (seed stochasticity from
2016
1941
  sample_id) — the engine replays steps after crash recovery and relies on identical results.
2017
1942
 
2018
1943
  latent_space_aggregation ('last_step' | 'mean') declares how the chain's latent-space
@@ -2718,15 +2643,6 @@ def tensorleap_preprocess():
2718
2643
  assert len(set(result)) == len(result), \
2719
2644
  (f'{user_function.__name__}() validation failed: '
2720
2645
  f'The return list should not contain duplicate PreprocessResponse objects.')
2721
- # All-or-none: a dataset is either all grouped (nested sample_ids) or all flat.
2722
- if len({response.is_grouped for response in result}) != 1:
2723
- shapes = ', '.join(
2724
- f"#{i}={'grouped' if response.is_grouped else 'flat'}"
2725
- for i, response in enumerate(result))
2726
- raise AssertionError(
2727
- f'{user_function.__name__}() validation failed: '
2728
- f'All PreprocessResponses must be either all grouped (nested sample_ids) '
2729
- f'or all flat, but got a mix: {shapes}.')
2730
2646
 
2731
2647
  def inner(*args, **kwargs):
2732
2648
  if not _call_from_tl_platform:
@@ -3064,10 +2980,14 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3064
2980
  f"channel axis in the batched tensor (batch = axis 0), so 0 is invalid. Use 1 "
3065
2981
  f"for channel-first (NCHW) and -1 for channel-last (NHWC).")
3066
2982
 
3067
- def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
3068
- _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
2983
+ def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
2984
+ assert type(sample_id) == preprocess_response.sample_id_type, \
2985
+ (f'{user_function.__name__}() validation failed: '
2986
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
2987
+ f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
3069
2988
 
3070
- def _validate_single(result):
2989
+ def _validate_result(result):
2990
+ validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray")
3071
2991
  assert isinstance(result, np.ndarray), \
3072
2992
  (f'{user_function.__name__}() validation failed: '
3073
2993
  f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
@@ -3077,13 +2997,6 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3077
2997
  assert channel_dim - 1 <= len(result.shape), (f'{user_function.__name__}() validation failed: '
3078
2998
  f'The channel_dim ({channel_dim}) should be <= to the rank of the resulting input rank ({len(result.shape)}).')
3079
2999
 
3080
- def _validate_result(result, grouped=False, group_size=None):
3081
- if not grouped:
3082
- validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray")
3083
- _validate_single(result)
3084
- return
3085
- _validate_grouped_result(result, group_size, user_function.__name__, _validate_single)
3086
-
3087
3000
  def inner_without_validate(sample_id, preprocess_response):
3088
3001
  global _called_from_inside_tl_decorator
3089
3002
  _called_from_inside_tl_decorator += 1
@@ -3100,27 +3013,18 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3100
3013
  def inner(*args, **kwargs):
3101
3014
  if not _call_from_tl_platform:
3102
3015
  set_current("tensorleap_input_encoder")
3103
- validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
3016
+ validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
3104
3017
  func_name=user_function.__name__, expected_names=["idx", "preprocess"], **kwargs)
3105
3018
  sample_id, preprocess_response = args if len(args) != 0 else kwargs.values()
3106
3019
  _validate_input_args(sample_id, preprocess_response)
3107
3020
 
3108
- grouped = isinstance(sample_id, list)
3109
- group_size = len(sample_id) if grouped else None
3110
3021
  result = inner_without_validate(sample_id, preprocess_response)
3111
3022
 
3112
- _validate_result(result, grouped, group_size)
3023
+ _validate_result(result)
3113
3024
 
3114
3025
  if _called_from_inside_tl_decorator == 0 and _called_from_inside_tl_integration_test_decorator:
3115
- if grouped:
3116
- # A grouped result is a list of per-sample arrays (never stacked, so a
3117
- # B=1-only model can be fed one sample at a time). Add a batch dim to each
3118
- # sample, mirroring the flat path's single-sample expand_dims.
3119
- if isinstance(result, list):
3120
- result = [np.expand_dims(r, axis=0) for r in result]
3121
- else:
3122
- batch_warning(result, user_function.__name__)
3123
- result = np.expand_dims(result, axis=0)
3026
+ batch_warning(result, user_function.__name__)
3027
+ result = np.expand_dims(result, axis=0)
3124
3028
  # Emit integration test event once per test
3125
3029
  try:
3126
3030
  emit_integration_event_once(AnalyticsEvent.INPUT_ENCODER_INTEGRATION_TEST, {
@@ -3141,15 +3045,8 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3141
3045
  inner.node_mapping = NodeMapping(name, node_mapping_type)
3142
3046
 
3143
3047
  def mapping_inner(*args, **kwargs):
3144
- if _mapping_dataset_is_grouped:
3145
- class TempMapping:
3146
- def __getitem__(self, key):
3147
- # Indexing a grouped input group (input_list[i]) selects a sample from the
3148
- # same input source; the model wiring is identical to the un-grouped input.
3149
- return self
3150
- else:
3151
- class TempMapping:
3152
- pass
3048
+ class TempMapping:
3049
+ pass
3153
3050
 
3154
3051
  ret = TempMapping()
3155
3052
  ret.node_mapping = mapping_inner.node_mapping
@@ -3179,10 +3076,15 @@ def tensorleap_gt_encoder(name: str):
3179
3076
  raise Exception(f'GT with name {name} already exists. '
3180
3077
  f'Please choose another')
3181
3078
 
3182
- def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
3183
- _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
3079
+ def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
3080
+ assert type(sample_id) == preprocess_response.sample_id_type, \
3081
+ (f'{user_function.__name__}() validation failed: '
3082
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
3083
+ f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
3184
3084
 
3185
- def _validate_single(result):
3085
+ def _validate_result(result):
3086
+ validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray",
3087
+ gt_flag=True)
3186
3088
  assert isinstance(result, np.ndarray), \
3187
3089
  (f'{user_function.__name__}() validation failed: '
3188
3090
  f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
@@ -3190,14 +3092,6 @@ def tensorleap_gt_encoder(name: str):
3190
3092
  (f'{user_function.__name__}() validation failed: '
3191
3093
  f'The return type should be a numpy array of type float32. Got {result.dtype}.')
3192
3094
 
3193
- def _validate_result(result, grouped=False, group_size=None):
3194
- if not grouped:
3195
- validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray",
3196
- gt_flag=True)
3197
- _validate_single(result)
3198
- return
3199
- _validate_grouped_result(result, group_size, user_function.__name__, _validate_single)
3200
-
3201
3095
  def inner_without_validate(sample_id, preprocess_response):
3202
3096
  global _called_from_inside_tl_decorator
3203
3097
  _called_from_inside_tl_decorator += 1
@@ -3214,27 +3108,18 @@ def tensorleap_gt_encoder(name: str):
3214
3108
  def inner(*args, **kwargs):
3215
3109
  if not _call_from_tl_platform:
3216
3110
  set_current("tensorleap_gt_encoder")
3217
- validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
3111
+ validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
3218
3112
  func_name=user_function.__name__, expected_names=["idx", "preprocess"], **kwargs)
3219
3113
  sample_id, preprocess_response = args
3220
3114
  _validate_input_args(sample_id, preprocess_response)
3221
3115
 
3222
- grouped = isinstance(sample_id, list)
3223
- group_size = len(sample_id) if grouped else None
3224
3116
  result = inner_without_validate(sample_id, preprocess_response)
3225
3117
 
3226
- _validate_result(result, grouped, group_size)
3118
+ _validate_result(result)
3227
3119
 
3228
3120
  if _called_from_inside_tl_decorator == 0 and _called_from_inside_tl_integration_test_decorator:
3229
- if grouped:
3230
- # A grouped result is a list of per-sample arrays (never stacked, so a
3231
- # B=1-only model can be fed one sample at a time). Add a batch dim to each
3232
- # sample, mirroring the flat path's single-sample expand_dims.
3233
- if isinstance(result, list):
3234
- result = [np.expand_dims(r, axis=0) for r in result]
3235
- else:
3236
- batch_warning(result, user_function.__name__)
3237
- result = np.expand_dims(result, axis=0)
3121
+ batch_warning(result, user_function.__name__)
3122
+ result = np.expand_dims(result, axis=0)
3238
3123
  _register_chain_artifact(result, 'ground_truth')
3239
3124
  # Emit integration test event once per test
3240
3125
  try:
@@ -3250,15 +3135,8 @@ def tensorleap_gt_encoder(name: str):
3250
3135
  inner.node_mapping = NodeMapping(name, NodeMappingType.GroundTruth)
3251
3136
 
3252
3137
  def mapping_inner(*args, **kwargs):
3253
- if _mapping_dataset_is_grouped:
3254
- class TempMapping:
3255
- def __getitem__(self, key):
3256
- # Indexing a grouped GT group (gt_list[i]) selects a sample from the same
3257
- # ground-truth source; wiring is identical to the un-grouped GT node.
3258
- return self
3259
- else:
3260
- class TempMapping:
3261
- pass
3138
+ class TempMapping:
3139
+ pass
3262
3140
 
3263
3141
  ret = TempMapping()
3264
3142
  ret.node_mapping = mapping_inner.node_mapping
code_loader/leaploader.py CHANGED
@@ -60,38 +60,14 @@ class LeapLoader(LeapLoaderBase):
60
60
 
61
61
  @lru_cache()
62
62
  def exec_script(self) -> None:
63
- from code_loader.inner_leap_binder import leapbinder_decorators as _leap_dec
64
63
  try:
65
64
  os.environ[mapping_runtime_mode_env_var_mame] = 'TRUE'
66
65
  self.evaluate_module()
67
-
68
- # A grouped integration test may index a grouped input/gt (image_list[i]) to wire a
69
- # single sample of a group; that indexing is only valid when the mapping graph is
70
- # built in grouped mode. Detect grouped-ness so the placeholder pass below matches
71
- # the dataset. Preprocess is stubbed while mapping mode is on, so run it with mapping
72
- # mode momentarily disabled, and cache it so _preprocess_result() doesn't re-run it.
73
- is_grouped = False
74
- if global_leap_binder.integration_test_func is not None:
75
- del os.environ[mapping_runtime_mode_env_var_mame]
76
- try:
77
- preprocess_result = global_leap_binder.get_preprocess_result()
78
- self._preprocess_result_cached = preprocess_result
79
- is_grouped = any(r.is_grouped for r in preprocess_result.values())
80
- except Exception:
81
- is_grouped = False
82
- finally:
83
- os.environ[mapping_runtime_mode_env_var_mame] = 'TRUE'
84
-
85
- _leap_dec._mapping_dataset_is_grouped = is_grouped
86
66
  if global_leap_binder.integration_test_func is not None:
87
67
  from code_loader.inner_leap_binder.leapbinder_decorators import \
88
68
  _reset_model_loop_state
89
69
  _reset_model_loop_state()
90
- mapping_preprocess = (
91
- PreprocessResponse(sample_ids=[["__mapping_placeholder__"]], state=DataStateType.training)
92
- if is_grouped else
93
- PreprocessResponse(state=DataStateType.training, length=0))
94
- global_leap_binder.integration_test_func(None, mapping_preprocess)
70
+ global_leap_binder.integration_test_func(None, PreprocessResponse(state=DataStateType.training, length=0))
95
71
  except TypeError as e:
96
72
  import traceback
97
73
  global_leap_binder.setup_container = DatasetIntegrationSetup()
@@ -104,7 +80,6 @@ class LeapLoader(LeapLoaderBase):
104
80
  raise DatasetScriptException(getattr(e, 'message', repr(e))) from e
105
81
  finally:
106
82
  # ensure that the environment variable is removed after the script execution
107
- _leap_dec._mapping_dataset_is_grouped = False
108
83
  if mapping_runtime_mode_env_var_mame in os.environ:
109
84
  del os.environ[mapping_runtime_mode_env_var_mame]
110
85
 
@@ -234,7 +209,7 @@ class LeapLoader(LeapLoaderBase):
234
209
  additional = self._preprocess_result().get(DataStateEnum.additional)
235
210
  if additional is None:
236
211
  return set()
237
- return set(additional.flat_sample_ids)
212
+ return set(additional.sample_ids)
238
213
 
239
214
  def _resolve_synthetic(self, sample_id: Union[int, str],
240
215
  state: Optional[DataStateEnum] = None
@@ -275,20 +250,12 @@ class LeapLoader(LeapLoaderBase):
275
250
  )
276
251
 
277
252
  preprocess_result = self._preprocess_result()
278
- if state == DataStateEnum.unlabeled and sample_id not in preprocess_result[state].flat_sample_ids:
253
+ if state == DataStateEnum.unlabeled and sample_id not in preprocess_result[state].sample_ids:
279
254
  self._preprocess_result(update_unlabeled_preprocess=True)
280
255
 
281
256
  metadata, metadata_is_none = self.get_metadata(state, sample_id)
282
257
 
283
- custom_latent_space = None
284
- if global_leap_binder.setup_container.custom_latent_space is not None:
285
- latent_fn = global_leap_binder.setup_container.custom_latent_space.function
286
- preprocess_state = preprocess_result[state]
287
- if preprocess_state.is_grouped:
288
- group_ids, pos = self._locate_group(preprocess_state, sample_id)
289
- custom_latent_space = self._to_grouped_list(latent_fn(group_ids, preprocess_state))[pos]
290
- else:
291
- custom_latent_space = latent_fn(sample_id, preprocess_state)
258
+ custom_latent_spaces = self._get_custom_latent_spaces(sample_id, preprocess_result[state])
292
259
  instance_mask = self._get_instances_masks(state, sample_id, instance_id)
293
260
  sample = DatasetSample(inputs=self._get_inputs(state, sample_id),
294
261
  gt=None if state == DataStateEnum.unlabeled else self._get_gt(state, sample_id),
@@ -296,7 +263,7 @@ class LeapLoader(LeapLoaderBase):
296
263
  metadata_is_none=metadata_is_none,
297
264
  index=sample_id,
298
265
  state=state,
299
- custom_latent_space=custom_latent_space,
266
+ custom_latent_spaces=custom_latent_spaces,
300
267
  instance_masks=instance_mask)
301
268
  return sample
302
269
 
@@ -327,11 +294,7 @@ class LeapLoader(LeapLoaderBase):
327
294
  handler.name, handler_result
328
295
  )
329
296
 
330
- custom_latent_space = None
331
- if global_leap_binder.setup_container.custom_latent_space is not None:
332
- custom_latent_space = global_leap_binder.setup_container.custom_latent_space.function(
333
- original_sample_id, preprocess
334
- )
297
+ custom_latent_spaces = self._get_custom_latent_spaces(original_sample_id, preprocess)
335
298
 
336
299
  return DatasetSample(
337
300
  inputs=inputs,
@@ -340,7 +303,7 @@ class LeapLoader(LeapLoaderBase):
340
303
  metadata_is_none=metadata_is_none,
341
304
  index=synthetic_index,
342
305
  state=DataStateEnum.additional,
343
- custom_latent_space=custom_latent_space,
306
+ custom_latent_spaces=custom_latent_spaces,
344
307
  instance_masks=None,
345
308
  )
346
309
 
@@ -419,7 +382,7 @@ class LeapLoader(LeapLoaderBase):
419
382
  if self.get_sample_id_type() is str:
420
383
  max_allowed_item_size = np.dtype('<U256').itemsize
421
384
  for state, preprocess_response in preprocess_result.items():
422
- sample_ids_array = np.array(preprocess_response.flat_sample_ids)
385
+ sample_ids_array = np.array(preprocess_response.sample_ids)
423
386
  if sample_ids_array.dtype.itemsize > max_allowed_item_size:
424
387
  raise Exception(f"Sample id are too long. Max allowed length is 256 charecters.")
425
388
 
@@ -515,10 +478,7 @@ class LeapLoader(LeapLoaderBase):
515
478
  if preprocess_response.sample_ids_to_instance_mappings:
516
479
  raise Exception('Element instances are not supported together with '
517
480
  'tensorleap_autoregressive_step.')
518
- # Grouped preprocess is fine: grouping only amortizes the shared base reads
519
- # (GT/metadata/custom_latent) — the AR hook always drives a single scalar chain
520
- # and is never handed a group.
521
- sample_id = preprocess_response.flat_sample_ids[0]
481
+ sample_id = preprocess_response.sample_ids[0]
522
482
  first_result = handler.function(sample_id, None, None, None, preprocess_response)
523
483
  second_result = handler.function(sample_id, None, None, None, preprocess_response)
524
484
  if not isinstance(first_result, tuple) or len(first_result) != 2:
@@ -599,7 +559,7 @@ class LeapLoader(LeapLoaderBase):
599
559
  if handler.input_shapes is None:
600
560
  preprocess_result = self._preprocess_result()
601
561
  first_state_response = next(iter(preprocess_result.values()))
602
- first_sample_id = first_state_response.flat_sample_ids[0]
562
+ first_sample_id = first_state_response.sample_ids[0]
603
563
  first_result = handler.function(first_sample_id, None, None, None,
604
564
  first_state_response)
605
565
  if not isinstance(first_result, tuple) or len(first_result) != 2 or \
@@ -938,57 +898,6 @@ class LeapLoader(LeapLoaderBase):
938
898
 
939
899
  return sample_ids
940
900
 
941
- @staticmethod
942
- def _grouped_dict_keys(rows: List[Dict[str, Any]], handler_name: str) -> List[str]:
943
- """Keys for a group of dict-metadata rows, requiring every row to share the same keys.
944
- A group must expose a uniform metadata schema; otherwise the per-key lists would silently
945
- drop or KeyError on rows that differ from row 0."""
946
- keys = list(rows[0].keys())
947
- key_set = set(keys)
948
- for pos, row in enumerate(rows):
949
- if set(row.keys()) != key_set:
950
- raise ValueError(
951
- f"Metadata handler {handler_name!r} returned inconsistent dict keys across the "
952
- f"group: row 0 has {sorted(key_set)} but row {pos} has {sorted(row.keys())}. "
953
- f"All rows in a group must share the same metadata keys.")
954
- return keys
955
-
956
- @staticmethod
957
- def _to_grouped_list(raw: Any) -> List[npt.NDArray[np.float32]]:
958
- """Normalize a grouped encoder result to a list of per-sample arrays.
959
-
960
- Grouped results are NEVER stacked into a (B, *) batch. Grouping is only a storage
961
- read-unit (one file load per group); assembling the model batch (B) is the engine's
962
- single responsibility, so it stays the only place samples get batched. Keeping
963
- per-sample arrays lets the engine batch to any B — including a B=1-only model — without
964
- an intermediate stack/unstack. A user encoder that already returned a stacked (B, *)
965
- array is split back into its per-sample rows so the contract is a list either way."""
966
- if isinstance(raw, list):
967
- return raw
968
- return [row for row in np.asarray(raw)]
969
-
970
- def _locate_group(self, preprocess_state: PreprocessResponse,
971
- sample_id: Union[int, str]) -> Tuple[List[Union[int, str]], int]:
972
- """Map a sample id to (its group, its position in that group). Cached on the
973
- PreprocessResponse itself (not keyed by id() on this loader) so grouped single-sample
974
- fetches don't rescan the groups, and the cache can never go stale: when the response is
975
- replaced (e.g. unlabeled preprocess refresh), the old object and its cache are simply
976
- discarded together instead of lingering under a possibly-reused id()."""
977
- mapping = preprocess_state._group_pos_cache
978
- if mapping is None:
979
- mapping = {}
980
- for group in preprocess_state.groups:
981
- for pos, sid in enumerate(group):
982
- if sid in mapping:
983
- raise ValueError(
984
- f"Duplicate sample id {sid!r} across groups in the preprocess response; "
985
- f"sample ids must be unique within and across groups.")
986
- mapping[sid] = (group, pos)
987
- preprocess_state._group_pos_cache = mapping
988
- if sample_id not in mapping:
989
- raise KeyError(f"Sample id {sample_id!r} is not present in any group of this preprocess response.")
990
- return mapping[sample_id]
991
-
992
901
  def _get_dataset_handlers(self, handlers: Iterable[DatasetBaseHandler],
993
902
  state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, npt.NDArray[np.float32]]:
994
903
  result_agg = {}
@@ -1000,100 +909,12 @@ class LeapLoader(LeapLoaderBase):
1000
909
  sample_id = original_local_id
1001
910
  else:
1002
911
  preprocess_state = preprocess_result[state]
1003
- if preprocess_state.is_grouped:
1004
- # Grouped dataset: call the encoder once with the whole group, index out the sample.
1005
- group_ids, pos = self._locate_group(preprocess_state, sample_id)
1006
- for handler in handlers:
1007
- grouped = self._to_grouped_list(handler.function(group_ids, preprocess_state))
1008
- result_agg[handler.name] = grouped[pos]
1009
- return result_agg
1010
912
  for handler in handlers:
1011
913
  handler_result = handler.function(sample_id, preprocess_state)
1012
914
  handler_name = handler.name
1013
915
  result_agg[handler_name] = handler_result
1014
916
  return result_agg
1015
917
 
1016
- def get_samples(self, state: DataStateEnum, group_ids: List[Union[int, str]]) -> DatasetSample:
1017
- """Group-aware fetch: hand the whole group to each encoder in a single call and return a
1018
- grouped DatasetSample (inputs/gt as per-sample lists of length B, metadata as per-key lists
1019
- of length B, index = the group). Grouped results are never stacked here — batching the
1020
- samples into the model's B is the engine's job. This is the path a group-aware engine calls
1021
- to read a file once per group. Row order matches group_ids exactly."""
1022
- self.exec_script()
1023
- preprocess_result = self._preprocess_result()
1024
- if state == DataStateEnum.unlabeled and any(
1025
- sid not in preprocess_result[state].flat_sample_ids for sid in group_ids):
1026
- # Mirrors get_sample's refresh: the unlabeled preprocess can grow between calls, so a
1027
- # group_id absent from the current snapshot may just not have been generated yet.
1028
- self._preprocess_result(update_unlabeled_preprocess=True)
1029
- preprocess_state = preprocess_result[state]
1030
- assert preprocess_state.is_grouped, (
1031
- "get_samples is the group-aware fetch path and requires a grouped preprocess "
1032
- "response; call get_sample for a flat (non-grouped) dataset.")
1033
- # All requested ids must belong to a single group (one file). A cross-group request
1034
- # would force the encoder to load multiple files, defeating the one-load-per-group
1035
- # contract; partitioning a scattered request by group is the engine's responsibility.
1036
- distinct_groups = {id(self._locate_group(preprocess_state, sid)[0]) for sid in group_ids}
1037
- assert len(distinct_groups) == 1, (
1038
- f"get_samples received sample ids spanning {len(distinct_groups)} groups; a request "
1039
- f"must be confined to a single group. The engine partitions cross-group requests and "
1040
- f"issues one get_samples call per group.")
1041
- inputs = {handler.name: self._to_grouped_list(handler.function(group_ids, preprocess_state))
1042
- for handler in global_leap_binder.setup_container.inputs}
1043
- autoregressive_handler = global_leap_binder.setup_container.autoregressive_step
1044
- if autoregressive_handler is not None:
1045
- # AR integrations have no input encoders — the hook's first call supplies each
1046
- # chain's step-0 model inputs. The hook is strictly per-scalar-chain (never handed
1047
- # a group), so it is called once per flat id in the group and the per-sample results
1048
- # are collected into per-key lists of length B, matching the grouped (never-stacked)
1049
- # contract used for every other encoder here.
1050
- step_zero_per_sample = []
1051
- for sid in group_ids:
1052
- step_zero_result = autoregressive_handler.function(sid, None, None, None,
1053
- preprocess_state)
1054
- if not isinstance(step_zero_result, tuple) or len(step_zero_result) != 2 or \
1055
- not isinstance(step_zero_result[0], dict):
1056
- raise Exception(
1057
- 'The autoregressive step hook must return a (next_inputs, state) tuple '
1058
- f'with a dict of initial model inputs on its first call, got '
1059
- f'{type(step_zero_result)} for sample {sid}.')
1060
- self._validate_autoregressive_step_inputs(step_zero_result[0], sid)
1061
- step_zero_per_sample.append(step_zero_result[0])
1062
- for key in (step_zero_per_sample[0].keys() if step_zero_per_sample else []):
1063
- inputs[key] = [row[key] for row in step_zero_per_sample]
1064
- gt = None
1065
- if state != DataStateEnum.unlabeled:
1066
- gt = {handler.name: self._to_grouped_list(handler.function(group_ids, preprocess_state))
1067
- for handler in global_leap_binder.setup_container.ground_truths}
1068
-
1069
- metadata: Dict[str, Any] = {}
1070
- metadata_is_none: Dict[str, Any] = {}
1071
- for handler in global_leap_binder.setup_container.metadata:
1072
- rows = handler.function(group_ids, preprocess_state) # list of B scalars/dicts
1073
- if rows and isinstance(rows[0], dict):
1074
- for key in self._grouped_dict_keys(rows, handler.name):
1075
- name = "{}_{}".format(handler.name, key)
1076
- converted = [self._convert_metadata_to_correct_type(name, row[key]) for row in rows]
1077
- metadata[name] = [v for v, _ in converted]
1078
- metadata_is_none[name] = [is_none for _, is_none in converted]
1079
- else:
1080
- converted = [self._convert_metadata_to_correct_type(handler.name, row) for row in rows]
1081
- metadata[handler.name] = [v for v, _ in converted]
1082
- metadata_is_none[handler.name] = [is_none for _, is_none in converted]
1083
-
1084
- # custom_latent_space is group-aware like the input/GT encoders: hand it the whole group in a
1085
- # single call so a file-backed latent fn loads the file once, and normalize to (B, d). This
1086
- # keeps the mandatory group path non-lossy. instance_masks stay None here: they are a
1087
- # per-(sample, instance) concern that needs an instance_id the group fetch does not carry.
1088
- custom_latent_space = None
1089
- if global_leap_binder.setup_container.custom_latent_space is not None:
1090
- latent_fn = global_leap_binder.setup_container.custom_latent_space.function
1091
- custom_latent_space = self._to_grouped_list(latent_fn(group_ids, preprocess_state))
1092
-
1093
- return DatasetSample(inputs=inputs, gt=gt, metadata=metadata, metadata_is_none=metadata_is_none,
1094
- index=list(group_ids), state=state, custom_latent_space=custom_latent_space,
1095
- instance_masks=None)
1096
-
1097
918
  def _get_inputs(self, state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, npt.NDArray[np.float32]]:
1098
919
  inputs = self._get_dataset_handlers(global_leap_binder.setup_container.inputs, state, sample_id)
1099
920
  autoregressive_handler = global_leap_binder.setup_container.autoregressive_step
@@ -1197,18 +1018,12 @@ class LeapLoader(LeapLoaderBase):
1197
1018
  sample_id = original_local_id
1198
1019
  else:
1199
1020
  preprocess_state = preprocess_result[state]
1200
- group_ids, pos = (None, None)
1201
- if preprocess_state.is_grouped:
1202
- group_ids, pos = self._locate_group(preprocess_state, sample_id)
1203
1021
  for handler in global_leap_binder.setup_container.metadata:
1204
1022
  if requested_metadata_names:
1205
1023
  if not is_metadata_name_starts_with_handler_name(handler):
1206
1024
  continue
1207
1025
 
1208
- if preprocess_state.is_grouped:
1209
- handler_result = handler.function(group_ids, preprocess_state)[pos]
1210
- else:
1211
- handler_result = handler.function(sample_id, preprocess_state)
1026
+ handler_result = handler.function(sample_id, preprocess_state)
1212
1027
  if isinstance(handler_result, dict):
1213
1028
  for single_metadata_name, single_metadata_result in handler_result.items():
1214
1029
  handler_name = f'{handler.name}_{single_metadata_name}'
@@ -1227,66 +1042,6 @@ class LeapLoader(LeapLoaderBase):
1227
1042
 
1228
1043
  return result_agg, is_none
1229
1044
 
1230
- def _grouped_metadata_for_group(self, preprocess_state: PreprocessResponse,
1231
- group_ids: List[Union[int, str]],
1232
- requested_metadata_names: Optional[List[str]]
1233
- ) -> Tuple[Dict[str, List[Any]], Dict[str, List[bool]]]:
1234
- def is_wanted(_handler):
1235
- if not requested_metadata_names:
1236
- return True
1237
- for metadata_name in requested_metadata_names:
1238
- if metadata_name.startswith(_handler.name + '_') or metadata_name == _handler.name:
1239
- return True
1240
- return False
1241
-
1242
- results: Dict[str, List[Any]] = {}
1243
- is_none: Dict[str, List[bool]] = {}
1244
- for handler in global_leap_binder.setup_container.metadata:
1245
- if requested_metadata_names and not is_wanted(handler):
1246
- continue
1247
- rows = handler.function(group_ids, preprocess_state)
1248
- if rows and isinstance(rows[0], dict):
1249
- for key in self._grouped_dict_keys(rows, handler.name):
1250
- name = f'{handler.name}_{key}'
1251
- if requested_metadata_names and name not in requested_metadata_names:
1252
- continue
1253
- converted = [self._convert_metadata_to_correct_type(name, row[key]) for row in rows]
1254
- results[name] = [v for v, _ in converted]
1255
- is_none[name] = [n for _, n in converted]
1256
- else:
1257
- name = handler.name
1258
- if requested_metadata_names and name not in requested_metadata_names:
1259
- continue
1260
- converted = [self._convert_metadata_to_correct_type(name, row) for row in rows]
1261
- results[name] = [v for v, _ in converted]
1262
- is_none[name] = [n for _, n in converted]
1263
- return results, is_none
1264
-
1265
- def get_metadata_multiple_samples(self, state: DataStateEnum, sample_ids: Union[List[int], List[str]],
1266
- requested_metadata_names: Optional[List[str]] = None
1267
- ) -> Tuple[Dict[str, Union[List[str], List[int], List[bool], List[float]]],
1268
- Dict[str, List[bool]]]:
1269
- preprocess_state = self._preprocess_result().get(state)
1270
- if preprocess_state is None or not preprocess_state.is_grouped:
1271
- return super().get_metadata_multiple_samples(state, sample_ids, requested_metadata_names)
1272
-
1273
- sample_id_type = self.get_sample_id_type()
1274
- aggregated_results: Dict[str, List[Any]] = {}
1275
- aggregated_is_none: Dict[str, List[bool]] = {}
1276
- group_cache: Dict[int, Tuple[Dict[str, List[Any]], Dict[str, List[bool]]]] = {}
1277
- for sample_id in sample_ids:
1278
- sample_id = sample_id_type(sample_id)
1279
- group_ids, pos = self._locate_group(preprocess_state, sample_id)
1280
- key = id(group_ids)
1281
- if key not in group_cache:
1282
- group_cache[key] = self._grouped_metadata_for_group(
1283
- preprocess_state, group_ids, requested_metadata_names)
1284
- group_results, group_is_none = group_cache[key]
1285
- for name, values in group_results.items():
1286
- aggregated_results.setdefault(name, []).append(values[pos])
1287
- aggregated_is_none.setdefault(name, []).append(group_is_none[name][pos])
1288
- return aggregated_results, aggregated_is_none
1289
-
1290
1045
  @lru_cache()
1291
1046
  def get_sample_id_type(self) -> Type:
1292
1047
  preprocess_results = list(self._preprocess_result().values())
@@ -1297,10 +1052,29 @@ class LeapLoader(LeapLoaderBase):
1297
1052
 
1298
1053
  return id_type
1299
1054
 
1055
+ @staticmethod
1056
+ def _get_custom_latent_spaces(
1057
+ sample_id: Union[int, str],
1058
+ preprocess: "PreprocessResponse") -> Optional[Dict[str, npt.NDArray[np.float32]]]:
1059
+ handlers = global_leap_binder.setup_container.custom_latent_spaces
1060
+ if not handlers:
1061
+ return None
1062
+ return {name: handler.function(sample_id, preprocess) for name, handler in handlers.items()}
1063
+
1300
1064
  @lru_cache()
1301
1065
  def has_custom_latent_space_decorator(self) -> bool:
1302
1066
  self.exec_script()
1303
- return global_leap_binder.setup_container.custom_latent_space is not None
1067
+ return len(global_leap_binder.setup_container.custom_latent_spaces) > 0
1068
+
1069
+ @lru_cache()
1070
+ def get_custom_latent_space_names(self) -> Tuple[str, ...]:
1071
+ """Ordered names of all registered custom latent spaces.
1072
+
1073
+ Registration order is the canonical index mapping consumed by the engine
1074
+ (name i -> user_custom_i). Returns a tuple so the lru_cache value is hashable.
1075
+ """
1076
+ self.exec_script()
1077
+ return tuple(global_leap_binder.setup_container.custom_latent_spaces.keys())
1304
1078
 
1305
1079
  @lru_cache()
1306
1080
  def has_autoregressive_step(self) -> bool:
@@ -218,6 +218,10 @@ class LeapLoaderBase:
218
218
  raise NotImplementedError(f'{type(self).__name__} does not implement '
219
219
  'autoregressive_visualizer_by_name.')
220
220
 
221
+ @abstractmethod
222
+ def get_custom_latent_space_names(self) -> Tuple[str, ...]:
223
+ pass
224
+
221
225
  @abstractmethod
222
226
  def get_heatmap_visualizer_raw_vis_input_arg_name(self, visualizer_name: str) -> Optional[str]:
223
227
  pass
code_loader/utils.py CHANGED
@@ -1,4 +1,6 @@
1
+ import io
1
2
  import math
3
+ import pickle
2
4
  import sys
3
5
  from pathlib import Path
4
6
  from types import TracebackType
@@ -15,11 +17,6 @@ from code_loader.contract.enums import DatasetMetadataType
15
17
  def to_numpy_return_wrapper(encoder_function: SectionCallableInterface) -> SectionCallableInterface:
16
18
  def numpy_encoder_function(idx: Union[int, str], samples: PreprocessResponse) -> npt.NDArray[np.float32]:
17
19
  result = encoder_function(idx, samples)
18
- if isinstance(result, list) and len(result) > 0 and all(isinstance(sample, np.ndarray) for sample in result):
19
- # A list of per-sample arrays only comes from a grouped encoder (a flat encoder returns
20
- # a single array). Never stack it into a (B, *) batch — grouping is only a storage
21
- # read-unit; batching the group to the model's B is the engine's single responsibility.
22
- return result
23
20
  numpy_result: npt.NDArray[np.float32] = np.array(result)
24
21
  return numpy_result
25
22
 
@@ -109,27 +106,31 @@ def get_metadata_type_from_variable(variable: Union[Optional[str], int, bool, Op
109
106
 
110
107
 
111
108
 
112
- AUTOREGRESSIVE_STATE_LEAF_TYPES = (np.ndarray, np.generic, int, float, str, bool, type(None))
109
+ # The platform queue transports state as pickled payloads which the engine deserializes
110
+ # WITHOUT the integration code loaded, so a class defined in the user's modules round-trips
111
+ # locally but crashes on the engine. Only modules importable on the engine may resolve.
112
+ _STATE_SAFE_PICKLE_MODULES = ('builtins', 'copyreg', 'collections', 'numpy', 'datetime')
113
+
114
+
115
+ class _EngineSafeUnpickler(pickle.Unpickler):
116
+ def find_class(self, module: str, name: str) -> Any:
117
+ if module.split('.')[0] in _STATE_SAFE_PICKLE_MODULES:
118
+ return super().find_class(module, name)
119
+ raise pickle.UnpicklingError(
120
+ f'{module}.{name} is defined in integration code, which is not importable on the '
121
+ f'platform engine')
113
122
 
114
123
 
115
124
  def validate_autoregressive_state_types(value: Any, path: str = 'state') -> None:
116
- if isinstance(value, dict):
117
- for key, item in value.items():
118
- if not isinstance(key, str):
119
- raise AssertionError(
120
- f'autoregressive state validation failed: dict key {key!r} at {path} must be '
121
- f'a string. Got {type(key).__name__}.')
122
- validate_autoregressive_state_types(item, f'{path}[{key!r}]')
123
- return
124
- if isinstance(value, (list, tuple)):
125
- for i, item in enumerate(value):
126
- validate_autoregressive_state_types(item, f'{path}[{i}]')
127
- return
128
- if not isinstance(value, AUTOREGRESSIVE_STATE_LEAF_TYPES):
125
+ try:
126
+ _EngineSafeUnpickler(io.BytesIO(pickle.dumps(value))).load()
127
+ except Exception as e:
129
128
  raise AssertionError(
130
- f'autoregressive state validation failed: {path} holds a {type(value).__name__}. '
131
- f'State must be built only from numpy arrays, numbers, strings, bools and nests of '
132
- f'dicts/lists of thoseit is serialized to the platform queue on every chain step.')
129
+ f'autoregressive state validation failed: {path} is not serializable ({e}). State '
130
+ 'is serialized to the platform queue on every chain step and deserialized without '
131
+ 'the integration codeany picklable nest of builtin/numpy values works (dicts, '
132
+ 'lists, tuples, sets, numbers, strings, arrays), but user-defined classes, lambdas '
133
+ 'and open resources do not.') from e
133
134
 
134
135
 
135
136
  def autoregressive_nests_equal(a: Any, b: Any) -> bool:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.196.dev0
3
+ Version: 1.0.197.dev0
4
4
  Summary:
5
5
  Home-page: https://github.com/tensorleap/code-loader
6
6
  License: MIT
@@ -1,7 +1,7 @@
1
1
  LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
2
2
  code_loader/__init__.py,sha256=outxRQ0M-zMfV0QGVJmAed5qWfRmyD0TV6-goEGAzBw,406
3
3
  code_loader/contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- code_loader/contract/datasetclasses.py,sha256=CX4HO3xiuBUiXaeSBEyjAFV7i1NGS7KZ3JnLGxofH28,16164
4
+ code_loader/contract/datasetclasses.py,sha256=rKitPlVyI9PZdAZHpH1q-0_s4Vs7oPg8Z659XeuAujM,13788
5
5
  code_loader/contract/enums.py,sha256=2q-IV_5g9lLE306DIbWA1c0tn5IhDtxsKxyV1x_Lreg,1671
6
6
  code_loader/contract/exceptions.py,sha256=jWqu5i7t-0IG0jGRsKF4DjJdrsdpJjIYpUkN1F4RiyQ,51
7
7
  code_loader/contract/mapping.py,sha256=sWJhpng-IkOzQnWQdMT5w2ZZ3X1Z_OOzSwCLXIS7oxE,1446
@@ -21,18 +21,18 @@ code_loader/experiment_api/types.py,sha256=MY8xFARHwdVA7p4dxyhD60ShmttgTvb4qdp1o
21
21
  code_loader/experiment_api/utils.py,sha256=XZHtxge12TS4H4-8PjV3sKuhp8Ud6ojAiIzTZJEqBqc,3304
22
22
  code_loader/experiment_api/workingspace_config_utils.py,sha256=DLzXQCg4dgTV_YgaSbeTVzq-2ja_SQw4zi7LXwKL9cY,990
23
23
  code_loader/inner_leap_binder/__init__.py,sha256=koOlJyMNYzGbEsoIbXathSmQ-L38N_pEXH_HvL7beXU,99
24
- code_loader/inner_leap_binder/leapbinder.py,sha256=hTkOL-JLtIQSaCqg8EVxnWWaHMbChrnTkgrT1Tj5AxE,54488
25
- code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=1zKGCW-TgC9AYv8oc_jEplIVlnpJEwqM9o2IpGxOwTI,183070
26
- code_loader/leaploader.py,sha256=k1yfKV6SBqxggUp3Yw1sNGfd50xsCaNb8-CXBsgsVY8,83459
27
- code_loader/leaploaderbase.py,sha256=PvBU_2OQqBfJLDMsbK1s372954eYr4Y3O4r18y5S7uY,10739
24
+ code_loader/inner_leap_binder/leapbinder.py,sha256=52nLuWLbOU7ljlABRRuS-e-hKscVlR5zxJTm5FPBdk8,54073
25
+ code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=tW8QmjzkloQU37xryr958aVwyrVOm2FoSFL1LH0S8EU,176272
26
+ code_loader/leaploader.py,sha256=0YZhh2dCouQMCQAakqaPa-nRNrNn65q4rrLTwC8yjE0,68695
27
+ code_loader/leaploaderbase.py,sha256=MMuMv2014d9VM5FQgTsbUBL-9HOBJ4h6L67uF_7jhR4,10837
28
28
  code_loader/mixpanel_tracker.py,sha256=rNwRmFifNbdUoqLQvvhhgpKczWpWiEmd8MfyJe27sxw,9131
29
29
  code_loader/plot_functions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
30
30
  code_loader/plot_functions/plot_functions.py,sha256=2DC-zlVaN13P4VNx5d8csgs80C6SisaeP1-Kq2LW7iM,16075
31
31
  code_loader/plot_functions/visualize.py,sha256=gsBAYYkwMh7jIpJeDMPS8G4CW-pxwx6LznoQIvi4vpo,657
32
- code_loader/utils.py,sha256=mt1V191TL-6goWPnsqjW76wffGFGNdx8xdQ0J4ZT9bU,6779
32
+ code_loader/utils.py,sha256=gEJCKpDWf6p9_KoEz-0EGiJqxD6QfPgZN6zdKdtSAz8,6628
33
33
  code_loader/visualizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
34
  code_loader/visualizers/default_visualizers.py,sha256=onRnLE_TXfgLN4o52hQIOOhUcFexGlqJ3xSpQDVLuZM,2604
35
- code_loader-1.0.196.dev0.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
36
- code_loader-1.0.196.dev0.dist-info/METADATA,sha256=okTBjK87MBiyLc7eEgcuXgtl2XjCMCk_FSOtBTAnXQw,1095
37
- code_loader-1.0.196.dev0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
38
- code_loader-1.0.196.dev0.dist-info/RECORD,,
35
+ code_loader-1.0.197.dev0.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
36
+ code_loader-1.0.197.dev0.dist-info/METADATA,sha256=WZ4kCsTIDPch7g1xrPJ5fy1EHEQoRGz9q_iygXHTM4s,1095
37
+ code_loader-1.0.197.dev0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
38
+ code_loader-1.0.197.dev0.dist-info/RECORD,,