code-loader 1.0.208.dev8__py3-none-any.whl → 1.0.209__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.
@@ -111,6 +111,10 @@ class LeapBinder:
111
111
 
112
112
  self.mapping_connections: List[NodeConnection] = []
113
113
  self.integration_test_func: Optional[Callable[[str, PreprocessResponse], Any]] = None
114
+ # Set by LeapLoader.exec_script when running the dataset script failed, because that
115
+ # also resets setup_container: an empty container after a failure means "the script
116
+ # crashed", not "the user forgot to register". See get_preprocess_result.
117
+ self.previous_script_failure: Optional[BaseException] = None
114
118
 
115
119
  self.batch_size_to_validate: Optional[int] = None
116
120
  self.leap_analysis_configuration = LeapAnalysisConfiguration()
@@ -803,6 +807,13 @@ class LeapBinder:
803
807
  def get_preprocess_result(self) -> Dict[DataStateEnum, PreprocessResponse]:
804
808
  preprocess = self.setup_container.preprocess
805
809
  if preprocess is None:
810
+ if self.previous_script_failure is not None:
811
+ # Running the dataset script already failed once, and that reset the
812
+ # registrations (LeapLoader.exec_script). Blaming a missing
813
+ # set_preprocess call here would hide the actual crash.
814
+ raise Exception(
815
+ f"The dataset script failed before registering its handlers: "
816
+ f"{self.previous_script_failure}") from self.previous_script_failure
806
817
  raise Exception("Please make sure you call the leap_binder.set_preprocess method")
807
818
  preprocess_results = preprocess.function()
808
819
  preprocess_result_dict = {}
@@ -1762,7 +1762,16 @@ def _classify_custom_latent_space_signature(user_function) -> str:
1762
1762
  """Dataset-computed when a parameter is typed PreprocessResponse (a subclass or an
1763
1763
  Optional[...] of it included), model-computed otherwise."""
1764
1764
  params = list(inspect.signature(user_function).parameters.values())
1765
- hints = typing.get_type_hints(user_function)
1765
+ try:
1766
+ hints = typing.get_type_hints(user_function)
1767
+ except NameError as e:
1768
+ raise Exception(
1769
+ f"tensorleap_custom_latent_space validation failed: could not resolve the type "
1770
+ f"annotations of '{user_function.__name__}' ({e}). Tensorleap reads them to tell a "
1771
+ f"dataset-computed latent space from a model-computed one, so every annotation, the "
1772
+ f"return type included, must be resolvable when the function is decorated. Import the "
1773
+ f"annotated types at module level (not only under TYPE_CHECKING) or remove the "
1774
+ f"annotation.") from e
1766
1775
  preprocess_params = [p.name for p in params if _is_preprocess_response_type(hints.get(p.name))]
1767
1776
  if preprocess_params:
1768
1777
  positional = [p.name for p in params
@@ -1789,18 +1798,29 @@ def _classify_custom_latent_space_signature(user_function) -> str:
1789
1798
  f"If you are upgrading an existing project, this signature used to be accepted "
1790
1799
  f"unannotated as dataset-computed; add ': PreprocessResponse' to '{second}' to keep "
1791
1800
  f"the previous behavior.")
1801
+ if len(params) > 2 and not any(p.name in hints for p in params):
1802
+ names = [p.name for p in params]
1803
+ raise Exception(
1804
+ f"tensorleap_custom_latent_space validation failed: '{user_function.__name__}' has "
1805
+ f"parameters {names} and none of them has a type annotation, so Tensorleap cannot "
1806
+ f"tell whether this is a dataset-computed latent space (one sample at a time) or a "
1807
+ f"model-computed one (a batch of model tensors). Please annotate them:\n"
1808
+ f" dataset-computed: def {user_function.__name__}({names[0]}, {names[1]}: PreprocessResponse, ...) -> (d,)\n"
1809
+ f" model-computed: def {user_function.__name__}({names[0]}: np.ndarray, {names[1]}: np.ndarray, ...) -> (batch, d)")
1792
1810
  return 'model'
1793
1811
 
1794
1812
 
1795
1813
  def _model_latent_space_arg_names(user_function) -> List[str]:
1796
- argspec = inspect.getfullargspec(user_function)
1797
- arg_names = list(argspec.args)
1814
+ # inspect.signature follows functools.wraps' __wrapped__, as the classifier does.
1815
+ params = inspect.signature(user_function).parameters.values()
1816
+ arg_names = [p.name for p in params
1817
+ if p.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)]
1798
1818
  spr_count = 0
1799
- for arg_name, arg_type in argspec.annotations.items():
1800
- if arg_name == 'return':
1819
+ for param in params:
1820
+ if param.annotation is inspect.Parameter.empty:
1801
1821
  continue
1802
- _reject_stringized_sample_preprocess_response(user_function, arg_name, arg_type)
1803
- if arg_type == SamplePreprocessResponse:
1822
+ _reject_stringized_sample_preprocess_response(user_function, param.name, param.annotation)
1823
+ if param.annotation == SamplePreprocessResponse:
1804
1824
  spr_count += 1
1805
1825
  if spr_count > 1:
1806
1826
  raise Exception(
@@ -1882,7 +1902,7 @@ def _check_custom_latent_space_values(result: np.ndarray, ls_name: str, has_batc
1882
1902
  key=("tensorleap_custom_latent_space_nonfinite", ls_name),
1883
1903
  message=(
1884
1904
  f"Custom latent space '{ls_name}' returned NaN or inf. Those samples are left out of "
1885
- f"this latent space; if they exceed 5% of the evaluated samples the latent space is "
1905
+ f"this latent space; if they exceed 15% of the evaluated samples the latent space is "
1886
1906
  f"dropped."))
1887
1907
  peak = 0.0
1888
1908
  if result.size and result.dtype.kind == 'f':
code_loader/leaploader.py CHANGED
@@ -1,4 +1,5 @@
1
1
  # mypy: ignore-errors
2
+ import copy
2
3
  import importlib.util
3
4
  import inspect
4
5
  import io
@@ -7,6 +8,7 @@ import sys
7
8
  from contextlib import redirect_stdout
8
9
  from functools import lru_cache
9
10
  from pathlib import Path
11
+ from types import TracebackType
10
12
  from typing import Dict, List, Iterable, Set, FrozenSet, Union, Any, Type, Optional, Callable, Tuple
11
13
 
12
14
  import numpy as np
@@ -33,6 +35,44 @@ from code_loader.utils import get_root_exception_file_and_line_number, get_metad
33
35
  validate_autoregressive_state_types, autoregressive_nests_equal, is_absent_metadata_value, \
34
36
  sample_preprocess_response_arg_name
35
37
 
38
+ _code_loader_dir = str(Path(__file__).parent)
39
+
40
+
41
+ def _innermost_frame_outside_code_loader(e: BaseException) -> Optional[TracebackType]:
42
+ """The deepest traceback frame that is not code_loader's own code, if any.
43
+
44
+ That is the line the user can go and look at. The deepest frame overall is often
45
+ ours — a validation that raises, or a builtin we wrapped — and "raised at
46
+ leapbinder.py" tells the user nothing about their script.
47
+ """
48
+ frame_in_user_code = None
49
+ _traceback = e.__traceback__
50
+ while _traceback is not None:
51
+ if not _traceback.tb_frame.f_code.co_filename.startswith(_code_loader_dir):
52
+ frame_in_user_code = _traceback
53
+ _traceback = _traceback.tb_next
54
+ return frame_in_user_code
55
+
56
+
57
+ def describe_script_exception(e: BaseException) -> str:
58
+ """One line describing a failure raised by user code: its type, its message and where it happened.
59
+
60
+ ``repr(e)`` on its own throws away what the user needs most: ``repr`` of an OSError
61
+ drops the filename (``FileNotFoundError(2, 'No such file or directory')`` — but not
62
+ *which* file), and no ``repr`` says which line of the integration script raised. Both
63
+ are what turns "the dataset script crashed" into an error the user can act on.
64
+ """
65
+ message = getattr(e, 'message', None)
66
+ if not isinstance(message, str) or not message:
67
+ message = str(e)
68
+ description = f'{type(e).__name__}: {message}' if message else repr(e)
69
+
70
+ frame_in_user_code = _innermost_frame_outside_code_loader(e)
71
+ if frame_in_user_code is not None:
72
+ file_name = Path(frame_in_user_code.tb_frame.f_code.co_filename).name
73
+ description = f'{description} (raised at {file_name}, line {frame_in_user_code.tb_lineno})'
74
+ return description
75
+
36
76
 
37
77
  def _serialize_sim_bounds(bounds) -> dict:
38
78
  if isinstance(bounds, (FloatBounds, IntBounds)):
@@ -55,6 +95,8 @@ class LeapLoader(LeapLoaderBase):
55
95
  self._preprocess_result_cached = None
56
96
  self._synthetic_lookup: Dict[str, Tuple[PreprocessResponse, Any]] = {}
57
97
  self._synthetic_populator: Optional[Callable[[str], None]] = None
98
+ # The first exec_script failure, re-raised by every later call. See exec_script.
99
+ self._exec_script_error: Optional[BaseException] = None
58
100
 
59
101
  try:
60
102
  from code_loader.mixpanel_tracker import track_code_loader_loaded
@@ -66,9 +108,33 @@ class LeapLoader(LeapLoaderBase):
66
108
  except Exception:
67
109
  pass
68
110
 
111
+ def _remember_exec_script_error(self, error: BaseException) -> BaseException:
112
+ # Also recorded on the binder: the failure handlers below wipe its setup_container,
113
+ # so anything that reaches the binder afterwards (another LeapLoader in the same
114
+ # process, say) can report the real failure instead of an empty container.
115
+ global_leap_binder.previous_script_failure = error
116
+ self._exec_script_error = error
117
+ return error
118
+
69
119
  @lru_cache()
70
120
  def exec_script(self) -> None:
71
121
  from code_loader.inner_leap_binder import leapbinder_decorators as _leap_dec
122
+
123
+ # A failed exec_script is sticky. lru_cache does not cache exceptions, so without
124
+ # this every later caller re-ran the script — and the re-run reports the WRONG
125
+ # error: the handlers below reset global_leap_binder.setup_container, while
126
+ # re-importing the entry file does not re-register handlers that live in modules
127
+ # already in sys.modules. The second run therefore raised "Please make sure you
128
+ # call the leap_binder.set_preprocess method", burying the real cause (a missing
129
+ # file, a bad path, a typo'd import). Callers do retry — the engine's samples
130
+ # generator calls this once per loop iteration — so the real error was logged once
131
+ # and then drowned in generic repeats.
132
+ if self._exec_script_error is not None:
133
+ # A fresh copy each time: re-raising the stored object would append this call's
134
+ # frames to its __traceback__, so a caller retrying in a loop grows it (and keeps
135
+ # every retry's frames alive) without bound.
136
+ error = self._exec_script_error
137
+ raise copy.copy(error) from error.__cause__
72
138
  try:
73
139
  os.environ[mapping_runtime_mode_env_var_mame] = 'TRUE'
74
140
  self.evaluate_module()
@@ -98,16 +164,19 @@ class LeapLoader(LeapLoaderBase):
98
164
  if is_grouped else
99
165
  PreprocessResponse(state=DataStateType.training, length=0))
100
166
  global_leap_binder.integration_test_func(None, mapping_preprocess)
167
+ global_leap_binder.previous_script_failure = None
101
168
  except TypeError as e:
102
169
  import traceback
103
170
  global_leap_binder.setup_container = DatasetIntegrationSetup()
104
171
  if "leap_binder.set_metadata(" in traceback.format_exc(5):
105
- raise DeprecationWarning(
106
- "Please remove the metadata_type on leap_binder.set_metadata in your dataset script")
107
- raise DatasetScriptException(getattr(e, 'message', repr(e))) from e
172
+ raise self._remember_exec_script_error(DeprecationWarning(
173
+ "Please remove the metadata_type on leap_binder.set_metadata in your dataset script"))
174
+ raise self._remember_exec_script_error(
175
+ DatasetScriptException(describe_script_exception(e))) from e
108
176
  except Exception as e:
109
177
  global_leap_binder.setup_container = DatasetIntegrationSetup()
110
- raise DatasetScriptException(getattr(e, 'message', repr(e))) from e
178
+ raise self._remember_exec_script_error(
179
+ DatasetScriptException(describe_script_exception(e))) from e
111
180
  finally:
112
181
  # ensure that the environment variable is removed after the script execution
113
182
  _leap_dec._mapping_dataset_is_grouped = False
@@ -1513,8 +1582,9 @@ class LeapLoader(LeapLoaderBase):
1513
1582
  # Preprocess runs only when the function asks for a SamplePreprocessResponse; the metrics
1514
1583
  # pod that calls this has no other reason to pay for it.
1515
1584
  if preprocess_response_arg_name is not None:
1516
- input_tensors_by_arg_name[preprocess_response_arg_name] = SamplePreprocessResponse(
1517
- sample_ids, self._preprocess_result()[state])
1585
+ input_tensors_by_arg_name = {
1586
+ **input_tensors_by_arg_name,
1587
+ preprocess_response_arg_name: SamplePreprocessResponse(sample_ids, self._preprocess_result()[state])}
1518
1588
 
1519
1589
  return handler.function(**input_tensors_by_arg_name)
1520
1590
 
code_loader/utils.py CHANGED
@@ -250,8 +250,8 @@ def autoregressive_nests_equal(a: Any, b: Any) -> bool:
250
250
 
251
251
 
252
252
  def sample_preprocess_response_arg_name(func: Callable[..., Any]) -> Optional[str]:
253
- # 'return' lives in annotations too and must never be mistaken for a parameter.
254
- for arg_name, arg_type in inspect.getfullargspec(func).annotations.items():
255
- if arg_name != 'return' and arg_type == SamplePreprocessResponse:
256
- return arg_name
253
+ # inspect.signature follows functools.wraps' __wrapped__; getfullargspec does not.
254
+ for param in inspect.signature(func).parameters.values():
255
+ if param.annotation == SamplePreprocessResponse:
256
+ return param.name
257
257
  return None
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: code-loader
3
- Version: 1.0.208.dev8
3
+ Version: 1.0.209
4
4
  Summary:
5
- Home-page: https://github.com/tensorleap/code-loader
6
5
  License: MIT
6
+ License-File: LICENSE
7
7
  Author: dorhar
8
8
  Author-email: doron.harnoy@tensorleap.ai
9
9
  Requires-Python: >=3.8,<3.13
@@ -20,6 +20,7 @@ Requires-Dist: numpy (>=2.3.2,<3.0.0) ; python_version >= "3.11" and python_vers
20
20
  Requires-Dist: psutil (>=5.9.5,<6.0.0)
21
21
  Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
22
22
  Requires-Dist: requests (>=2.32.3,<3.0.0)
23
+ Project-URL: Homepage, https://github.com/tensorleap/code-loader
23
24
  Project-URL: Repository, https://github.com/tensorleap/code-loader
24
25
  Description-Content-Type: text/markdown
25
26
 
@@ -1,4 +1,3 @@
1
- LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
2
1
  code_loader/__init__.py,sha256=outxRQ0M-zMfV0QGVJmAed5qWfRmyD0TV6-goEGAzBw,406
3
2
  code_loader/contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
3
  code_loader/contract/datasetclasses.py,sha256=yNEPIyZqCO54fKBgmgbFIKEMVBzvpf4n8U2zmPhXv88,18110
@@ -21,18 +20,18 @@ code_loader/experiment_api/types.py,sha256=MY8xFARHwdVA7p4dxyhD60ShmttgTvb4qdp1o
21
20
  code_loader/experiment_api/utils.py,sha256=XZHtxge12TS4H4-8PjV3sKuhp8Ud6ojAiIzTZJEqBqc,3304
22
21
  code_loader/experiment_api/workingspace_config_utils.py,sha256=DLzXQCg4dgTV_YgaSbeTVzq-2ja_SQw4zi7LXwKL9cY,990
23
22
  code_loader/inner_leap_binder/__init__.py,sha256=koOlJyMNYzGbEsoIbXathSmQ-L38N_pEXH_HvL7beXU,99
24
- code_loader/inner_leap_binder/leapbinder.py,sha256=fplNN3TfJHg79YpEPHKK3b6CxrR7W0ugDeHhAZfYty0,62784
25
- code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=paUtnncLn-4iFUJhqEOg3rPtKh9DoS3_HVgGUgOz8c4,210906
26
- code_loader/leaploader.py,sha256=DiVCs076JP21HXBfpKkzs3Qaumg8Cz26q1tIc4C-kcg,97552
23
+ code_loader/inner_leap_binder/leapbinder.py,sha256=EhUD4OLSBuVslKYgiXFDoufnfatwCb0LQe_gH9kg5w0,63615
24
+ code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=WNaV9M02Mh8OkPiOrZlnmj_GquGKTa1IxIsaLNk6R2E,212474
25
+ code_loader/leaploader.py,sha256=e7jNqgurKp8o6zbjeXMwPp6Fm3Eltb9VCwv_5IxLENk,101375
27
26
  code_loader/leaploaderbase.py,sha256=JzgpEfY-kNUWbWUb_cZ1G1zHo6oSci6QhT7hqw3E1Jg,12371
28
27
  code_loader/mixpanel_tracker.py,sha256=rNwRmFifNbdUoqLQvvhhgpKczWpWiEmd8MfyJe27sxw,9131
29
28
  code_loader/plot_functions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
30
29
  code_loader/plot_functions/plot_functions.py,sha256=2DC-zlVaN13P4VNx5d8csgs80C6SisaeP1-Kq2LW7iM,16075
31
30
  code_loader/plot_functions/visualize.py,sha256=gsBAYYkwMh7jIpJeDMPS8G4CW-pxwx6LznoQIvi4vpo,657
32
- code_loader/utils.py,sha256=v6VraCdbFADoNwNx5TH89BLnZ6yfPoWMkyJrqQ_usFc,12377
31
+ code_loader/utils.py,sha256=Yuv2hPx4G70RV2x0Fc_UCube9BLpEryyq4cuKIcsq7s,12347
33
32
  code_loader/visualizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
33
  code_loader/visualizers/default_visualizers.py,sha256=grTPin_lCE9aci8i8CqA7DqQwAyXRB7_EamA3na_pls,5438
35
- code_loader-1.0.208.dev8.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
36
- code_loader-1.0.208.dev8.dist-info/METADATA,sha256=Zv4Z5dCnspuqPU778nnj7nEOkmHqIhxBg44L_ZwRIUw,1095
37
- code_loader-1.0.208.dev8.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
38
- code_loader-1.0.208.dev8.dist-info/RECORD,,
34
+ code_loader-1.0.209.dist-info/METADATA,sha256=BtmLGfi5uX44twtzoko8cZskG5Qj0LSJUNY43JRzq0c,1124
35
+ code_loader-1.0.209.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
36
+ code_loader-1.0.209.dist-info/licenses/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
37
+ code_loader-1.0.209.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.9.0
2
+ Generator: poetry-core 2.4.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 TensorLeap
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.