code-loader 1.0.193.dev3__py3-none-any.whl → 1.0.193.dev5__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,4 @@
1
1
  # mypy: ignore-errors
2
- import copy
3
- import hashlib
4
2
  import inspect
5
3
  import os
6
4
  import warnings
@@ -15,8 +13,7 @@ from typing import Optional, Union, Callable, List, Dict, get_args, get_origin,
15
13
  import numpy as np
16
14
  import numpy.typing as npt
17
15
 
18
- from code_loader.utils import get_metadata_type_from_variable, map_dict_to_metadata_types, \
19
- validate_autoregressive_state_types, autoregressive_nests_equal
16
+ from code_loader.utils import get_metadata_type_from_variable, map_dict_to_metadata_types
20
17
 
21
18
  logger = logging.getLogger(__name__)
22
19
 
@@ -29,17 +26,13 @@ from code_loader.contract.enums import MetricDirection, LeapDataType, DatasetMet
29
26
  from code_loader import leap_binder, LeapLoader
30
27
  from code_loader.contract.mapping import NodeMapping, NodeMappingType, NodeConnection
31
28
  from code_loader.contract.visualizer_classes import LeapImage, LeapImageMask, LeapTextMask, LeapText, LeapGraph, \
32
- LeapHorizontalBar, LeapImageWithBBox, LeapImageWithHeatmap, LeapVideo, LeapValidationError, \
33
- map_leap_data_type_to_visualizer_class
29
+ LeapHorizontalBar, LeapImageWithBBox, LeapImageWithHeatmap, LeapVideo, LeapValidationError
34
30
  from code_loader.inner_leap_binder.leapbinder import mapping_runtime_mode_env_var_mame
35
31
  from code_loader.mixpanel_tracker import clear_integration_events, AnalyticsEvent, emit_integration_event_once
36
32
 
37
33
  _called_from_inside_tl_decorator = 0
38
34
  _called_from_inside_tl_integration_test_decorator = False
39
- # Whether any integration test wrapper was entered in this process. The crash reporter uses it
40
- # to tell a raise in the test body (report as code-flow failure) from a module-level crash
41
- # before any test ran (report as a plain script crash).
42
- _integration_test_started = False
35
+ _mapping_dataset_is_grouped = False
43
36
  _call_from_tl_platform = os.environ.get('IS_TENSORLEAP_PLATFORM') == 'true'
44
37
 
45
38
  # ---- warnings store (module-level) ----
@@ -213,6 +206,50 @@ def batch_warning(result, func_name):
213
206
  )
214
207
 
215
208
 
209
+ def _validate_id_or_group(sample_id, preprocess_response, func_name):
210
+ """Accept either a single sample id (flat dataset) or a group — a list of ids (grouped
211
+ dataset). The argument shape must match the dataset: a group requires a grouped
212
+ PreprocessResponse and a single id requires a flat one. Every id must match the declared
213
+ sample_id_type."""
214
+ is_group = isinstance(sample_id, list)
215
+ if is_group and not preprocess_response.is_grouped:
216
+ raise AssertionError(
217
+ f'{func_name}() validation failed: got a group (list of sample ids) but the '
218
+ f'PreprocessResponse is not grouped. Pass a single sample id for a flat dataset.')
219
+ if not is_group and preprocess_response.is_grouped:
220
+ raise AssertionError(
221
+ f'{func_name}() validation failed: got a single sample id but the PreprocessResponse '
222
+ f'is grouped. Pass a group (list of sample ids) for a grouped dataset.')
223
+ ids = sample_id if is_group else [sample_id]
224
+ for sid in ids:
225
+ assert type(sid) == preprocess_response.sample_id_type, \
226
+ (f'{func_name}() validation failed: '
227
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
228
+ f'{preprocess_response.sample_id_type}. Got {type(sid)}.')
229
+
230
+
231
+ def _validate_grouped_result(result, group_size, func_name, validate_single):
232
+ """A grouped (group) encoder result must be either a single ndarray with leading dim
233
+ == group_size, or a list of `group_size` per-sample results (each validated by
234
+ validate_single). Metadata validates its grouped result separately (list only)."""
235
+ if isinstance(result, np.ndarray):
236
+ assert len(result.shape) > 0 and result.shape[0] == group_size, \
237
+ (f'{func_name}() validation failed: expected a grouped output for a group of '
238
+ f'{group_size}: an array with leading dim {group_size}, got shape {result.shape}.')
239
+ validate_single(result)
240
+ elif isinstance(result, list):
241
+ assert len(result) == group_size, \
242
+ (f'{func_name}() validation failed: expected a grouped output for a group of '
243
+ f'{group_size}: a list of {group_size} arrays, got {len(result)}.')
244
+ for r in result:
245
+ validate_single(r)
246
+ else:
247
+ raise AssertionError(
248
+ f'{func_name}() validation failed: expected a grouped output for a group of '
249
+ f'{group_size}: either an array with leading dim {group_size} or a list of '
250
+ f'{group_size} arrays, got {type(result)}.')
251
+
252
+
216
253
  def _add_mapping_connection(user_unique_name, connection_destinations, arg_names, name, node_mapping_type):
217
254
  connection_destinations = [connection_destination for connection_destination in connection_destinations
218
255
  if not isinstance(connection_destination, SamplePreprocessResponse)]
@@ -290,21 +327,16 @@ def tensorleap_integration_test():
290
327
 
291
328
  def _validate_input_args(*args, **kwargs):
292
329
  sample_id, preprocess_response = args
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
- )
330
+ _validate_id_or_group(sample_id, preprocess_response, 'tensorleap_integration_test')
298
331
 
299
332
  def inner(*args, **kwargs):
300
333
  if not _call_from_tl_platform:
301
334
  set_current('tensorleap_integration_test')
302
- validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
335
+ validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
303
336
  func_name='integration_test', expected_names=["idx", "preprocess"], **kwargs)
304
337
  _validate_input_args(*args, **kwargs)
305
338
 
306
- global _called_from_inside_tl_integration_test_decorator, _integration_test_started
307
- _integration_test_started = True
339
+ global _called_from_inside_tl_integration_test_decorator
308
340
  # Clear integration test events for new test
309
341
  try:
310
342
  clear_integration_events()
@@ -315,12 +347,12 @@ def tensorleap_integration_test():
315
347
  if not _call_from_tl_platform:
316
348
  update_env_params_func("tensorleap_integration_test",
317
349
  "v") # put here because otherwise it will become v only if it finishes all the script
318
- _reset_model_loop_state()
319
350
  ret = integration_test_function(*args, **kwargs)
320
351
 
352
+ global _mapping_dataset_is_grouped
353
+ _mapping_dataset_is_grouped = args[1].is_grouped
321
354
  try:
322
355
  os.environ[mapping_runtime_mode_env_var_mame] = 'True'
323
- _reset_model_loop_state()
324
356
  integration_test_function(None, PreprocessResponse(state=DataStateType.training, length=0))
325
357
  except Exception as e:
326
358
  import traceback
@@ -338,6 +370,7 @@ def tensorleap_integration_test():
338
370
  f'Integration test is only allowed to call Tensorleap decorators. '
339
371
  f'Ensure any arithmetics, external library use, Python logic is placed within Tensorleap decoders')
340
372
  finally:
373
+ _mapping_dataset_is_grouped = False
341
374
  if mapping_runtime_mode_env_var_mame in os.environ:
342
375
  del os.environ[mapping_runtime_mode_env_var_mame]
343
376
  finally:
@@ -587,8 +620,6 @@ def tensorleap_load_model(prediction_types: Optional[List[PredictionTypeHandler]
587
620
  return self.model.get_inputs()
588
621
 
589
622
  model_placeholder = ModelPlaceholder(prediction_types)
590
- global _last_loaded_model
591
- _last_loaded_model = model_placeholder
592
623
  if not _call_from_tl_platform:
593
624
  update_env_params_func("tensorleap_load_model", "v")
594
625
  return model_placeholder
@@ -599,16 +630,8 @@ def tensorleap_load_model(prediction_types: Optional[List[PredictionTypeHandler]
599
630
  self.node_mapping = NodeMapping('', NodeMappingType.Prediction0)
600
631
 
601
632
  def __getitem__(self, key):
602
- assert isinstance(key, (int, str)), \
603
- f'Expected key to be an int or a prediction-type name, got {type(key)} instead.'
604
- if isinstance(key, str):
605
- declared_names = [prediction_type.name for prediction_type
606
- in leap_binder.setup_container.prediction_types]
607
- if key not in declared_names:
608
- raise Exception(
609
- f'Unknown prediction name "{key}" — declared prediction types: '
610
- f'{declared_names}.')
611
- key = declared_names.index(key)
633
+ assert isinstance(key, int), \
634
+ f'Expected key to be an int, got {type(key)} instead.'
612
635
 
613
636
  ret = TempMapping()
614
637
  try:
@@ -662,10 +685,7 @@ def tensorleap_load_model(prediction_types: Optional[List[PredictionTypeHandler]
662
685
 
663
686
  return FollowInputIndex()
664
687
 
665
- model_placeholder = ModelPlaceholder()
666
- global _last_loaded_model
667
- _last_loaded_model = model_placeholder
668
- return model_placeholder
688
+ return ModelPlaceholder()
669
689
 
670
690
  def final_inner(*args, **kwargs):
671
691
  if os.environ.get(mapping_runtime_mode_env_var_mame):
@@ -1542,13 +1562,10 @@ def tensorleap_metadata(
1542
1562
  raise Exception(f'Metadata with name {name} already exists. '
1543
1563
  f'Please choose another')
1544
1564
 
1545
- def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
1546
- assert type(sample_id) == preprocess_response.sample_id_type, \
1547
- (f'{user_function.__name__}() validation failed: '
1548
- f'Argument sample_id should be as the same type as defined in the preprocess response '
1549
- f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
1565
+ def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
1566
+ _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
1550
1567
 
1551
- def _validate_result(result):
1568
+ def _validate_single(result):
1552
1569
  supported_result_types = (type(None), int, str, bool, float, dict, np.floating,
1553
1570
  np.bool_, np.unsignedinteger, np.signedinteger, np.integer)
1554
1571
  if isinstance(result, tuple):
@@ -1566,6 +1583,20 @@ def tensorleap_metadata(
1566
1583
  (f'{user_function.__name__}() validation failed: '
1567
1584
  f'Values in the return dict should be of type {str(supported_result_types)}. Got {type(value)}.')
1568
1585
 
1586
+ def _validate_result(result, grouped=False, group_size=None):
1587
+ if not grouped:
1588
+ _validate_single(result)
1589
+ return
1590
+ # Grouped metadata: a list of `group_size` per-sample scalars/dicts.
1591
+ assert isinstance(result, list), \
1592
+ (f'{user_function.__name__}() validation failed: expected a grouped output for a group '
1593
+ f'of {group_size}: a list of {group_size} metadata values, got {type(result)}.')
1594
+ assert len(result) == group_size, \
1595
+ (f'{user_function.__name__}() validation failed: expected a grouped output for a group '
1596
+ f'of {group_size}: a list of {group_size} metadata values, got {len(result)}.')
1597
+ for value in result:
1598
+ _validate_single(value)
1599
+
1569
1600
  def inner_without_validate(sample_id, preprocess_response):
1570
1601
 
1571
1602
  global _called_from_inside_tl_decorator
@@ -1585,14 +1616,16 @@ def tensorleap_metadata(
1585
1616
  set_current('tensorleap_metadata')
1586
1617
  if os.environ.get(mapping_runtime_mode_env_var_mame):
1587
1618
  return None
1588
- validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
1619
+ validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
1589
1620
  func_name=user_function.__name__, expected_names=["idx", "preprocess"], **kwargs)
1590
1621
  sample_id, preprocess_response = args if len(args) != 0 else kwargs.values()
1591
1622
  _validate_input_args(sample_id, preprocess_response)
1592
1623
 
1624
+ grouped = isinstance(sample_id, list)
1625
+ group_size = len(sample_id) if grouped else None
1593
1626
  result = inner_without_validate(sample_id, preprocess_response)
1594
1627
 
1595
- _validate_result(result)
1628
+ _validate_result(result, grouped, group_size)
1596
1629
  if not _call_from_tl_platform:
1597
1630
  update_env_params_func("tensorleap_metadata", "v")
1598
1631
  return result
@@ -1604,35 +1637,50 @@ def tensorleap_metadata(
1604
1637
 
1605
1638
  def tensorleap_custom_latent_space():
1606
1639
  def decorating_function(user_function: SectionCallableInterface):
1607
- def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
1608
- assert isinstance(sample_id, (int, str)), \
1609
- (f'tensorleap_custom_latent_space validation failed: '
1610
- f'Argument sample_id should be either int or str. Got {type(sample_id)}.')
1611
- assert isinstance(preprocess_response, PreprocessResponse), \
1612
- (f'tensorleap_custom_latent_space validation failed: '
1613
- f'Argument preprocess_response should be a PreprocessResponse. Got {type(preprocess_response)}.')
1614
- assert type(sample_id) == preprocess_response.sample_id_type, \
1615
- (f'tensorleap_custom_latent_space validation failed: '
1616
- f'Argument sample_id should be as the same type as defined in the preprocess response '
1617
- f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
1640
+ def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
1641
+ _validate_id_or_group(sample_id, preprocess_response, 'tensorleap_custom_latent_space')
1618
1642
 
1619
- def _validate_result(result):
1620
- assert isinstance(result, np.ndarray), \
1643
+ def _validate_single(single_result):
1644
+ assert isinstance(single_result, np.ndarray), \
1621
1645
  (f'tensorleap_custom_latent_space validation failed: '
1622
- f'The return type should be a numpy array. Got {type(result)}.')
1623
- if result.ndim > 1:
1624
- flat_dim = int(np.prod(result.shape))
1646
+ f'The return type should be a numpy array. Got {type(single_result)}.')
1647
+ if single_result.ndim > 1:
1648
+ flat_dim = int(np.prod(single_result.shape))
1625
1649
  store_general_warning(
1626
- key=("tensorleap_custom_latent_space_flatten", tuple(result.shape)),
1650
+ key=("tensorleap_custom_latent_space_flatten", tuple(single_result.shape)),
1627
1651
  message=(
1628
- f"tensorleap_custom_latent_space returned per-sample shape {tuple(result.shape)} "
1629
- f"(ndim={result.ndim}). Tensorleap assumes per-sample shape (d, ...) and will "
1652
+ f"tensorleap_custom_latent_space returned per-sample shape {tuple(single_result.shape)} "
1653
+ f"(ndim={single_result.ndim}). Tensorleap assumes per-sample shape (d, ...) and will "
1630
1654
  f"flatten to ({flat_dim},) before downstream visualization and clustering. "
1631
1655
  f"If you want a different aggregation (e.g. global average pooling), do it "
1632
1656
  f"inside your function."
1633
1657
  ),
1634
1658
  )
1635
1659
 
1660
+ def _validate_result(result, grouped=False, group_size=None):
1661
+ if not grouped:
1662
+ _validate_single(result)
1663
+ return
1664
+ # Grouped: (B, *) array or list of B per-sample arrays. Validate each per-sample slice so
1665
+ # the per-sample flatten check/warning uses the sample shape, not the (B, *) batch shape.
1666
+ if isinstance(result, np.ndarray):
1667
+ assert result.ndim >= 1 and result.shape[0] == group_size, \
1668
+ (f'tensorleap_custom_latent_space validation failed: expected a grouped output for a '
1669
+ f'group of {group_size}: an array with leading dim {group_size}, got shape {result.shape}.')
1670
+ for single in result:
1671
+ _validate_single(single)
1672
+ elif isinstance(result, list):
1673
+ assert len(result) == group_size, \
1674
+ (f'tensorleap_custom_latent_space validation failed: expected a grouped output for a '
1675
+ f'group of {group_size}: a list of {group_size} arrays, got {len(result)}.')
1676
+ for single in result:
1677
+ _validate_single(single)
1678
+ else:
1679
+ raise AssertionError(
1680
+ f'tensorleap_custom_latent_space validation failed: expected a grouped output for a '
1681
+ f'group of {group_size}: either an array with leading dim {group_size} or a list of '
1682
+ f'{group_size} arrays, got {type(result)}.')
1683
+
1636
1684
  def inner_without_validate(sample_id, preprocess_response):
1637
1685
  global _called_from_inside_tl_decorator
1638
1686
  _called_from_inside_tl_decorator += 1
@@ -1652,9 +1700,11 @@ def tensorleap_custom_latent_space():
1652
1700
 
1653
1701
  _validate_input_args(sample_id, preprocess_response)
1654
1702
 
1703
+ grouped = isinstance(sample_id, list)
1704
+ group_size = len(sample_id) if grouped else None
1655
1705
  result = inner_without_validate(sample_id, preprocess_response)
1656
1706
 
1657
- _validate_result(result)
1707
+ _validate_result(result, grouped, group_size)
1658
1708
  return result
1659
1709
 
1660
1710
  return inner
@@ -1662,260 +1712,18 @@ def tensorleap_custom_latent_space():
1662
1712
  return decorating_function
1663
1713
 
1664
1714
 
1665
- _MODEL_LOOP_MAX_STEPS = 1000
1666
-
1667
- _active_model_loop = None
1668
- _model_loop_run_in_current_test = False
1669
- _last_loaded_model = None
1670
- _chain_artifact_provenance: Dict[int, tuple] = {}
1671
-
1672
- _validate_state_types = validate_autoregressive_state_types
1673
- _nest_equal = autoregressive_nests_equal
1674
-
1675
-
1676
- def _nest_fingerprint(value):
1677
- digest = hashlib.sha1()
1678
-
1679
- def _feed(item):
1680
- if isinstance(item, dict):
1681
- digest.update(b'{')
1682
- for key in sorted(item):
1683
- digest.update(str(key).encode())
1684
- digest.update(b':')
1685
- _feed(item[key])
1686
- digest.update(b'}')
1687
- elif isinstance(item, (list, tuple)):
1688
- digest.update(b'[')
1689
- for element in item:
1690
- _feed(element)
1691
- digest.update(b']')
1692
- elif isinstance(item, np.ndarray):
1693
- digest.update(str(item.dtype).encode())
1694
- digest.update(str(item.shape).encode())
1695
- digest.update(np.ascontiguousarray(item).tobytes())
1696
- else:
1697
- digest.update(repr(item).encode())
1698
-
1699
- _feed(value)
1700
- return digest.hexdigest()
1701
-
1702
-
1703
- def _ndarray_leaves(value):
1704
- if isinstance(value, np.ndarray):
1705
- return [value]
1706
- if isinstance(value, dict):
1707
- return [leaf for item in value.values() for leaf in _ndarray_leaves(item)]
1708
- if isinstance(value, (list, tuple)):
1709
- return [leaf for item in value for leaf in _ndarray_leaves(item)]
1710
- return []
1711
-
1712
-
1713
- def _squeeze_leading_batch_axis(tensors_dict):
1714
- squeezed = {}
1715
- for key, value in tensors_dict.items():
1716
- if isinstance(value, np.ndarray) and value.ndim > 0 and value.shape[0] == 1:
1717
- squeezed[key] = value[0]
1718
- else:
1719
- squeezed[key] = value
1720
- return squeezed
1721
-
1722
-
1723
- def _register_chain_artifact(obj, kind):
1724
- # The object reference is kept in the registry entry so its id() cannot be recycled by the GC.
1725
- _chain_artifact_provenance[id(obj)] = (kind, _nest_fingerprint(obj), obj)
1726
-
1727
-
1728
- def _lookup_chain_artifact(obj):
1729
- entry = _chain_artifact_provenance.get(id(obj))
1730
- if entry is None or entry[2] is not obj:
1731
- return None
1732
- return entry
1733
-
1734
-
1735
- def _reset_model_loop_state():
1736
- global _active_model_loop, _model_loop_run_in_current_test
1737
- _active_model_loop = None
1738
- _model_loop_run_in_current_test = False
1739
- _chain_artifact_provenance.clear()
1740
-
1741
-
1742
- class _MappingStatePlaceholder:
1743
- def _unsupported(self):
1744
- raise LeapValidationError(
1745
- 'The autoregressive state is opaque inside the integration test — pass it whole '
1746
- 'between the hook, the model loop and the autoregressive metrics. Read or derive '
1747
- 'state content inside the hook or inside the metric/visualizer body.')
1748
-
1749
- def __getitem__(self, key):
1750
- self._unsupported()
1751
-
1752
- def __getattr__(self, name):
1753
- raise AttributeError(name)
1754
-
1755
- def __iter__(self):
1756
- self._unsupported()
1757
-
1758
-
1759
- class _ModelLoopContext:
1760
- def __init__(self, sample_id, preprocess_response, prediction_names, is_mapping):
1761
- self.sample_id = sample_id
1762
- self.preprocess_response = preprocess_response
1763
- self.prediction_names = prediction_names
1764
- self.is_mapping = is_mapping
1765
- self.phase = 'awaiting_first_hook'
1766
- self.steps = 0
1767
- self.fed_inputs = None
1768
- self.fed_inputs_fingerprint = None
1769
- self.last_outputs = None
1770
- self.last_outputs_fingerprint = None
1771
- self.last_state = None
1772
- self.last_state_fingerprint = None
1773
-
1774
- def _fail(self, message):
1775
- raise LeapValidationError(f'tensorleap_model_loop validation failed: {message}')
1776
-
1777
- def on_hook_call(self, sample_id, prev_inputs, prev_outputs, state, preprocess_response):
1778
- if self.phase == 'ended':
1779
- self._fail('the chain already ended — once the autoregressive step returns None for '
1780
- 'next_inputs the loop must exit without further hook or model calls.')
1781
- if self.phase == 'awaiting_model':
1782
- self._fail('two autoregressive step calls in a row — the model must run exactly once '
1783
- 'between hook calls.')
1784
- if sample_id != self.sample_id:
1785
- self._fail('the hook must be called with the sample_id the model loop received.')
1786
- if preprocess_response is not self.preprocess_response:
1787
- self._fail('the hook must be called with the preprocess response the model loop '
1788
- 'received.')
1789
- if self.phase == 'awaiting_first_hook':
1790
- if prev_inputs is not None or prev_outputs is not None or state is not None:
1791
- self._fail('the first hook call inside the model loop must be the initial call: '
1792
- 'prev_inputs=None, prev_outputs=None, state=None.')
1793
- return
1794
- if prev_inputs is not self.fed_inputs:
1795
- self._fail('prev_inputs must be exactly the inputs dict the previous hook call '
1796
- 'returned (the one fed to the model) — do not copy, rebuild or slice it.')
1797
- if prev_outputs is not self.last_outputs:
1798
- self._fail('prev_outputs must be exactly the outputs dict the model call returned — '
1799
- 'do not copy, rebuild or slice it.')
1800
- if state is not self.last_state:
1801
- self._fail('state must be exactly the state object the previous hook call returned.')
1802
- if _nest_fingerprint(prev_inputs) != self.fed_inputs_fingerprint:
1803
- self._fail('the model inputs were mutated in place after being fed to the model — '
1804
- 'the platform re-reads the stored step tensors, so local mutations diverge '
1805
- 'from platform results. Compute new tensors inside the hook instead.')
1806
- if _nest_fingerprint(prev_outputs) != self.last_outputs_fingerprint:
1807
- self._fail('the model outputs were mutated in place after the model call — the '
1808
- 'platform re-reads the stored step tensors, so local mutations diverge '
1809
- 'from platform results. Compute derived tensors inside the hook instead.')
1810
- if _nest_fingerprint(state) != self.last_state_fingerprint:
1811
- self._fail('the state object was mutated between hook calls — state may only change '
1812
- 'inside the hook body.')
1813
-
1814
- def on_hook_return(self, next_inputs, state):
1815
- self.steps += 1
1816
- if self.steps > _MODEL_LOOP_MAX_STEPS:
1817
- self._fail(f'the chain exceeded {_MODEL_LOOP_MAX_STEPS} steps without the '
1818
- f'autoregressive step returning None — the loop would never terminate on '
1819
- f'the platform.')
1820
- self.last_state = state
1821
- self.last_state_fingerprint = _nest_fingerprint(state)
1822
- if next_inputs is None:
1823
- self.phase = 'ended'
1824
- else:
1825
- self.fed_inputs = next_inputs
1826
- self.fed_inputs_fingerprint = _nest_fingerprint(next_inputs)
1827
- self.phase = 'awaiting_model'
1828
-
1829
- def mapping_hook_call(self, inputs_placeholder, state_placeholder):
1830
- if self.phase == 'ended':
1831
- self._fail('the chain already ended — once the autoregressive step returns None for '
1832
- 'next_inputs the loop must exit without further hook or model calls.')
1833
- if self.phase == 'awaiting_model':
1834
- self._fail('two autoregressive step calls in a row — the model must run exactly once '
1835
- 'between hook calls.')
1836
- self.last_state = state_placeholder
1837
- if self.phase == 'awaiting_first_hook':
1838
- self.fed_inputs = inputs_placeholder
1839
- self.phase = 'awaiting_model'
1840
- return inputs_placeholder, state_placeholder
1841
- self.phase = 'ended'
1842
- return None, state_placeholder
1843
-
1844
- def on_model_call(self, fed):
1845
- if self.phase == 'awaiting_first_hook':
1846
- self._fail('the model was called before the autoregressive step produced the initial '
1847
- 'inputs — the loop must start with the initial hook call '
1848
- '(prev_inputs=None, prev_outputs=None, state=None).')
1849
- if self.phase == 'awaiting_hook':
1850
- self._fail('the model was called twice in a row — the autoregressive step must run '
1851
- 'between model calls.')
1852
- if self.phase == 'ended':
1853
- self._fail('the chain already ended — once the autoregressive step returns None for '
1854
- 'next_inputs the loop must exit without further hook or model calls.')
1855
- if self.is_mapping:
1856
- return
1857
- fed_ids = {id(leaf) for leaf in _ndarray_leaves(fed)}
1858
- hook_ids = {id(value) for value in self.fed_inputs.values()}
1859
- if fed_ids != hook_ids:
1860
- self._fail('the model must be fed exactly the tensors the last hook call returned — '
1861
- 'any computation between the hook and the model is invisible to the '
1862
- 'platform. Move it into the hook.')
1863
- if _nest_fingerprint(self.fed_inputs) != self.fed_inputs_fingerprint:
1864
- self._fail('the model inputs were mutated in place after the hook returned them — '
1865
- 'the platform feeds the model the tensors exactly as the hook returned '
1866
- 'them. Compute new tensors inside the hook instead.')
1867
-
1868
- def on_model_return(self, raw_outputs):
1869
- self.phase = 'awaiting_hook'
1870
- if self.is_mapping:
1871
- self.last_outputs = raw_outputs
1872
- return raw_outputs
1873
- outputs_list = raw_outputs if isinstance(raw_outputs, list) else [raw_outputs]
1874
- if len(outputs_list) != len(self.prediction_names):
1875
- self._fail(f'the model returned {len(outputs_list)} outputs but '
1876
- f'{len(self.prediction_names)} prediction types are declared on '
1877
- f'tensorleap_load_model — declare one prediction type per model output.')
1878
- named_outputs = {name: np.asarray(output)
1879
- for name, output in zip(self.prediction_names, outputs_list)}
1880
- self.last_outputs = named_outputs
1881
- self.last_outputs_fingerprint = _nest_fingerprint(named_outputs)
1882
- return named_outputs
1883
-
1884
-
1885
- class _ModelLoopModelProxy:
1886
- def __init__(self, model, context):
1887
- self._model = model
1888
- self._context = context
1889
-
1890
- def __call__(self, inputs):
1891
- self._context.on_model_call(inputs)
1892
- return self._context.on_model_return(self._model(inputs))
1893
-
1894
- def run(self, output_names, input_dict):
1895
- self._context.on_model_call(input_dict)
1896
- return self._context.on_model_return(self._model.run(output_names, input_dict))
1897
-
1898
- def get_inputs(self):
1899
- return self._model.get_inputs()
1900
-
1901
-
1902
1715
  def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
1903
1716
  """The feedback hook that drives an autoregressive chain.
1904
1717
 
1905
1718
  Signature of the decorated function:
1906
- (sample_id, prev_inputs, prev_outputs, state, preprocess)
1907
- -> (Optional[Dict[str, np.ndarray]], state)
1908
-
1909
- First call per chain: prev_inputs=None, prev_outputs=None, state=None returns the initial
1910
- model inputs and the initial state. Later calls receive the previous step's model inputs and
1911
- outputs (unbatched, per-sample; outputs keyed by the declared prediction-type names) plus the
1912
- state returned by the previous call, and return the next step's full input dict together with
1913
- the updated state; returning (None, state) ends the chain the terminating call still
1914
- returns state, so the final step participates in state aggregation. State is never fed to
1915
- the model; it may be any nest of dicts/lists holding numpy arrays, numbers, strings or bools,
1916
- and it rides the platform queue on every step — accumulate reductions, not raw per-step
1917
- tensors. The hook must be stateless and deterministically seeded (seed stochasticity from
1918
- sample_id) — the engine replays steps after crash recovery and relies on identical results.
1719
+ (sample_id, prev_inputs, prev_outputs, preprocess) -> Optional[Dict[str, np.ndarray]]
1720
+
1721
+ First call per chain: prev_inputs=None, prev_outputs=None — returns the initial model inputs.
1722
+ Later calls receive the previous step's model inputs and outputs (unbatched, per-sample) and
1723
+ return the next step's full input dict; returning None ends the chain. Keys starting with '_'
1724
+ are passthrough state: never fed to the model, handed back verbatim in prev_inputs next call.
1725
+ The hook must be stateless and deterministically seeded (seed stochasticity from sample_id)
1726
+ the engine replays steps after crash recovery and relies on identical results.
1919
1727
 
1920
1728
  latent_space_aggregation ('last_step' | 'mean') declares how the chain's latent-space
1921
1729
  vectors are derived from its per-step forward passes. 'last_step' (default): every latent
@@ -1934,95 +1742,62 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
1934
1742
  first_call_record: Dict[str, Any] = {'keys': None, 'shapes': None}
1935
1743
 
1936
1744
  def _normalize_args(args, kwargs):
1937
- expected_names = ["sample_id", "prev_inputs", "prev_outputs", "state", "preprocess"]
1745
+ expected_names = ["sample_id", "prev_inputs", "prev_outputs", "preprocess"]
1746
+ validate_args_structure(
1747
+ *args,
1748
+ types_order=[Union[int, str], Union[dict, type(None)], Union[dict, type(None)],
1749
+ PreprocessResponse],
1750
+ func_name=user_function.__name__, expected_names=expected_names, **kwargs)
1938
1751
  normalized = []
1939
- for i, arg_name in enumerate(expected_names):
1940
- if i < len(args):
1941
- normalized.append(args[i])
1942
- elif arg_name in kwargs:
1943
- normalized.append(kwargs[arg_name])
1944
- else:
1945
- raise AssertionError(
1946
- f'{user_function.__name__} validation failed: missing required argument '
1947
- f"'{arg_name}'. Expected arguments: {expected_names}.")
1948
- if len(args) + len(kwargs) != len(expected_names):
1949
- raise AssertionError(
1950
- f'{user_function.__name__} validation failed: expected exactly '
1951
- f'{len(expected_names)} arguments {expected_names}, got '
1952
- f'{len(args) + len(kwargs)}.')
1953
- sample_id, prev_inputs, prev_outputs, state, preprocess_response = normalized
1954
- assert isinstance(sample_id, (int, str)), \
1955
- (f'{user_function.__name__}() validation failed: '
1956
- f'sample_id must be an int or str. Got {type(sample_id).__name__}.')
1957
- assert prev_inputs is None or isinstance(prev_inputs, dict), \
1958
- (f'{user_function.__name__}() validation failed: '
1959
- f'prev_inputs must be a dict or None. Got {type(prev_inputs).__name__}.')
1960
- assert prev_outputs is None or isinstance(prev_outputs, dict), \
1961
- (f'{user_function.__name__}() validation failed: '
1962
- f'prev_outputs must be a dict or None. Got {type(prev_outputs).__name__}.')
1963
- assert isinstance(preprocess_response, PreprocessResponse), \
1964
- (f'{user_function.__name__}() validation failed: '
1965
- f'preprocess must be a PreprocessResponse. Got '
1966
- f'{type(preprocess_response).__name__}.')
1752
+ for i, name in enumerate(expected_names):
1753
+ normalized.append(args[i] if i < len(args) else kwargs[name])
1967
1754
  return normalized
1968
1755
 
1969
- def _validate_input_args(sample_id, prev_inputs, prev_outputs, state, preprocess_response):
1756
+ def _validate_input_args(sample_id, prev_inputs, prev_outputs, preprocess_response):
1970
1757
  assert (prev_inputs is None) == (prev_outputs is None), \
1971
1758
  (f'{user_function.__name__}() validation failed: '
1972
1759
  f'prev_inputs and prev_outputs must both be None (first call) or both be dicts '
1973
1760
  f'(subsequent calls). Got prev_inputs={type(prev_inputs).__name__}, '
1974
1761
  f'prev_outputs={type(prev_outputs).__name__}.')
1975
- assert not (prev_inputs is None and state is not None), \
1976
- (f'{user_function.__name__}() validation failed: '
1977
- f'the first call (prev_inputs=None, prev_outputs=None) must pass state=None. '
1978
- f'Got state of type {type(state).__name__}.')
1979
1762
  assert type(sample_id) == preprocess_response.sample_id_type, \
1980
1763
  (f'{user_function.__name__}() validation failed: '
1981
1764
  f'Argument sample_id should be as the same type as defined in the preprocess response '
1982
1765
  f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
1983
1766
 
1984
1767
  def _validate_result(result, is_first_call):
1985
- assert isinstance(result, tuple) and len(result) == 2, \
1986
- (f'{user_function.__name__}() validation failed: '
1987
- f'the hook must return a (next_inputs, state) tuple — next_inputs is a dict of '
1988
- f'named model input tensors, or None to end the chain; state rides to the next '
1989
- f'call. Got {type(result).__name__}.')
1990
- next_inputs, state = result
1991
- if next_inputs is None:
1768
+ if result is None:
1992
1769
  assert not is_first_call, \
1993
1770
  (f'{user_function.__name__}() validation failed: '
1994
- f'the first call (prev_inputs=None, prev_outputs=None, state=None) must return '
1995
- f'the initial model inputs dict — returning None on the first call would '
1996
- f'produce an empty chain.')
1771
+ f'the first call (prev_inputs=None, prev_outputs=None) must return the initial '
1772
+ f'model inputs dict — returning None on the first call would produce an empty chain.')
1997
1773
  return
1998
- assert isinstance(next_inputs, dict), \
1774
+ assert isinstance(result, dict), \
1999
1775
  (f'{user_function.__name__}() validation failed: '
2000
- f'next_inputs must be a dict of named model input tensors, or None to end the '
2001
- f'chain. Got {type(next_inputs)}.')
2002
- assert next_inputs, \
1776
+ f'the return value must be a dict of named model input tensors, or None to end the '
1777
+ f'chain. Got {type(result)}.')
1778
+ model_input_keys = [key for key in result if not key.startswith('_')]
1779
+ assert model_input_keys, \
2003
1780
  (f'{user_function.__name__}() validation failed: '
2004
- f'next_inputs is an empty dict return the full model input dict, or None to '
2005
- f'end the chain.')
2006
- for key, value in next_inputs.items():
1781
+ f'the returned dict contains no model inputs every key starts with "_" '
1782
+ f'(underscore keys are passthrough state, never fed to the model).')
1783
+ for key, value in result.items():
2007
1784
  assert isinstance(key, str), \
2008
1785
  (f'{user_function.__name__}() validation failed: '
2009
- f'all keys in next_inputs must be strings. Got {type(key)}.')
2010
- assert not key.startswith('_'), \
2011
- (f'{user_function.__name__}() validation failed: '
2012
- f'next_inputs key "{key}" starts with "_" — underscore passthrough keys were '
2013
- f'replaced by the explicit state channel. Move passthrough values into the '
2014
- f'returned state.')
1786
+ f'all keys in the returned dict must be strings. Got {type(key)}.')
1787
+ if key.startswith('_'):
1788
+ continue
2015
1789
  assert isinstance(value, np.ndarray), \
2016
1790
  (f'{user_function.__name__}() validation failed: '
2017
1791
  f'value for model input "{key}" must be a numpy array. Got {type(value)}.')
2018
1792
 
2019
- def _validate_consistency(next_inputs):
2020
- # Rules 2-3 of the autoregressive contract: identical key set and identical shapes on
2021
- # every call — compiled graphs need static shapes.
2022
- if next_inputs is None:
1793
+ def _validate_consistency(result):
1794
+ # Rules 2-3 of the autoregressive contract: identical key set and identical
1795
+ # (non-passthrough) shapes on every call — compiled graphs need static shapes.
1796
+ if result is None:
2023
1797
  return
2024
- keys = set(next_inputs.keys())
2025
- shapes = {key: tuple(value.shape) for key, value in next_inputs.items()}
1798
+ keys = set(result.keys())
1799
+ shapes = {key: tuple(value.shape) for key, value in result.items()
1800
+ if not key.startswith('_') and isinstance(value, np.ndarray)}
2026
1801
  if first_call_record['keys'] is None:
2027
1802
  first_call_record['keys'] = keys
2028
1803
  first_call_record['shapes'] = shapes
@@ -2044,19 +1819,14 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2044
1819
  f'the hook is not deterministic — two calls with identical arguments returned different '
2045
1820
  f'outputs. Seed any stochasticity (e.g. initial noise) from sample_id: the engine '
2046
1821
  f'replays steps after crash recovery and relies on identical results.')
2047
- assert isinstance(first_result, tuple) and isinstance(second_result, tuple) and \
2048
- len(first_result) == 2 and len(second_result) == 2, error_message
2049
- first_inputs, first_state = first_result
2050
- second_inputs, second_state = second_result
2051
- if first_inputs is None or second_inputs is None:
2052
- assert first_inputs is None and second_inputs is None, error_message
2053
- else:
2054
- assert set(first_inputs.keys()) == set(second_inputs.keys()), error_message
2055
- for key, value in first_inputs.items():
2056
- if not isinstance(value, np.ndarray):
2057
- continue
2058
- assert _nest_equal(value, second_inputs[key]), error_message
2059
- assert _nest_equal(first_state, second_state), error_message
1822
+ if first_result is None or second_result is None:
1823
+ assert first_result is None and second_result is None, error_message
1824
+ return
1825
+ assert set(first_result.keys()) == set(second_result.keys()), error_message
1826
+ for key, value in first_result.items():
1827
+ if key.startswith('_') or not isinstance(value, np.ndarray):
1828
+ continue
1829
+ assert np.array_equal(value, second_result[key]), error_message
2060
1830
 
2061
1831
  def _squeeze_test_batch_dim(tensors_dict):
2062
1832
  # Inside the integration test the model works on batch-1 tensors (this wrapper adds the
@@ -2067,18 +1837,18 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2067
1837
  return None
2068
1838
  squeezed = {}
2069
1839
  for key, value in tensors_dict.items():
2070
- if isinstance(value, np.ndarray) and value.ndim > 0 and value.shape[0] == 1:
1840
+ if not key.startswith('_') and isinstance(value, np.ndarray) \
1841
+ and value.ndim > 0 and value.shape[0] == 1:
2071
1842
  squeezed[key] = value[0]
2072
1843
  else:
2073
1844
  squeezed[key] = value
2074
1845
  return squeezed
2075
1846
 
2076
- def inner_without_validate(sample_id, prev_inputs, prev_outputs, state, preprocess_response):
1847
+ def inner_without_validate(sample_id, prev_inputs, prev_outputs, preprocess_response):
2077
1848
  global _called_from_inside_tl_decorator
2078
1849
  _called_from_inside_tl_decorator += 1
2079
1850
  try:
2080
- result = user_function(sample_id, prev_inputs, prev_outputs, state,
2081
- preprocess_response)
1851
+ result = user_function(sample_id, prev_inputs, prev_outputs, preprocess_response)
2082
1852
  finally:
2083
1853
  _called_from_inside_tl_decorator -= 1
2084
1854
  return result
@@ -2089,66 +1859,43 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2089
1859
  def inner(*args, **kwargs):
2090
1860
  if not _call_from_tl_platform:
2091
1861
  set_current('tensorleap_autoregressive_step')
2092
- sample_id, prev_inputs, prev_outputs, state, preprocess_response = \
2093
- _normalize_args(args, kwargs)
1862
+ sample_id, prev_inputs, prev_outputs, preprocess_response = _normalize_args(args, kwargs)
2094
1863
 
2095
- is_top_level = _called_from_inside_tl_decorator == 0
2096
- is_top_level_in_test = (is_top_level
1864
+ is_top_level_in_test = (_called_from_inside_tl_decorator == 0
2097
1865
  and _called_from_inside_tl_integration_test_decorator)
2098
- loop_context = _active_model_loop
2099
- if is_top_level_in_test and loop_context is None:
2100
- raise LeapValidationError(
2101
- f'{user_function.__name__}() validation failed: inside the integration '
2102
- f'test the autoregressive step may only be called from within the '
2103
- f'tensorleap_model_loop function — including the initial call '
2104
- f'(prev_inputs=None). The platform drives the chain through the model '
2105
- f'loop only, so a hook call outside it would not run on the platform.')
2106
- # Outside the integration test a model loop may still be running (local debugging);
2107
- # the loop's phase machine must advance there too, or its model proxy always raises.
2108
- notify_loop = is_top_level and loop_context is not None
2109
- if notify_loop:
2110
- loop_context.on_hook_call(sample_id, prev_inputs, prev_outputs, state,
2111
- preprocess_response)
2112
1866
  if is_top_level_in_test:
2113
1867
  prev_inputs = _squeeze_test_batch_dim(prev_inputs)
2114
1868
  prev_outputs = _squeeze_test_batch_dim(prev_outputs)
2115
1869
 
2116
- _validate_input_args(sample_id, prev_inputs, prev_outputs, state, preprocess_response)
1870
+ _validate_input_args(sample_id, prev_inputs, prev_outputs, preprocess_response)
2117
1871
 
2118
- # The deep copy keeps the determinism double-call independent: a hook that
2119
- # accumulates into state in place would otherwise see its own first-call mutations.
2120
- state_for_second_call = copy.deepcopy(state) if is_top_level_in_test else None
2121
- result = inner_without_validate(sample_id, prev_inputs, prev_outputs, state,
2122
- preprocess_response)
1872
+ result = inner_without_validate(sample_id, prev_inputs, prev_outputs, preprocess_response)
2123
1873
 
2124
1874
  if is_top_level_in_test:
2125
1875
  # Rule 7: determinism double-call. An unseeded sampler fails here, on the user's
2126
1876
  # machine, instead of silently forking a chain on engine crash-replay.
2127
1877
  second_result = inner_without_validate(sample_id, prev_inputs, prev_outputs,
2128
- state_for_second_call, preprocess_response)
1878
+ preprocess_response)
2129
1879
  _assert_deterministic(result, second_result)
2130
1880
 
2131
1881
  _validate_result(result, is_first_call=prev_inputs is None)
2132
- next_inputs, new_state = result
2133
- _validate_consistency(next_inputs)
2134
- _validate_state_types(new_state)
1882
+ _validate_consistency(result)
2135
1883
 
2136
- if is_top_level_in_test and next_inputs is not None:
2137
- next_inputs = {key: np.expand_dims(value, axis=0)
2138
- for key, value in next_inputs.items()}
2139
- if notify_loop:
2140
- loop_context.on_hook_return(next_inputs, new_state)
1884
+ if is_top_level_in_test and result is not None:
1885
+ result = {key: (np.expand_dims(value, axis=0)
1886
+ if not key.startswith('_') and isinstance(value, np.ndarray) else value)
1887
+ for key, value in result.items()}
2141
1888
 
2142
1889
  if not _call_from_tl_platform:
2143
1890
  update_env_params_func("tensorleap_autoregressive_step", "v")
2144
- return next_inputs, new_state
1891
+ return result
2145
1892
 
2146
1893
  class _MappingInputsPlaceholder:
2147
- """Mapping-mode stand-in for the hook's returned inputs dict.
1894
+ """Mapping-mode stand-in for the hook's returned dict.
2148
1895
 
2149
1896
  Indexing it by a model-input name yields a placeholder whose node_mapping the model
2150
1897
  placeholder tags Input0/Input1/... — exactly how input encoders wire the graph. One
2151
- NodeConnection is recorded per key, once.
1898
+ NodeConnection is recorded per non-passthrough key, once.
2152
1899
  """
2153
1900
  def __init__(self):
2154
1901
  self._items: Dict[str, Any] = {}
@@ -2161,7 +1908,8 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2161
1908
  pass
2162
1909
  ret = TempMapping()
2163
1910
  ret.node_mapping = NodeMapping(key, NodeMappingType.Input)
2164
- leap_binder.mapping_connections.append(NodeConnection(ret.node_mapping, None))
1911
+ if not key.startswith('_'):
1912
+ leap_binder.mapping_connections.append(NodeConnection(ret.node_mapping, None))
2165
1913
  self._items[key] = ret
2166
1914
  return self._items[key]
2167
1915
 
@@ -2186,17 +1934,9 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2186
1934
  self._unsupported_iteration()
2187
1935
 
2188
1936
  mapping_placeholder = _MappingInputsPlaceholder()
2189
- mapping_state_placeholder = _MappingStatePlaceholder()
2190
1937
 
2191
1938
  def mapping_inner(*args, **kwargs):
2192
- loop_context = _active_model_loop
2193
- if loop_context is None:
2194
- raise LeapValidationError(
2195
- f'{user_function.__name__}() validation failed: inside the integration test '
2196
- f'the autoregressive step may only be called from within the '
2197
- f'tensorleap_model_loop function — including the initial call '
2198
- f'(prev_inputs=None).')
2199
- return loop_context.mapping_hook_call(mapping_placeholder, mapping_state_placeholder)
1939
+ return mapping_placeholder
2200
1940
 
2201
1941
  def final_inner(*args, **kwargs):
2202
1942
  if os.environ.get(mapping_runtime_mode_env_var_mame):
@@ -2212,396 +1952,6 @@ def tensorleap_autoregressive_step(latent_space_aggregation: str = 'last_step'):
2212
1952
  return decorating_function
2213
1953
 
2214
1954
 
2215
- def tensorleap_model_loop():
2216
- """The user-authored autoregressive rollout loop.
2217
-
2218
- Signature of the decorated function:
2219
- (model, sample_id, preprocess) -> (final_inputs, final_outputs, final_state)
2220
-
2221
- The function drives the chain locally, exactly as the platform will: it makes the initial
2222
- hook call (prev_inputs=None, prev_outputs=None, state=None) inside the loop, alternates
2223
- model forwards with hook calls, feeds the model exactly the tensors the hook returned, and
2224
- exits when the hook returns None for next_inputs — returning the last inputs dict fed to the
2225
- model, the last model outputs (a dict keyed by the declared prediction-type names) and the
2226
- final state. The loop body itself never runs on the platform — the engine drives the chain —
2227
- so the decorator validates, while the loop runs, that its behavior matches the engine loop;
2228
- any computation in the loop body outside the hook and the model is invisible to the platform
2229
- and fails validation. Canonical shape:
2230
-
2231
- @tensorleap_model_loop()
2232
- def model_loop(model, sample_id, preprocess):
2233
- inputs, state = generate_next_inputs(sample_id, None, None, None, preprocess)
2234
- while True:
2235
- outputs = model(inputs)
2236
- next_inputs, state = generate_next_inputs(sample_id, inputs, outputs, state,
2237
- preprocess)
2238
- if next_inputs is None:
2239
- return inputs, outputs, state
2240
- inputs = next_inputs
2241
- """
2242
-
2243
- def decorating_function(user_function):
2244
-
2245
- def _normalize_args(args, kwargs):
2246
- expected_names = ["model", "sample_id", "preprocess"]
2247
- normalized = []
2248
- for i, arg_name in enumerate(expected_names):
2249
- if i < len(args):
2250
- normalized.append(args[i])
2251
- elif arg_name in kwargs:
2252
- normalized.append(kwargs[arg_name])
2253
- else:
2254
- raise AssertionError(
2255
- f'{user_function.__name__} validation failed: missing required argument '
2256
- f"'{arg_name}'. Expected arguments: {expected_names}.")
2257
- if len(args) + len(kwargs) != len(expected_names):
2258
- raise AssertionError(
2259
- f'{user_function.__name__} validation failed: expected exactly '
2260
- f'{len(expected_names)} arguments {expected_names}, got '
2261
- f'{len(args) + len(kwargs)}.')
2262
- return normalized
2263
-
2264
- def _fail(message):
2265
- raise LeapValidationError(f'tensorleap_model_loop validation failed: {message}')
2266
-
2267
- def _run_with_context(model, sample_id, preprocess_response, is_mapping):
2268
- global _active_model_loop, _model_loop_run_in_current_test
2269
- in_test = bool(_called_from_inside_tl_integration_test_decorator)
2270
- if _active_model_loop is not None:
2271
- _fail('model loops cannot nest or run concurrently.')
2272
- if in_test and _model_loop_run_in_current_test:
2273
- _fail('only one model loop run is allowed per integration test.')
2274
- if model is None or model is not _last_loaded_model:
2275
- _fail('the model argument must be the object returned by the '
2276
- 'tensorleap_load_model function, unchanged.')
2277
- if leap_binder.setup_container.autoregressive_step is None:
2278
- _fail('tensorleap_model_loop requires a tensorleap_autoregressive_step hook.')
2279
- prediction_names = [prediction_type.name for prediction_type
2280
- in leap_binder.setup_container.prediction_types]
2281
- if not prediction_names:
2282
- _fail('tensorleap_model_loop requires prediction types declared on '
2283
- 'tensorleap_load_model — the loop keys the model outputs by their names.')
2284
- context = _ModelLoopContext(sample_id, preprocess_response, prediction_names,
2285
- is_mapping)
2286
- _active_model_loop = context
2287
- try:
2288
- result = user_function(_ModelLoopModelProxy(model, context), sample_id,
2289
- preprocess_response)
2290
- finally:
2291
- _active_model_loop = None
2292
- if in_test:
2293
- _model_loop_run_in_current_test = True
2294
- if context.phase == 'awaiting_first_hook':
2295
- _fail('the loop never called the autoregressive step — it must start with the '
2296
- 'initial hook call (prev_inputs=None, prev_outputs=None, state=None).')
2297
- if context.phase != 'ended':
2298
- _fail('the loop returned before the autoregressive step signaled the chain end — '
2299
- 'it must run until the hook returns None for next_inputs and then return '
2300
- '(final_inputs, final_outputs, final_state).')
2301
- if not isinstance(result, tuple) or len(result) != 3:
2302
- _fail('the loop must return (final_inputs, final_outputs, final_state). Got '
2303
- f'{type(result).__name__}.')
2304
- final_inputs, final_outputs, final_state = result
2305
- if final_inputs is not context.fed_inputs:
2306
- _fail('final_inputs must be exactly the last inputs dict fed to the model — the '
2307
- 'one the hook returned before the terminating call.')
2308
- if final_outputs is not context.last_outputs:
2309
- _fail('final_outputs must be exactly the outputs dict of the last model call.')
2310
- if final_state is not context.last_state:
2311
- _fail('final_state must be exactly the state returned by the terminating hook '
2312
- 'call.')
2313
- return context, final_inputs, final_outputs, final_state
2314
-
2315
- def inner(*args, **kwargs):
2316
- if not _call_from_tl_platform:
2317
- set_current('tensorleap_model_loop')
2318
- model, sample_id, preprocess_response = _normalize_args(args, kwargs)
2319
- in_test = _called_from_inside_tl_integration_test_decorator
2320
- context, final_inputs, final_outputs, final_state = _run_with_context(
2321
- model, sample_id, preprocess_response, is_mapping=False)
2322
- if _nest_fingerprint(final_inputs) != context.fed_inputs_fingerprint:
2323
- _fail('the final inputs were mutated in place after the last model call.')
2324
- if _nest_fingerprint(final_outputs) != context.last_outputs_fingerprint:
2325
- _fail('the final outputs were mutated in place after the last model call.')
2326
- if _nest_fingerprint(final_state) != context.last_state_fingerprint:
2327
- _fail('the final state was mutated in place after the terminating hook call.')
2328
- if not in_test:
2329
- if not _call_from_tl_platform:
2330
- update_env_params_func("tensorleap_model_loop", "v")
2331
- return final_inputs, final_outputs, final_state
2332
- # Inside the integration test the chain tensors carry a batch-1 axis; the platform
2333
- # feeds autoregressive metrics per-chain unbatched dicts, so strip it here.
2334
- squeezed_inputs = _squeeze_leading_batch_axis(final_inputs)
2335
- squeezed_outputs = _squeeze_leading_batch_axis(final_outputs)
2336
- _register_chain_artifact(squeezed_inputs, 'final_inputs')
2337
- _register_chain_artifact(squeezed_outputs, 'final_outputs')
2338
- _register_chain_artifact(final_state, 'final_state')
2339
- if not _call_from_tl_platform:
2340
- update_env_params_func("tensorleap_model_loop", "v")
2341
- return squeezed_inputs, squeezed_outputs, final_state
2342
-
2343
- def mapping_inner(*args, **kwargs):
2344
- model, sample_id, preprocess_response = _normalize_args(args, kwargs)
2345
- context, final_inputs, final_outputs, final_state = _run_with_context(
2346
- model, sample_id, preprocess_response, is_mapping=True)
2347
- _register_chain_artifact(final_inputs, 'final_inputs')
2348
- _register_chain_artifact(final_outputs, 'final_outputs')
2349
- _register_chain_artifact(final_state, 'final_state')
2350
- return final_inputs, final_outputs, final_state
2351
-
2352
- def final_inner(*args, **kwargs):
2353
- if os.environ.get(mapping_runtime_mode_env_var_mame):
2354
- return mapping_inner(*args, **kwargs)
2355
- else:
2356
- return inner(*args, **kwargs)
2357
-
2358
- if not _call_from_tl_platform:
2359
- register_decorator_row("tensorleap_model_loop")
2360
-
2361
- return final_inner
2362
-
2363
- return decorating_function
2364
-
2365
-
2366
- _IMPLICIT_ARG_TO_ARTIFACT_KIND = {'inputs': 'final_inputs', 'outputs': 'final_outputs',
2367
- 'state': 'final_state'}
2368
- _ARTIFACT_KIND_DESCRIPTIONS = {
2369
- 'final_inputs': 'final inputs dict returned by the model loop',
2370
- 'final_outputs': 'final outputs dict returned by the model loop',
2371
- 'final_state': 'final state returned by the model loop',
2372
- 'ground_truth': 'direct return value of a ground-truth encoder',
2373
- }
2374
- _AUTOREGRESSIVE_SCALAR_TYPES = (int, float, np.floating, np.integer, np.bool_)
2375
-
2376
-
2377
- def _normalize_autoregressive_call_args(func_name, full_arg_names, args, kwargs):
2378
- if len(args) + len(kwargs) != len(full_arg_names):
2379
- raise AssertionError(
2380
- f'{func_name} validation failed: expected exactly {len(full_arg_names)} arguments '
2381
- f'{full_arg_names}, got {len(args) + len(kwargs)}.')
2382
- normalized = {}
2383
- for i, arg_name in enumerate(full_arg_names):
2384
- if i < len(args):
2385
- normalized[arg_name] = args[i]
2386
- elif arg_name in kwargs:
2387
- normalized[arg_name] = kwargs[arg_name]
2388
- else:
2389
- raise AssertionError(
2390
- f'{func_name} validation failed: missing required argument \'{arg_name}\'. '
2391
- f'Expected arguments: {full_arg_names}.')
2392
- return normalized
2393
-
2394
-
2395
- def _validate_autoregressive_arg_provenance(func_name, normalized):
2396
- for arg_name, value in normalized.items():
2397
- expected_kind = _IMPLICIT_ARG_TO_ARTIFACT_KIND.get(arg_name, 'ground_truth')
2398
- entry = _lookup_chain_artifact(value)
2399
- if entry is None:
2400
- raise LeapValidationError(
2401
- f'{func_name} validation failed: argument "{arg_name}" must be the '
2402
- f'{_ARTIFACT_KIND_DESCRIPTIONS[expected_kind]}, passed whole and unmodified — '
2403
- f'the platform feeds it from the finished chain, so anything else would not '
2404
- f'exist at platform runtime. Slice or derive inside the function body instead.')
2405
- kind, fingerprint, _ = entry
2406
- if kind != expected_kind:
2407
- raise LeapValidationError(
2408
- f'{func_name} validation failed: argument "{arg_name}" received the '
2409
- f'{_ARTIFACT_KIND_DESCRIPTIONS[kind]} but must be the '
2410
- f'{_ARTIFACT_KIND_DESCRIPTIONS[expected_kind]}.')
2411
- if fingerprint != _nest_fingerprint(value):
2412
- raise LeapValidationError(
2413
- f'{func_name} validation failed: argument "{arg_name}" was mutated in place '
2414
- f'after it was produced — the platform feeds the original values, so local '
2415
- f'mutations diverge from platform results.')
2416
-
2417
-
2418
- def _squeeze_wired_autoregressive_args(normalized):
2419
- squeezed = {}
2420
- for arg_name, value in normalized.items():
2421
- if arg_name not in _IMPLICIT_ARG_TO_ARTIFACT_KIND and isinstance(value, np.ndarray) \
2422
- and value.ndim > 0 and value.shape[0] == 1:
2423
- squeezed[arg_name] = value[0]
2424
- else:
2425
- squeezed[arg_name] = value
2426
- return squeezed
2427
-
2428
-
2429
- def _validate_autoregressive_scalar_result(func_name, result, allow_dict):
2430
- def _is_scalar(value):
2431
- return isinstance(value, _AUTOREGRESSIVE_SCALAR_TYPES) or \
2432
- (isinstance(value, np.ndarray) and value.ndim == 0)
2433
-
2434
- if _is_scalar(result):
2435
- return
2436
- if allow_dict and isinstance(result, dict) and result and \
2437
- all(isinstance(key, str) for key in result) and \
2438
- all(_is_scalar(value) for value in result.values()):
2439
- return
2440
- expected = 'a scalar number' + (' or a dict of named scalar numbers' if allow_dict else '')
2441
- raise AssertionError(
2442
- f'{func_name} validation failed: autoregressive results are per-chain — the function '
2443
- f'must return {expected} for the single chain it received. Got {type(result).__name__}.')
2444
-
2445
-
2446
- def _autoregressive_mapping_call(mapping_inner_func, args, kwargs, node_mapping_type):
2447
- user_unique_name = mapping_inner_func.name
2448
- if 'user_unique_name' in kwargs:
2449
- kwargs = dict(kwargs)
2450
- user_unique_name = kwargs.pop('user_unique_name')
2451
- if user_unique_name in mapping_inner_func.name_to_unique_name[mapping_inner_func.name]:
2452
- user_unique_name = \
2453
- f'{user_unique_name}_{len(mapping_inner_func.name_to_unique_name[mapping_inner_func.name])}'
2454
- mapping_inner_func.name_to_unique_name[mapping_inner_func.name].add(user_unique_name)
2455
-
2456
- normalized = _normalize_autoregressive_call_args(mapping_inner_func.name,
2457
- mapping_inner_func.full_arg_names, args,
2458
- kwargs)
2459
- for arg_name, value in normalized.items():
2460
- if arg_name in _IMPLICIT_ARG_TO_ARTIFACT_KIND:
2461
- entry = _lookup_chain_artifact(value)
2462
- expected_kind = _IMPLICIT_ARG_TO_ARTIFACT_KIND[arg_name]
2463
- if entry is None or entry[0] != expected_kind:
2464
- raise LeapValidationError(
2465
- f'{mapping_inner_func.name} validation failed: argument "{arg_name}" must '
2466
- f'be the {_ARTIFACT_KIND_DESCRIPTIONS[expected_kind]}, passed whole.')
2467
- elif not hasattr(value, 'node_mapping'):
2468
- raise LeapValidationError(
2469
- f'{mapping_inner_func.name} validation failed: argument "{arg_name}" must be '
2470
- f'the direct return value of a ground-truth encoder.')
2471
- ordered_connections = [normalized[arg_name] for arg_name in mapping_inner_func.arg_names]
2472
- _add_mapping_connection(user_unique_name, ordered_connections, mapping_inner_func.arg_names,
2473
- mapping_inner_func.name, node_mapping_type)
2474
- return None
2475
-
2476
-
2477
- def _make_autoregressive_decorator_inner(user_function, name, decorator_env_name, handler_data,
2478
- node_mapping_type, validate_result):
2479
- full_arg_names = inspect.getfullargspec(user_function)[0]
2480
-
2481
- def inner_without_validate(*args, **kwargs):
2482
- global _called_from_inside_tl_decorator
2483
- _called_from_inside_tl_decorator += 1
2484
- try:
2485
- result = user_function(*args, **kwargs)
2486
- finally:
2487
- _called_from_inside_tl_decorator -= 1
2488
- return result
2489
-
2490
- def inner(*args, **kwargs):
2491
- if not _call_from_tl_platform:
2492
- set_current(decorator_env_name)
2493
- normalized = _normalize_autoregressive_call_args(user_function.__name__, full_arg_names,
2494
- args, kwargs)
2495
- is_top_level_in_test = (_called_from_inside_tl_decorator == 0
2496
- and _called_from_inside_tl_integration_test_decorator)
2497
- if is_top_level_in_test:
2498
- _validate_autoregressive_arg_provenance(user_function.__name__, normalized)
2499
- normalized = _squeeze_wired_autoregressive_args(normalized)
2500
- result = inner_without_validate(**normalized)
2501
- validate_result(user_function.__name__, result)
2502
- if not _call_from_tl_platform:
2503
- update_env_params_func(decorator_env_name, "v")
2504
- return result
2505
-
2506
- def mapping_inner(*args, **kwargs):
2507
- return _autoregressive_mapping_call(mapping_inner, args, kwargs, node_mapping_type)
2508
-
2509
- mapping_inner.name = name
2510
- mapping_inner.full_arg_names = full_arg_names
2511
- mapping_inner.arg_names = handler_data.arg_names
2512
- mapping_inner.name_to_unique_name = defaultdict(set)
2513
-
2514
- def final_inner(*args, **kwargs):
2515
- if os.environ.get(mapping_runtime_mode_env_var_mame):
2516
- return mapping_inner(*args, **kwargs)
2517
- else:
2518
- return inner(*args, **kwargs)
2519
-
2520
- if not _call_from_tl_platform:
2521
- register_decorator_row(decorator_env_name)
2522
-
2523
- return final_inner
2524
-
2525
-
2526
- def tensorleap_autoregressive_metric(name: str,
2527
- direction: Union[MetricDirection, Dict[str, MetricDirection]]
2528
- = MetricDirection.Downward,
2529
- compute_insights: Optional[Union[bool, Dict[str, bool]]] = None):
2530
- """A per-chain metric over a finished autoregressive chain.
2531
-
2532
- The reserved arguments inputs / outputs / state are fed implicitly by the platform from the
2533
- chain's final step (unbatched dicts; outputs keyed by the declared prediction-type names;
2534
- state as the terminating hook call returned it). Declare whichever of them the metric needs.
2535
- Every other argument is wired to a ground-truth encoder through the integration test. Runs
2536
- once per chain and must return a scalar number (or a dict of named scalar numbers).
2537
- """
2538
-
2539
- def decorating_function(user_function):
2540
- leap_binder.add_autoregressive_metric(user_function, name, direction, compute_insights)
2541
- handler_data = \
2542
- leap_binder.setup_container.autoregressive_metrics[-1].metric_handler_data
2543
-
2544
- def validate_result(func_name, result):
2545
- _validate_autoregressive_scalar_result(func_name, result, allow_dict=True)
2546
-
2547
- return _make_autoregressive_decorator_inner(
2548
- user_function, name, 'tensorleap_autoregressive_metric', handler_data,
2549
- NodeMappingType.Metric, validate_result)
2550
-
2551
- return decorating_function
2552
-
2553
-
2554
- def tensorleap_autoregressive_loss(name: str):
2555
- """A per-chain loss over a finished autoregressive chain.
2556
-
2557
- Same argument contract as tensorleap_autoregressive_metric; must return a single scalar
2558
- number for the chain it received.
2559
- """
2560
-
2561
- def decorating_function(user_function):
2562
- leap_binder.add_autoregressive_loss(user_function, name)
2563
- handler_data = \
2564
- leap_binder.setup_container.autoregressive_losses[-1].custom_loss_handler_data
2565
-
2566
- def validate_result(func_name, result):
2567
- _validate_autoregressive_scalar_result(func_name, result, allow_dict=False)
2568
-
2569
- return _make_autoregressive_decorator_inner(
2570
- user_function, name, 'tensorleap_autoregressive_loss', handler_data,
2571
- NodeMappingType.CustomLoss, validate_result)
2572
-
2573
- return decorating_function
2574
-
2575
-
2576
- def tensorleap_autoregressive_visualizer(name: str, visualizer_type: LeapDataType):
2577
- """A per-chain visualizer over a finished autoregressive chain.
2578
-
2579
- Same argument contract as tensorleap_autoregressive_metric; must return a LeapData object
2580
- matching visualizer_type.
2581
- """
2582
-
2583
- def decorating_function(user_function):
2584
- assert isinstance(visualizer_type, LeapDataType), \
2585
- (f'{user_function.__name__} validation failed: visualizer_type should be of type '
2586
- f'{LeapDataType.__name__} but got {type(visualizer_type)}')
2587
- leap_binder.add_autoregressive_visualizer(user_function, name, visualizer_type)
2588
- handler_data = \
2589
- leap_binder.setup_container.autoregressive_visualizers[-1].visualizer_handler_data
2590
-
2591
- def validate_result(func_name, result):
2592
- expected_class = map_leap_data_type_to_visualizer_class[visualizer_type.value]
2593
- assert isinstance(result, expected_class), \
2594
- (f'{func_name} validation failed: the return type should be '
2595
- f'{expected_class.__name__} (visualizer_type={visualizer_type}). '
2596
- f'Got {type(result).__name__}.')
2597
-
2598
- return _make_autoregressive_decorator_inner(
2599
- user_function, name, 'tensorleap_autoregressive_visualizer', handler_data,
2600
- NodeMappingType.Visualizer, validate_result)
2601
-
2602
- return decorating_function
2603
-
2604
-
2605
1955
  def tensorleap_preprocess():
2606
1956
  def decorating_function(user_function: Callable[[], List[PreprocessResponse]]):
2607
1957
  leap_binder.set_preprocess(user_function)
@@ -2632,6 +1982,15 @@ def tensorleap_preprocess():
2632
1982
  assert len(set(result)) == len(result), \
2633
1983
  (f'{user_function.__name__}() validation failed: '
2634
1984
  f'The return list should not contain duplicate PreprocessResponse objects.')
1985
+ # All-or-none: a dataset is either all grouped (nested sample_ids) or all flat.
1986
+ if len({response.is_grouped for response in result}) != 1:
1987
+ shapes = ', '.join(
1988
+ f"#{i}={'grouped' if response.is_grouped else 'flat'}"
1989
+ for i, response in enumerate(result))
1990
+ raise AssertionError(
1991
+ f'{user_function.__name__}() validation failed: '
1992
+ f'All PreprocessResponses must be either all grouped (nested sample_ids) '
1993
+ f'or all flat, but got a mix: {shapes}.')
2635
1994
 
2636
1995
  def inner(*args, **kwargs):
2637
1996
  if not _call_from_tl_platform:
@@ -2969,14 +2328,10 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
2969
2328
  f"channel axis in the batched tensor (batch = axis 0), so 0 is invalid. Use 1 "
2970
2329
  f"for channel-first (NCHW) and -1 for channel-last (NHWC).")
2971
2330
 
2972
- def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
2973
- assert type(sample_id) == preprocess_response.sample_id_type, \
2974
- (f'{user_function.__name__}() validation failed: '
2975
- f'Argument sample_id should be as the same type as defined in the preprocess response '
2976
- f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
2331
+ def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
2332
+ _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
2977
2333
 
2978
- def _validate_result(result):
2979
- validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray")
2334
+ def _validate_single(result):
2980
2335
  assert isinstance(result, np.ndarray), \
2981
2336
  (f'{user_function.__name__}() validation failed: '
2982
2337
  f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
@@ -2986,6 +2341,13 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
2986
2341
  assert channel_dim - 1 <= len(result.shape), (f'{user_function.__name__}() validation failed: '
2987
2342
  f'The channel_dim ({channel_dim}) should be <= to the rank of the resulting input rank ({len(result.shape)}).')
2988
2343
 
2344
+ def _validate_result(result, grouped=False, group_size=None):
2345
+ if not grouped:
2346
+ validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray")
2347
+ _validate_single(result)
2348
+ return
2349
+ _validate_grouped_result(result, group_size, user_function.__name__, _validate_single)
2350
+
2989
2351
  def inner_without_validate(sample_id, preprocess_response):
2990
2352
  global _called_from_inside_tl_decorator
2991
2353
  _called_from_inside_tl_decorator += 1
@@ -3002,18 +2364,27 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3002
2364
  def inner(*args, **kwargs):
3003
2365
  if not _call_from_tl_platform:
3004
2366
  set_current("tensorleap_input_encoder")
3005
- validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
2367
+ validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
3006
2368
  func_name=user_function.__name__, expected_names=["idx", "preprocess"], **kwargs)
3007
2369
  sample_id, preprocess_response = args if len(args) != 0 else kwargs.values()
3008
2370
  _validate_input_args(sample_id, preprocess_response)
3009
2371
 
2372
+ grouped = isinstance(sample_id, list)
2373
+ group_size = len(sample_id) if grouped else None
3010
2374
  result = inner_without_validate(sample_id, preprocess_response)
3011
2375
 
3012
- _validate_result(result)
2376
+ _validate_result(result, grouped, group_size)
3013
2377
 
3014
2378
  if _called_from_inside_tl_decorator == 0 and _called_from_inside_tl_integration_test_decorator:
3015
- batch_warning(result, user_function.__name__)
3016
- result = np.expand_dims(result, axis=0)
2379
+ if grouped:
2380
+ # A grouped result is a list of per-sample arrays (never stacked, so a
2381
+ # B=1-only model can be fed one sample at a time). Add a batch dim to each
2382
+ # sample, mirroring the flat path's single-sample expand_dims.
2383
+ if isinstance(result, list):
2384
+ result = [np.expand_dims(r, axis=0) for r in result]
2385
+ else:
2386
+ batch_warning(result, user_function.__name__)
2387
+ result = np.expand_dims(result, axis=0)
3017
2388
  # Emit integration test event once per test
3018
2389
  try:
3019
2390
  emit_integration_event_once(AnalyticsEvent.INPUT_ENCODER_INTEGRATION_TEST, {
@@ -3034,8 +2405,15 @@ def tensorleap_input_encoder(name: str, channel_dim=_UNSET, model_input_index=No
3034
2405
  inner.node_mapping = NodeMapping(name, node_mapping_type)
3035
2406
 
3036
2407
  def mapping_inner(*args, **kwargs):
3037
- class TempMapping:
3038
- pass
2408
+ if _mapping_dataset_is_grouped:
2409
+ class TempMapping:
2410
+ def __getitem__(self, key):
2411
+ # Indexing a grouped input group (input_list[i]) selects a sample from the
2412
+ # same input source; the model wiring is identical to the un-grouped input.
2413
+ return self
2414
+ else:
2415
+ class TempMapping:
2416
+ pass
3039
2417
 
3040
2418
  ret = TempMapping()
3041
2419
  ret.node_mapping = mapping_inner.node_mapping
@@ -3065,15 +2443,10 @@ def tensorleap_gt_encoder(name: str):
3065
2443
  raise Exception(f'GT with name {name} already exists. '
3066
2444
  f'Please choose another')
3067
2445
 
3068
- def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
3069
- assert type(sample_id) == preprocess_response.sample_id_type, \
3070
- (f'{user_function.__name__}() validation failed: '
3071
- f'Argument sample_id should be as the same type as defined in the preprocess response '
3072
- f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
2446
+ def _validate_input_args(sample_id: Union[int, str, list], preprocess_response: PreprocessResponse):
2447
+ _validate_id_or_group(sample_id, preprocess_response, user_function.__name__)
3073
2448
 
3074
- def _validate_result(result):
3075
- validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray",
3076
- gt_flag=True)
2449
+ def _validate_single(result):
3077
2450
  assert isinstance(result, np.ndarray), \
3078
2451
  (f'{user_function.__name__}() validation failed: '
3079
2452
  f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
@@ -3081,6 +2454,14 @@ def tensorleap_gt_encoder(name: str):
3081
2454
  (f'{user_function.__name__}() validation failed: '
3082
2455
  f'The return type should be a numpy array of type float32. Got {result.dtype}.')
3083
2456
 
2457
+ def _validate_result(result, grouped=False, group_size=None):
2458
+ if not grouped:
2459
+ validate_output_structure(result, func_name=user_function.__name__, expected_type_name="np.ndarray",
2460
+ gt_flag=True)
2461
+ _validate_single(result)
2462
+ return
2463
+ _validate_grouped_result(result, group_size, user_function.__name__, _validate_single)
2464
+
3084
2465
  def inner_without_validate(sample_id, preprocess_response):
3085
2466
  global _called_from_inside_tl_decorator
3086
2467
  _called_from_inside_tl_decorator += 1
@@ -3097,19 +2478,27 @@ def tensorleap_gt_encoder(name: str):
3097
2478
  def inner(*args, **kwargs):
3098
2479
  if not _call_from_tl_platform:
3099
2480
  set_current("tensorleap_gt_encoder")
3100
- validate_args_structure(*args, types_order=[Union[int, str], PreprocessResponse],
2481
+ validate_args_structure(*args, types_order=[Union[int, str, list], PreprocessResponse],
3101
2482
  func_name=user_function.__name__, expected_names=["idx", "preprocess"], **kwargs)
3102
2483
  sample_id, preprocess_response = args
3103
2484
  _validate_input_args(sample_id, preprocess_response)
3104
2485
 
2486
+ grouped = isinstance(sample_id, list)
2487
+ group_size = len(sample_id) if grouped else None
3105
2488
  result = inner_without_validate(sample_id, preprocess_response)
3106
2489
 
3107
- _validate_result(result)
2490
+ _validate_result(result, grouped, group_size)
3108
2491
 
3109
2492
  if _called_from_inside_tl_decorator == 0 and _called_from_inside_tl_integration_test_decorator:
3110
- batch_warning(result, user_function.__name__)
3111
- result = np.expand_dims(result, axis=0)
3112
- _register_chain_artifact(result, 'ground_truth')
2493
+ if grouped:
2494
+ # A grouped result is a list of per-sample arrays (never stacked, so a
2495
+ # B=1-only model can be fed one sample at a time). Add a batch dim to each
2496
+ # sample, mirroring the flat path's single-sample expand_dims.
2497
+ if isinstance(result, list):
2498
+ result = [np.expand_dims(r, axis=0) for r in result]
2499
+ else:
2500
+ batch_warning(result, user_function.__name__)
2501
+ result = np.expand_dims(result, axis=0)
3113
2502
  # Emit integration test event once per test
3114
2503
  try:
3115
2504
  emit_integration_event_once(AnalyticsEvent.GT_ENCODER_INTEGRATION_TEST, {
@@ -3124,8 +2513,15 @@ def tensorleap_gt_encoder(name: str):
3124
2513
  inner.node_mapping = NodeMapping(name, NodeMappingType.GroundTruth)
3125
2514
 
3126
2515
  def mapping_inner(*args, **kwargs):
3127
- class TempMapping:
3128
- pass
2516
+ if _mapping_dataset_is_grouped:
2517
+ class TempMapping:
2518
+ def __getitem__(self, key):
2519
+ # Indexing a grouped GT group (gt_list[i]) selects a sample from the same
2520
+ # ground-truth source; wiring is identical to the un-grouped GT node.
2521
+ return self
2522
+ else:
2523
+ class TempMapping:
2524
+ pass
3129
2525
 
3130
2526
  ret = TempMapping()
3131
2527
  ret.node_mapping = mapping_inner.node_mapping
@@ -3407,11 +2803,7 @@ def tensorleap_status_table():
3407
2803
  return
3408
2804
 
3409
2805
  if _crashed["value"]:
3410
- crashed_at = _current_func['name']
3411
- if crashed_at:
3412
- print(f"\nScript crashed before completing all steps. crashed at function '{crashed_at}'.")
3413
- else:
3414
- print("\nScript crashed before completing all steps.")
2806
+ print(f"\nScript crashed before completing all steps. crashed at function '{_current_func['name']}'.")
3415
2807
  return
3416
2808
 
3417
2809
  print(ready_mess) if ready else print(
@@ -3486,11 +2878,9 @@ def tensorleap_status_table():
3486
2878
  row = _find_row(crashed_name)
3487
2879
  if row:
3488
2880
  row["Added to integration"] = CROSS
3489
- elif not crashed_name and _integration_test_started:
3490
- # Crash with no decorator currently running while an integration test has been
3491
- # entered = the test body / code flow itself failed; report that rather than
3492
- # blaming a decorator. Without a started test (a module-level crash between
3493
- # decorator registrations) the plain script-crash message is the truthful one.
2881
+ elif not crashed_name:
2882
+ # Crash with no decorator currently running = the integration-test body /
2883
+ # code flow itself failed; report that rather than blaming a decorator.
3494
2884
  code_mapping_failure[0] = 1
3495
2885
 
3496
2886
  traceback.print_exception(exc_type, exc_value, exc_traceback)