jonghanko commited on
Commit
9d8a3f2
·
verified ·
1 Parent(s): dc37b4c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi +0 -0
  2. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/__init__.pyi +0 -0
  3. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_aoti.pyi +164 -0
  4. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_autograd.pyi +142 -0
  5. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_cpu.pyi +13 -0
  6. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_cudnn.pyi +14 -0
  7. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi +1 -0
  8. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi +26 -0
  9. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi +853 -0
  10. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi +188 -0
  11. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi +32 -0
  12. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi +4 -0
  13. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi +13 -0
  14. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi +80 -0
  15. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/guards.pyi +438 -0
  16. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi +9 -0
  17. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi +24 -0
  18. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_functionalization.pyi +16 -0
  19. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_functions.pyi +19 -0
  20. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_functorch.pyi +86 -0
  21. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi +4 -0
  22. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_itt.pyi +5 -0
  23. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi +202 -0
  24. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_lazy.pyi +26 -0
  25. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi +12 -0
  26. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_monitor.pyi +58 -0
  27. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_nn.pyi +295 -0
  28. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_nvtx.pyi +9 -0
  29. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_onnx.pyi +39 -0
  30. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_profiler.pyi +246 -0
  31. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_verbose.pyi +3 -0
  32. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/__init__.py +0 -0
  33. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/_conversions.cpython-310.pyc +0 -0
  34. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/fft.cpython-310.pyc +0 -0
  35. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/_conversions.py +119 -0
  36. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/fft.py +592 -0
  37. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py +343 -0
  38. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
  39. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/__init__.py +1 -0
  40. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-310.pyc +0 -0
  41. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py +1289 -0
  42. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-310.pyc +0 -0
  43. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/special/__init__.py +236 -0
  44. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/special/__pycache__/__init__.cpython-310.pyc +0 -0
  45. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__init__.py +0 -0
  46. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__pycache__/__init__.cpython-310.pyc +0 -0
  47. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__pycache__/cli_function_profiler.cpython-310.pyc +0 -0
  48. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__pycache__/compile_time_profiler.cpython-310.pyc +0 -0
  49. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/cli_function_profiler.py +321 -0
  50. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/compile_time_profiler.py +224 -0
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/__init__.pyi ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_aoti.pyi ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import c_void_p
2
+ from typing import overload, Protocol
3
+
4
+ from torch import Tensor
5
+
6
+ # Defined in torch/csrc/inductor/aoti_runner/pybind.cpp
7
+
8
+ # Tensor to AtenTensorHandle
9
+ def unsafe_alloc_void_ptrs_from_tensors(tensors: list[Tensor]) -> list[c_void_p]: ...
10
+ def unsafe_alloc_void_ptr_from_tensor(tensor: Tensor) -> c_void_p: ...
11
+
12
+ # AtenTensorHandle to Tensor
13
+ def alloc_tensors_by_stealing_from_void_ptrs(
14
+ handles: list[c_void_p],
15
+ ) -> list[Tensor]: ...
16
+ def alloc_tensor_by_stealing_from_void_ptr(
17
+ handle: c_void_p,
18
+ ) -> Tensor: ...
19
+
20
+ class AOTIModelContainerRunner(Protocol):
21
+ def run(
22
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
23
+ ) -> list[Tensor]: ...
24
+ def get_call_spec(self) -> list[str]: ...
25
+ def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
26
+ def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
27
+ def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
28
+ def update_constant_buffer(
29
+ self,
30
+ tensor_map: dict[str, Tensor],
31
+ use_inactive: bool,
32
+ validate_full_updates: bool,
33
+ user_managed: bool = ...,
34
+ ) -> None: ...
35
+ def swap_constant_buffer(self) -> None: ...
36
+ def free_inactive_constant_buffer(self) -> None: ...
37
+
38
+ class AOTIModelContainerRunnerCpu:
39
+ def __init__(self, model_so_path: str, num_models: int) -> None: ...
40
+ def run(
41
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
42
+ ) -> list[Tensor]: ...
43
+ def get_call_spec(self) -> list[str]: ...
44
+ def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
45
+ def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
46
+ def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
47
+ def update_constant_buffer(
48
+ self,
49
+ tensor_map: dict[str, Tensor],
50
+ use_inactive: bool,
51
+ validate_full_updates: bool,
52
+ user_managed: bool = ...,
53
+ ) -> None: ...
54
+ def swap_constant_buffer(self) -> None: ...
55
+ def free_inactive_constant_buffer(self) -> None: ...
56
+
57
+ class AOTIModelContainerRunnerCuda:
58
+ @overload
59
+ def __init__(self, model_so_path: str, num_models: int) -> None: ...
60
+ @overload
61
+ def __init__(
62
+ self, model_so_path: str, num_models: int, device_str: str
63
+ ) -> None: ...
64
+ @overload
65
+ def __init__(
66
+ self, model_so_path: str, num_models: int, device_str: str, cubin_dir: str
67
+ ) -> None: ...
68
+ def run(
69
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
70
+ ) -> list[Tensor]: ...
71
+ def get_call_spec(self) -> list[str]: ...
72
+ def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
73
+ def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
74
+ def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
75
+ def update_constant_buffer(
76
+ self,
77
+ tensor_map: dict[str, Tensor],
78
+ use_inactive: bool,
79
+ validate_full_updates: bool,
80
+ user_managed: bool = ...,
81
+ ) -> None: ...
82
+ def swap_constant_buffer(self) -> None: ...
83
+ def free_inactive_constant_buffer(self) -> None: ...
84
+
85
+ class AOTIModelContainerRunnerXpu:
86
+ @overload
87
+ def __init__(self, model_so_path: str, num_models: int) -> None: ...
88
+ @overload
89
+ def __init__(
90
+ self, model_so_path: str, num_models: int, device_str: str
91
+ ) -> None: ...
92
+ @overload
93
+ def __init__(
94
+ self, model_so_path: str, num_models: int, device_str: str, kernel_bin_dir: str
95
+ ) -> None: ...
96
+ def run(
97
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
98
+ ) -> list[Tensor]: ...
99
+ def get_call_spec(self) -> list[str]: ...
100
+ def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
101
+ def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
102
+ def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
103
+ def update_constant_buffer(
104
+ self,
105
+ tensor_map: dict[str, Tensor],
106
+ use_inactive: bool,
107
+ validate_full_updates: bool,
108
+ user_managed: bool = ...,
109
+ ) -> None: ...
110
+ def swap_constant_buffer(self) -> None: ...
111
+ def free_inactive_constant_buffer(self) -> None: ...
112
+
113
+ class AOTIModelContainerRunnerMps:
114
+ def __init__(self, model_so_path: str, num_models: int) -> None: ...
115
+ def run(
116
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
117
+ ) -> list[Tensor]: ...
118
+ def get_call_spec(self) -> list[str]: ...
119
+ def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
120
+ def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
121
+ def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
122
+ def update_constant_buffer(
123
+ self,
124
+ tensor_map: dict[str, Tensor],
125
+ use_inactive: bool,
126
+ validate_full_updates: bool,
127
+ user_managed: bool = ...,
128
+ ) -> None: ...
129
+ def swap_constant_buffer(self) -> None: ...
130
+ def free_inactive_constant_buffer(self) -> None: ...
131
+
132
+ # Defined in torch/csrc/inductor/aoti_package/pybind.cpp
133
+ class AOTIModelPackageLoader:
134
+ def __init__(
135
+ self,
136
+ model_package_path: str,
137
+ model_name: str,
138
+ run_single_threaded: bool,
139
+ num_runners: int,
140
+ device_index: int,
141
+ ) -> None: ...
142
+ def get_metadata(self) -> dict[str, str]: ...
143
+ def run(
144
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
145
+ ) -> list[Tensor]: ...
146
+ def boxed_run(
147
+ self, inputs: list[Tensor], stream_handle: c_void_p = ...
148
+ ) -> list[Tensor]: ...
149
+ def get_call_spec(self) -> list[str]: ...
150
+ def get_constant_fqns(self) -> list[str]: ...
151
+ def load_constants(
152
+ self,
153
+ constants_map: dict[str, Tensor],
154
+ use_inactive: bool,
155
+ check_full_update: bool,
156
+ user_managed: bool = ...,
157
+ ) -> None: ...
158
+ def update_constant_buffer(
159
+ self,
160
+ tensor_map: dict[str, Tensor],
161
+ use_inactive: bool,
162
+ validate_full_updates: bool,
163
+ user_managed: bool = ...,
164
+ ) -> None: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_autograd.pyi ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from enum import Enum
3
+ from typing import Any, Callable
4
+
5
+ import torch
6
+ from torch._C._profiler import (
7
+ _ProfilerEvent,
8
+ ActiveProfilerType,
9
+ ProfilerActivity,
10
+ ProfilerConfig,
11
+ )
12
+
13
+ # Defined in torch/csrc/autograd/init.cpp
14
+
15
+ class DeviceType(Enum):
16
+ CPU = ...
17
+ CUDA = ...
18
+ XPU = ...
19
+ MKLDNN = ...
20
+ OPENGL = ...
21
+ OPENCL = ...
22
+ IDEEP = ...
23
+ HIP = ...
24
+ FPGA = ...
25
+ MAIA = ...
26
+ XLA = ...
27
+ MTIA = ...
28
+ MPS = ...
29
+ HPU = ...
30
+ Meta = ...
31
+ Vulkan = ...
32
+ Metal = ...
33
+ PrivateUse1 = ...
34
+
35
+ class ProfilerEvent:
36
+ def cpu_elapsed_us(self, other: ProfilerEvent) -> float: ...
37
+ def cpu_memory_usage(self) -> int: ...
38
+ def cuda_elapsed_us(self, other: ProfilerEvent) -> float: ...
39
+ def privateuse1_elapsed_us(self, other: ProfilerEvent) -> float: ...
40
+ def cuda_memory_usage(self) -> int: ...
41
+ def device(self) -> int: ...
42
+ def handle(self) -> int: ...
43
+ def has_cuda(self) -> bool: ...
44
+ def is_remote(self) -> bool: ...
45
+ def kind(self) -> int: ...
46
+ def name(self) -> str: ...
47
+ def node_id(self) -> int: ...
48
+ def sequence_nr(self) -> int: ...
49
+ def shapes(self) -> list[list[int]]: ...
50
+ def thread_id(self) -> int: ...
51
+ def flops(self) -> float: ...
52
+ def is_async(self) -> bool: ...
53
+
54
+ class _KinetoEvent:
55
+ def name(self) -> str: ...
56
+ def overload_name(self) -> str: ...
57
+ def device_index(self) -> int: ...
58
+ def device_resource_id(self) -> int: ...
59
+ def start_ns(self) -> int: ...
60
+ def end_ns(self) -> int: ...
61
+ def duration_ns(self) -> int: ...
62
+ def is_async(self) -> bool: ...
63
+ def linked_correlation_id(self) -> int: ...
64
+ def shapes(self) -> list[list[int]]: ...
65
+ def dtypes(self) -> list[str]: ...
66
+ def concrete_inputs(self) -> list[Any]: ...
67
+ def kwinputs(self) -> dict[str, Any]: ...
68
+ def device_type(self) -> DeviceType: ...
69
+ def start_thread_id(self) -> int: ...
70
+ def end_thread_id(self) -> int: ...
71
+ def correlation_id(self) -> int: ...
72
+ def fwd_thread_id(self) -> int: ...
73
+ def stack(self) -> list[str]: ...
74
+ def scope(self) -> int: ...
75
+ def sequence_nr(self) -> int: ...
76
+ def flops(self) -> int: ...
77
+ def cuda_elapsed_us(self) -> int: ...
78
+ def privateuse1_elapsed_us(self) -> int: ...
79
+ def is_user_annotation(self) -> bool: ...
80
+ def is_hidden_event(self) -> bool: ...
81
+
82
+ class _ProfilerResult:
83
+ def events(self) -> list[_KinetoEvent]: ...
84
+ def legacy_events(self) -> list[list[ProfilerEvent]]: ...
85
+ def save(self, path: str) -> None: ...
86
+ def experimental_event_tree(self) -> list[_ProfilerEvent]: ...
87
+ def trace_start_ns(self) -> int: ...
88
+
89
+ class SavedTensor: ...
90
+
91
+ def _enable_profiler(
92
+ config: ProfilerConfig,
93
+ activities: set[ProfilerActivity],
94
+ ) -> None: ...
95
+ def _prepare_profiler(
96
+ config: ProfilerConfig,
97
+ activities: set[ProfilerActivity],
98
+ ) -> None: ...
99
+ def _toggle_collection_dynamic(
100
+ enable: bool,
101
+ activities: set[ProfilerActivity],
102
+ ) -> None: ...
103
+ def _disable_profiler() -> _ProfilerResult: ...
104
+ def _profiler_enabled() -> bool: ...
105
+ def _add_metadata_json(key: str, value: str) -> None: ...
106
+ def _kineto_step() -> None: ...
107
+ def _get_current_graph_task_keep_graph() -> bool: ...
108
+ def _get_sequence_nr() -> int: ...
109
+ def kineto_available() -> bool: ...
110
+ def _record_function_with_args_enter(name: str, *args) -> torch.Tensor: ...
111
+ def _record_function_with_args_exit(handle: torch.Tensor) -> None: ...
112
+ def _supported_activities() -> set[ProfilerActivity]: ...
113
+ def _enable_record_function(enable: bool) -> None: ...
114
+ def _set_empty_test_observer(is_global: bool, sampling_prob: float) -> None: ...
115
+ def _push_saved_tensors_default_hooks(
116
+ pack_hook: Callable[[torch.Tensor], Any],
117
+ unpack_hook: Callable[[Any], torch.Tensor],
118
+ ) -> None: ...
119
+ def _pop_saved_tensors_default_hooks() -> None: ...
120
+ def _top_saved_tensors_default_hooks(
121
+ ignore_is_tracing: bool,
122
+ ) -> tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]]: ...
123
+ def _unsafe_set_version_counter(
124
+ t: tuple[torch.Tensor, ...], prev_version: tuple[int, ...]
125
+ ) -> None: ...
126
+ def _enable_profiler_legacy(config: ProfilerConfig) -> None: ...
127
+ def _disable_profiler_legacy() -> list[list[ProfilerEvent]]: ...
128
+ def _profiler_type() -> ActiveProfilerType: ...
129
+ def _saved_tensors_hooks_enable() -> None: ...
130
+ def _saved_tensors_hooks_disable(message: str, fail_if_non_empty=True) -> None: ...
131
+ def _saved_tensors_hooks_get_disabled_error_message() -> str | None: ...
132
+ def _saved_tensors_hooks_set_tracing(is_tracing: bool) -> bool: ...
133
+
134
+ class CreationMeta(Enum):
135
+ DEFAULT = ...
136
+ IN_CUSTOM_FUNCTION = ...
137
+ MULTI_OUTPUT_NODE = ...
138
+ NO_GRAD_MODE = ...
139
+ INFERENCE_MODE = ...
140
+
141
+ def _set_creation_meta(t: torch.Tensor, creation_meta: CreationMeta) -> None: ...
142
+ def _get_creation_meta(t: torch.Tensor) -> CreationMeta: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_cpu.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.types import _bool, _int
2
+
3
+ # Defined in torch/csrc/cpu/Module.cpp
4
+
5
+ def _is_avx2_supported() -> _bool: ...
6
+ def _is_avx512_supported() -> _bool: ...
7
+ def _is_avx512_vnni_supported() -> _bool: ...
8
+ def _is_avx512_bf16_supported() -> _bool: ...
9
+ def _is_amx_tile_supported() -> _bool: ...
10
+ def _is_amx_fp16_supported() -> _bool: ...
11
+ def _init_amx() -> _bool: ...
12
+ def _L1d_cache_size() -> _int: ...
13
+ def _L2_cache_size() -> _int: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_cudnn.pyi ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import IntEnum
2
+
3
+ # Defined in torch/csrc/cuda/shared/cudnn.cpp
4
+ is_cuda: bool
5
+
6
+ def getRuntimeVersion() -> tuple[int, int, int]: ...
7
+ def getCompileVersion() -> tuple[int, int, int]: ...
8
+ def getVersionInt() -> int: ...
9
+
10
+ class RNNMode(IntEnum):
11
+ rnn_relu = ...
12
+ rnn_tanh = ...
13
+ lstm = ...
14
+ gru = ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi ADDED
@@ -0,0 +1 @@
 
 
1
+ def getVersionInt() -> int: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import torch
4
+
5
+ # This module is defined in torch/csrc/distributed/autograd/init.cpp
6
+
7
+ class DistAutogradContext:
8
+ def _context_id(self) -> int: ...
9
+ def _recv_functions(self) -> dict[int, Any]: ...
10
+ def _send_functions(self) -> dict[int, Any]: ...
11
+ def _known_worker_ids(self) -> set[int]: ...
12
+
13
+ def _new_context() -> DistAutogradContext: ...
14
+ def _release_context(context_id: int) -> None: ...
15
+ def _get_max_id() -> int: ...
16
+ def _is_valid_context(worker_id: int) -> bool: ...
17
+ def _retrieve_context(context_id: int) -> DistAutogradContext: ...
18
+ def _current_context() -> DistAutogradContext: ...
19
+ def _init(worker_id: int) -> None: ...
20
+ def _get_debug_info() -> dict[str, str]: ...
21
+ def backward(
22
+ context_id: int,
23
+ roots: list[torch.Tensor],
24
+ retain_graph: bool = False,
25
+ ) -> None: ...
26
+ def get_gradients(context_id: int) -> dict[torch.Tensor, torch.Tensor]: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # mypy: disable-error-code="type-arg"
3
+ from datetime import timedelta
4
+ from enum import Enum
5
+ from typing import Any, Optional, overload, Union
6
+
7
+ import torch
8
+ from torch import Tensor
9
+ from torch._C import ScriptObject
10
+ from torch._C._autograd import DeviceType
11
+ from torch.futures import Future
12
+
13
+ # This module is defined in torch/csrc/distributed/c10d/init.cpp
14
+
15
+ _DEFAULT_FIRST_BUCKET_BYTES: int
16
+ _DEFAULT_NO_TIMEOUT: timedelta
17
+ _DEFAULT_PG_TIMEOUT: timedelta
18
+ _DEFAULT_PG_NCCL_TIMEOUT: timedelta
19
+
20
+ class BuiltinCommHookType(Enum):
21
+ ALLREDUCE = ...
22
+ FP16_COMPRESS = ...
23
+
24
+ def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ...
25
+ def _register_builtin_comm_hook(
26
+ reducer: Reducer,
27
+ comm_hook_type: BuiltinCommHookType,
28
+ ): ...
29
+ def _set_global_rank(rank: int) -> None: ...
30
+ def _hash_tensors(tensors: list[Tensor]) -> int: ...
31
+
32
+ class GradBucket:
33
+ def index(self) -> int: ...
34
+ def buffer(self) -> Tensor: ...
35
+ def gradients(self) -> list[Tensor]: ...
36
+ def is_last(self) -> bool: ...
37
+ def set_buffer(self, tensor: Tensor) -> None: ...
38
+ def parameters(self) -> list[Tensor]: ...
39
+
40
+ class Reducer:
41
+ def __init__(
42
+ self,
43
+ params: list[Tensor],
44
+ bucket_indices: list[list[int]],
45
+ per_bucket_size_limits: list[int],
46
+ process_group: ProcessGroup,
47
+ expect_sparse_gradients: list[bool] = ...,
48
+ bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp
49
+ find_unused_parameters: bool = ...,
50
+ gradient_as_bucket_view: bool = ...,
51
+ param_to_name_mapping: dict[int, str] = ...,
52
+ first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp
53
+ skip_all_reduce_unused_params: bool = ...,
54
+ use_python_reducer: bool = ...,
55
+ ) -> None: ...
56
+ def prepare_for_forward(self) -> None: ...
57
+ def prepare_for_backward(self, output: list[Tensor]) -> None: ...
58
+ def get_backward_stats(self) -> list[int]: ...
59
+ def _install_post_backward_futures(self, futures: list[Future]) -> None: ...
60
+ def _rebuild_buckets(self) -> bool: ...
61
+ def _get_zeros_like_grad_buckets(self) -> list[GradBucket]: ...
62
+ def _push_all_rebuilt_params(self) -> None: ...
63
+ def _set_forward_pass_work_handle(
64
+ self,
65
+ work: Work,
66
+ use_static_world_size: bool,
67
+ ): ...
68
+ def _get_local_used_map(self) -> Tensor: ...
69
+ def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ...
70
+ def _set_static_graph(self) -> None: ...
71
+ def _run_comm_hook(self, bucket: GradBucket) -> Future: ...
72
+ def set_logger(self, logger: Logger) -> None: ...
73
+ def _remove_autograd_hooks(self) -> None: ...
74
+ def _check_reducer_finalized(self) -> None: ...
75
+ def _set_sparse_metadata(self, global_unique_ids: dict[str, Tensor]) -> None: ...
76
+ def _reset_state(self) -> None: ...
77
+ def _update_process_group(self, new_process_group: ProcessGroup) -> None: ...
78
+
79
+ class DDPLoggingData:
80
+ strs_map: dict[str, str]
81
+ ints_map: dict[str, int]
82
+
83
+ class Logger:
84
+ def __init__(self, reducer: Reducer) -> None: ...
85
+ def set_construction_data_and_log(
86
+ self,
87
+ module_name: str,
88
+ device_ids: list[int],
89
+ output_device: int,
90
+ broadcast_buffers: bool,
91
+ has_sync_bn: bool,
92
+ static_graph: bool,
93
+ ): ...
94
+ def set_runtime_stats_and_log(self) -> None: ...
95
+ def set_error_and_log(self, error: str) -> None: ...
96
+ def _get_ddp_logging_data(self) -> DDPLoggingData: ...
97
+ def _set_comm_hook_name(self, comm_hook: str) -> None: ...
98
+ def _set_uneven_input_join(self) -> None: ...
99
+ def _set_static_graph(self) -> None: ...
100
+
101
+ class _WorkerServer:
102
+ def __init__(self, socket_path: str) -> None: ...
103
+ def shutdown(self) -> None: ...
104
+
105
+ def get_debug_level(): ...
106
+ def set_debug_level(): ...
107
+ def set_debug_level_from_env(): ...
108
+
109
+ class DebugLevel(Enum):
110
+ OFF = ...
111
+ INFO = ...
112
+ DETAIL = ...
113
+
114
+ class ReduceOp:
115
+ def __init__(self, op: RedOpType) -> None: ...
116
+
117
+ SUM: RedOpType = ...
118
+ AVG: RedOpType = ...
119
+ PRODUCT: RedOpType = ...
120
+ MIN: RedOpType = ...
121
+ MAX: RedOpType = ...
122
+ BAND: RedOpType = ...
123
+ BOR: RedOpType = ...
124
+ BXOR: RedOpType = ...
125
+ PREMUL_SUM: RedOpType = ...
126
+ UNUSED: RedOpType = ...
127
+
128
+ # mypy error being ignored:
129
+ # Detected enum "torch._C._distributed_c10d.ReduceOp.RedOpType" in a type
130
+ # stub with zero members. There is a chance this is due to a recent change
131
+ # in the semantics of enum membership. If so, use `member = value` to mark
132
+ # an enum member, instead of `member: type`
133
+ class RedOpType(Enum): ... # type: ignore[misc]
134
+
135
+ class BroadcastOptions:
136
+ rootRank: int
137
+ rootTensor: int
138
+ timeout: timedelta
139
+ asyncOp: bool
140
+
141
+ class AllreduceOptions:
142
+ reduceOp: ReduceOp
143
+ timeout: timedelta
144
+ asyncOp: bool
145
+ sparseIndices: Optional[Tensor]
146
+
147
+ class AllreduceCoalescedOptions(AllreduceOptions): ...
148
+
149
+ class ReduceOptions:
150
+ reduceOp: ReduceOp
151
+ rootRank: int
152
+ rootTensor: int
153
+ timeout: timedelta
154
+ asyncOp: bool
155
+
156
+ class AllgatherOptions:
157
+ timeout: timedelta
158
+ asyncOp: bool
159
+
160
+ class GatherOptions:
161
+ rootRank: int
162
+ timeout: timedelta
163
+ asyncOp: bool
164
+
165
+ class ScatterOptions:
166
+ rootRank: int
167
+ timeout: timedelta
168
+ asyncOp: bool
169
+
170
+ class ReduceScatterOptions:
171
+ reduceOp: ReduceOp
172
+ timeout: timedelta
173
+ asyncOp: bool
174
+
175
+ class BarrierOptions:
176
+ device_ids: list[int]
177
+ device: torch.device
178
+ timeout: timedelta
179
+ asyncOp: bool
180
+
181
+ class AllToAllOptions:
182
+ timeout: timedelta
183
+ asyncOp: bool
184
+
185
+ class Store:
186
+ def set(self, key: str, value: str): ...
187
+ def get(self, key: str) -> bytes: ...
188
+ def add(self, key: str, value: int) -> int: ...
189
+ def check(self, keys: list[str]) -> bool: ...
190
+ def compare_set(
191
+ self,
192
+ key: str,
193
+ expected_value: str,
194
+ desired_value: str,
195
+ ) -> bytes: ...
196
+ def delete_key(self, key: str) -> bool: ...
197
+ def num_keys(self) -> int: ...
198
+ def set_timeout(self, timeout: timedelta): ...
199
+ @overload
200
+ def wait(self, keys: list[str]): ...
201
+ @overload
202
+ def wait(self, keys: list[str], timeout: timedelta): ...
203
+ def queue_pop(self, key: str, block: bool = True) -> bytes: ...
204
+ def queue_push(self, key: str, value: Union[bytes, str]) -> None: ...
205
+ def queue_len(self, key: str) -> int: ...
206
+
207
+ class FileStore(Store):
208
+ def __init__(self, path: str, numWorkers: int = ...) -> None: ...
209
+
210
+ class HashStore(Store):
211
+ def __init__(self) -> None: ...
212
+
213
+ class TCPStore(Store):
214
+ def __init__(
215
+ self,
216
+ host_name: str,
217
+ port: int,
218
+ world_size: int | None = ...,
219
+ is_master: bool = ...,
220
+ timeout: timedelta = ...,
221
+ wait_for_workers: bool = ...,
222
+ multi_tenant: bool = ...,
223
+ master_listen_fd: int | None = ...,
224
+ use_libuv: bool | None = ...,
225
+ ) -> None: ...
226
+ @property
227
+ def host(self) -> str: ...
228
+ @property
229
+ def port(self) -> int: ...
230
+
231
+ class PrefixStore(Store):
232
+ def __init__(self, prefix: str, store: Store) -> None: ...
233
+ @property
234
+ def underlying_store(self) -> Store: ...
235
+
236
+ class _ControlCollectives:
237
+ def barrier(self, key: str, timeout: timedelta, blocking: bool) -> None: ...
238
+ def broadcast_send(self, key: str, data: str, timeout: timedelta) -> None: ...
239
+ def broadcast_recv(self, key: str, timeout: timedelta) -> str: ...
240
+ def gather_send(self, key: str, data: str, timeout: timedelta) -> None: ...
241
+ def gather_recv(self, key: str, timeout: timedelta) -> str: ...
242
+ def scatter_send(self, key: str, data: str, timeout: timedelta) -> None: ...
243
+ def scatter_recv(self, key: str, timeout: timedelta) -> str: ...
244
+ def all_gather(self, key: str, data: str, timeout: timedelta) -> str: ...
245
+ def all_sum(self, key: str, data: int, timeout: timedelta) -> int: ...
246
+
247
+ class _StoreCollectives(_ControlCollectives):
248
+ def __init__(self, store: Store, rank: int, world_size: int) -> None: ...
249
+
250
+ class _DistributedBackendOptions:
251
+ def __init__(self) -> None: ...
252
+ @property
253
+ def store(self) -> Store: ...
254
+ @store.setter
255
+ def store(self, store: Store) -> None: ...
256
+ @property
257
+ def group_rank(self) -> int: ...
258
+ @group_rank.setter
259
+ def group_rank(self, rank: int) -> None: ...
260
+ @property
261
+ def group_size(self) -> int: ...
262
+ @group_size.setter
263
+ def group_size(self, size: int) -> None: ...
264
+ @property
265
+ def timeout(self) -> timedelta: ...
266
+ @timeout.setter
267
+ def timeout(self, timeout: timedelta) -> None: ...
268
+ @property
269
+ def group_id(self) -> str: ...
270
+ @group_id.setter
271
+ def group_id(self, group_id: str) -> None: ...
272
+ @property
273
+ def global_ranks_in_group(self) -> list[int]: ...
274
+ @global_ranks_in_group.setter
275
+ def global_ranks_in_group(self, ranks: list[int]) -> None: ...
276
+
277
+ class Work:
278
+ def is_completed(self) -> bool: ...
279
+ def is_success(self) -> bool: ...
280
+ def exception(self) -> Any: ...
281
+ def wait(self, timeout: timedelta = ...) -> bool: ...
282
+ def block_current_stream(self) -> None: ...
283
+ def get_future(self) -> Future: ...
284
+ def source_rank(self) -> int: ...
285
+ def _source_rank(self) -> int: ...
286
+ def result(self) -> list[Tensor]: ...
287
+ def synchronize(self) -> None: ...
288
+ def boxed(self) -> ScriptObject: ...
289
+ @staticmethod
290
+ def unbox(obj: ScriptObject) -> Work: ...
291
+
292
+ class Backend:
293
+ class Options:
294
+ def __init__(self, backend: str, timeout: timedelta = ...) -> None: ...
295
+ @property
296
+ def backend(self) -> str: ...
297
+ @property
298
+ def _timeout(self) -> timedelta: ...
299
+ @_timeout.setter
300
+ def _timeout(self, val: timedelta) -> None: ...
301
+ global_ranks_in_group: list[int]
302
+ group_name: str
303
+
304
+ def __init__(
305
+ self,
306
+ rank: int,
307
+ size: int,
308
+ ) -> None: ...
309
+ @property
310
+ def supports_splitting(self) -> bool: ...
311
+ @property
312
+ def supports_coalescing(self) -> bool: ...
313
+ @property
314
+ def supports_time_estimate(self) -> bool: ...
315
+ def set_timeout(self, timeout: timedelta) -> None: ...
316
+ @property
317
+ def options(self) -> Options: ...
318
+ def rank(self) -> int: ...
319
+ def size(self) -> int: ...
320
+ def name(self) -> str: ...
321
+ def abort(self) -> None: ...
322
+ def shutdown(self) -> None: ...
323
+ def eager_connect_single_device(self, device: torch.device | None) -> None: ...
324
+ def _set_sequence_number_for_group(self) -> None: ...
325
+ def _set_default_timeout(self, timeout: timedelta) -> None: ...
326
+ def get_error(self) -> ErrorType: ...
327
+ def supports_tensor_alloc(self, device: torch.device) -> bool: ...
328
+ def allocate_tensor(
329
+ self,
330
+ size: int,
331
+ *,
332
+ dtype: torch.dtype,
333
+ device: torch.device,
334
+ ) -> Tensor: ...
335
+ @property
336
+ def mem_allocator(self) -> Any: ...
337
+
338
+ class ProcessGroup:
339
+ class BackendType(Enum):
340
+ UNDEFINED = ...
341
+ GLOO = ...
342
+ NCCL = ...
343
+ UCC = ...
344
+ MPI = ...
345
+ XCCL = ...
346
+ CUSTOM = ...
347
+
348
+ def __init__(
349
+ self,
350
+ store: Store,
351
+ rank: int,
352
+ size: int,
353
+ ) -> None: ...
354
+ def rank(self) -> int: ...
355
+ def size(self) -> int: ...
356
+ def get_group_store(self) -> Store: ...
357
+ def split_group(
358
+ self,
359
+ new_ranks: list[int],
360
+ timeout: Optional[timedelta] = None,
361
+ opts: Optional[Backend.Options] = None,
362
+ group_name: Optional[str] = None,
363
+ group_desc: Optional[str] = None,
364
+ ) -> Optional[ProcessGroup]: ...
365
+ def merge_remote_group(
366
+ self,
367
+ store: Store,
368
+ size: int,
369
+ timeout: timedelta,
370
+ group_name: Optional[str] = None,
371
+ group_desc: Optional[str] = None,
372
+ ) -> ProcessGroup: ...
373
+ def abort(self) -> None: ...
374
+ def set_timeout(self, timeout: timedelta) -> None: ...
375
+ def shutdown(self) -> None: ...
376
+ @overload
377
+ def broadcast(
378
+ self,
379
+ tensors: list[Tensor],
380
+ opts=...,
381
+ ) -> Work: ...
382
+ @overload
383
+ def broadcast(
384
+ self,
385
+ tensor: Tensor,
386
+ root: int,
387
+ timeout: timedelta | None = None,
388
+ ) -> Work: ...
389
+ @overload
390
+ def allreduce(
391
+ self,
392
+ tensors: list[Tensor],
393
+ opts: AllreduceOptions = ...,
394
+ ) -> Work: ...
395
+ @overload
396
+ def allreduce(
397
+ self,
398
+ tensors: list[Tensor],
399
+ op=...,
400
+ timeout: timedelta | None = None,
401
+ ) -> Work: ...
402
+ @overload
403
+ def allreduce(
404
+ self,
405
+ tensor: Tensor,
406
+ op=...,
407
+ timeout: timedelta | None = None,
408
+ ) -> Work: ...
409
+ def allreduce_coalesced(
410
+ self,
411
+ tensors: list[Tensor],
412
+ opts=...,
413
+ ) -> Work: ...
414
+ def reduce_scatter_tensor_coalesced(
415
+ self,
416
+ outputTensors: list[Tensor],
417
+ inputTensors: list[Tensor],
418
+ opts: ReduceScatterOptions | None = None,
419
+ ) -> Work: ...
420
+ @overload
421
+ def reduce(
422
+ self,
423
+ tensors: list[Tensor],
424
+ opts=...,
425
+ ) -> Work: ...
426
+ @overload
427
+ def reduce(
428
+ self,
429
+ tensor: Tensor,
430
+ root: int,
431
+ op=...,
432
+ timeout: timedelta | None = None,
433
+ ) -> Work: ...
434
+ @overload
435
+ def allgather(
436
+ self,
437
+ output_tensors: list[list[Tensor]],
438
+ input_tensors: list[Tensor],
439
+ opts=...,
440
+ ) -> Work: ...
441
+ @overload
442
+ def allgather(
443
+ self,
444
+ output_tensors: list[Tensor],
445
+ input_tensor: Tensor,
446
+ timeout: timedelta | None = None,
447
+ ) -> Work: ...
448
+ def _allgather_base(
449
+ self,
450
+ output: Tensor,
451
+ input: Tensor,
452
+ opts=...,
453
+ ) -> Work: ...
454
+ def allgather_coalesced(
455
+ self,
456
+ output_lists: list[list[Tensor]],
457
+ input_list: list[Tensor],
458
+ opts=...,
459
+ ) -> Work: ...
460
+ def allgather_into_tensor_coalesced(
461
+ self,
462
+ output_lists: list[Tensor],
463
+ input_list: list[Tensor],
464
+ opts=...,
465
+ ) -> Work: ...
466
+ @overload
467
+ def gather(
468
+ self,
469
+ output_tensors: list[list[Tensor]],
470
+ input_tensors: list[Tensor],
471
+ opts=...,
472
+ ) -> Work: ...
473
+ @overload
474
+ def gather(
475
+ self,
476
+ output_tensors: list[Tensor],
477
+ input_tensor: Tensor,
478
+ root: int,
479
+ timeout: timedelta | None = None,
480
+ ) -> Work: ...
481
+ @overload
482
+ def scatter(
483
+ self,
484
+ output_tensors: list[Tensor],
485
+ input_tensors: list[list[Tensor]],
486
+ opts=...,
487
+ ) -> Work: ...
488
+ @overload
489
+ def scatter(
490
+ self,
491
+ output_tensor: Tensor,
492
+ input_tensors: list[Tensor],
493
+ root: int,
494
+ timeout: timedelta | None = None,
495
+ ) -> Work: ...
496
+ @overload
497
+ def reduce_scatter(
498
+ self,
499
+ output_tensors: list[Tensor],
500
+ input_tensors: list[list[Tensor]],
501
+ opts=...,
502
+ ) -> Work: ...
503
+ @overload
504
+ def reduce_scatter(
505
+ self,
506
+ output_tensors: Tensor,
507
+ input_tensor: list[Tensor],
508
+ op=...,
509
+ timeout: timedelta | None = None,
510
+ ) -> Work: ...
511
+ def _reduce_scatter_base(
512
+ self,
513
+ outputTensor: Tensor,
514
+ inputTensor: Tensor,
515
+ opts: ReduceScatterOptions | None,
516
+ ) -> Work: ...
517
+ @overload
518
+ def alltoall_base(
519
+ self,
520
+ output_tensor: Tensor,
521
+ input_tensor: Tensor,
522
+ output_split_sizes: list[int],
523
+ input_split_sizes: list[int],
524
+ opts=...,
525
+ ) -> Work: ...
526
+ @overload
527
+ def alltoall_base(
528
+ self,
529
+ output: Tensor,
530
+ input: Tensor,
531
+ output_split_sizes: list[int],
532
+ input_split_sizes: list[int],
533
+ timeout: timedelta | None = None,
534
+ ) -> Work: ...
535
+ @overload
536
+ def alltoall(
537
+ self,
538
+ output_tensor: list[Tensor],
539
+ input_tensor: list[Tensor],
540
+ opts=...,
541
+ ) -> Work: ...
542
+ @overload
543
+ def alltoall(
544
+ self,
545
+ output: list[Tensor],
546
+ input: list[Tensor],
547
+ timeout: timedelta | None = None,
548
+ ) -> Work: ...
549
+ def send(
550
+ self,
551
+ tensors: list[Tensor],
552
+ dstRank: int,
553
+ tag: int,
554
+ ) -> Work: ...
555
+ def recv(
556
+ self,
557
+ tensors: list[Tensor],
558
+ srcRank: int,
559
+ tag: int,
560
+ ) -> Work: ...
561
+ def recv_anysource(self, tensors: list[Tensor], tag: int) -> Work: ...
562
+ @overload
563
+ def barrier(self, opts=...) -> Work: ...
564
+ @overload
565
+ def barrier(self, timeout: timedelta | None = None) -> Work: ...
566
+ def boxed(self) -> ScriptObject: ...
567
+ @staticmethod
568
+ def unbox(obj: ScriptObject) -> ProcessGroup: ...
569
+ def _start_coalescing(self, device: torch.device) -> None: ...
570
+ def _end_coalescing(self, device: torch.device) -> Work: ...
571
+ def _get_backend_name(self) -> str: ...
572
+ def _backend_id(self, backend_type: BackendType) -> int: ...
573
+ @property
574
+ def _device_types(self) -> list[torch.device]: ...
575
+ def _get_backend(self, device: torch.device) -> Backend: ...
576
+ def _set_default_backend(self, backend_type: BackendType) -> None: ...
577
+ def _register_backend(
578
+ self,
579
+ device: torch.device,
580
+ backend_type: BackendType,
581
+ backend: Backend | None,
582
+ ) -> None: ...
583
+ def _set_group_name(self, name: str) -> None: ...
584
+ def _set_group_desc(self, desc: str) -> None: ...
585
+ def name(self) -> str: ...
586
+ def _has_hooks(self) -> bool: ...
587
+ def _wait_for_pending_works(self) -> None: ...
588
+ def _set_sequence_number_for_group(self) -> None: ...
589
+ @property
590
+ def bound_device_id(self) -> torch.device | None: ...
591
+ @bound_device_id.setter
592
+ def bound_device_id(self, device: torch.device | None) -> None: ...
593
+ @property
594
+ def group_name(self) -> str: ...
595
+ @property
596
+ def group_desc(self) -> str: ...
597
+
598
+ class FakeProcessGroup(Backend):
599
+ def __init__(self, rank: int, world_size: int) -> None: ...
600
+
601
+ class FakeWork(Work):
602
+ seq_id: int
603
+ def __init__(self) -> None: ...
604
+ def wait(self, timeout: timedelta = ...) -> bool: ...
605
+ def getFuture(self) -> Future: ...
606
+
607
+ class ProcessGroupGloo(Backend):
608
+ class Device: ...
609
+
610
+ class Options(Backend.Options):
611
+ devices: list[ProcessGroupGloo.Device]
612
+ threads: int
613
+
614
+ def __init__(self): ...
615
+
616
+ def __init__(
617
+ self,
618
+ store: Store,
619
+ rank: int,
620
+ size: int,
621
+ timeout: timedelta,
622
+ ) -> None: ...
623
+ @staticmethod
624
+ def create_device(hostname="", interface="", lazy_init=None) -> Device: ...
625
+ @staticmethod
626
+ def create_default_device(lazy_init=None) -> Device: ...
627
+ def _set_default_timeout(self, timeout) -> None: ...
628
+ @property
629
+ def options(self) -> Options: ... # type: ignore[override]
630
+
631
+ class _ProcessGroupWrapper(Backend):
632
+ def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo) -> None: ...
633
+ wrapped_pg: Backend
634
+
635
+ class ErrorType(Enum):
636
+ SUCCESS = ...
637
+ TIMEOUT = ...
638
+ COMM_ERROR = ...
639
+ REMOTE_ERROR = ...
640
+
641
+ class ProcessGroupNCCL(Backend):
642
+ class NCCLConfig:
643
+ blocking: int
644
+ cga_cluster_size: int
645
+ min_ctas: int
646
+ max_ctas: int
647
+ def unsafe_get_ptr(self) -> int: ...
648
+
649
+ class Options(Backend.Options):
650
+ config: ProcessGroupNCCL.NCCLConfig
651
+ is_high_priority_stream: bool
652
+ split_from: ProcessGroupNCCL
653
+ split_color: int
654
+
655
+ def __init__(self, is_high_priority_stream: bool = False): ...
656
+
657
+ def __init__(
658
+ self,
659
+ store: Store,
660
+ rank: int,
661
+ size: int,
662
+ options: Options,
663
+ ) -> None: ...
664
+ def _group_start(self) -> None: ...
665
+ def _group_end(self) -> None: ...
666
+ def _start_time_estimate(self) -> None: ...
667
+ def _end_time_estimate(self) -> float: ...
668
+ def _set_default_timeout(self, timeout) -> None: ...
669
+ def perform_nocolor_split(self, device: torch.device) -> None: ...
670
+ def register_mem_pool(self, pool: torch.cuda.MemPool) -> None: ...
671
+ def deregister_mem_pool(self, pool: torch.cuda.MemPool) -> None: ...
672
+ def comm_split_count(self) -> int: ...
673
+ def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ...
674
+ def abort(self) -> None: ...
675
+ def _is_initialized(self) -> bool: ...
676
+ @property
677
+ def uid(self) -> int: ...
678
+ @property
679
+ def options(self) -> Options: ... # type: ignore[override]
680
+ @staticmethod
681
+ def get_build_nccl_version(self) -> tuple[int, int, int]: ...
682
+ @staticmethod
683
+ def get_runtime_nccl_version(self) -> tuple[int, int, int]: ...
684
+
685
+ class ProcessGroupUCC(Backend):
686
+ def __init__(
687
+ self,
688
+ store: Store,
689
+ rank: int,
690
+ size: int,
691
+ timeout: timedelta,
692
+ ) -> None: ...
693
+
694
+ class ProcessGroupMPI(Backend):
695
+ def __init__(
696
+ self,
697
+ rank: int,
698
+ size: int,
699
+ pgComm: int,
700
+ ) -> None: ...
701
+ @staticmethod
702
+ def create(ranks: list[int]) -> ProcessGroupMPI: ...
703
+
704
+ def _compute_bucket_assignment_by_size(
705
+ tensors: list[Tensor],
706
+ bucket_size_limits: list[int],
707
+ expect_sparse_gradient: list[bool] = ...,
708
+ tensor_indices: list[int] = ...,
709
+ ) -> tuple[list[list[int]], list[int]]: ...
710
+ def _broadcast_coalesced(
711
+ process_group: ProcessGroup,
712
+ tensors: list[Tensor],
713
+ buffer_size: int,
714
+ src: int,
715
+ ): ...
716
+ def _test_python_store(store: Store): ...
717
+ def _verify_params_across_processes(
718
+ process_group: ProcessGroup,
719
+ params: list[Tensor],
720
+ logger: Logger | None,
721
+ ): ...
722
+ def _make_nccl_premul_sum(factor: float | list[Tensor]) -> ReduceOp: ...
723
+ def _register_process_group(
724
+ group_name: str,
725
+ process_group: ProcessGroup,
726
+ ) -> None: ...
727
+ def _resolve_process_group(group_name: str) -> ProcessGroup: ...
728
+ def _register_work(tensor: torch.Tensor, work: Work) -> ProcessGroup: ...
729
+ def _get_work_registry_size() -> int: ...
730
+ def _set_allow_inflight_collective_as_graph_input(
731
+ value: bool,
732
+ ) -> None: ...
733
+ def _allow_inflight_collective_as_graph_input() -> bool: ...
734
+ def _unregister_all_process_groups() -> None: ...
735
+ def _unregister_process_group(group_name: str) -> None: ...
736
+
737
+ # Initializes the device state in CUmodule so that it’s able to perform NVSHMEM
738
+ # operations. CUmodule is a pointer to a CUDA module, carried by a int64 in
739
+ # Python. At C++ interface, it is converted to a uintptr_t.
740
+ def _nvshmemx_cumodule_init(module: int) -> None: ...
741
+
742
+ # Check if NVSHMEM is available on current system.
743
+ def _is_nvshmem_available() -> bool: ...
744
+
745
+ class _SymmetricMemory:
746
+ @staticmethod
747
+ def set_group_info(
748
+ group_name: str,
749
+ rank: int,
750
+ world_size: int,
751
+ store: Store,
752
+ ) -> None: ...
753
+ @staticmethod
754
+ def empty_strided_p2p(
755
+ size: torch.types._size,
756
+ stride: torch.types._size,
757
+ dtype: torch.dtype,
758
+ device: torch.device,
759
+ group_name: str | None = None,
760
+ alloc_id: int | None = None,
761
+ ) -> torch.Tensor: ...
762
+ @staticmethod
763
+ def has_multicast_support(
764
+ device_type: DeviceType,
765
+ device_idx: int,
766
+ ) -> bool: ...
767
+ # Set Symmetric Memory allocation backend.
768
+ @staticmethod
769
+ def set_backend(name: str) -> None: ...
770
+ @staticmethod
771
+ def get_backend(device: torch.device) -> Optional[str]: ...
772
+ @staticmethod
773
+ def get_mempool_allocator(device: torch.device) -> Any: ...
774
+ @property
775
+ def rank(self) -> int: ...
776
+ @property
777
+ def world_size(self) -> int: ...
778
+ @staticmethod
779
+ def rendezvous(
780
+ tensor: torch.Tensor, group_name: str | None = None
781
+ ) -> _SymmetricMemory: ...
782
+ def get_buffer(
783
+ self,
784
+ rank: int,
785
+ sizes: torch.types._size,
786
+ dtype: torch.dtype,
787
+ storage_offset: int | None = 0,
788
+ ) -> torch.Tensor: ...
789
+ def get_signal_pad(
790
+ self,
791
+ rank: int,
792
+ sizes: torch.types._size = [],
793
+ dtype: torch.dtype | None = None,
794
+ storage_offset: int | None = 0,
795
+ ) -> torch.Tensor: ...
796
+ def barrier(self, channel: int = 0, timeout_ms: int = 0) -> None: ...
797
+ def put_signal(
798
+ self,
799
+ dst_rank: int,
800
+ channel: int = 0,
801
+ timeout_ms: int = 0,
802
+ ) -> None: ...
803
+ def wait_signal(
804
+ self,
805
+ src_rank: int,
806
+ channel: int = 0,
807
+ timeout_ms: int = 0,
808
+ ) -> None: ...
809
+ def get_remote_tensor(
810
+ self,
811
+ peer: int,
812
+ sizes: torch.types._size,
813
+ dtype: torch.dtype,
814
+ ) -> torch.Tensor: ...
815
+ @staticmethod
816
+ def memset32(
817
+ tensor: torch.Tensor, offset: int, val: int, count: int = 1
818
+ ) -> torch.Tensor: ...
819
+ @staticmethod
820
+ def stream_write_value32(
821
+ tensor: torch.Tensor, offset: int, val: int
822
+ ) -> torch.Tensor: ...
823
+ @property
824
+ def buffer_ptrs(self) -> list[int]: ...
825
+ @property
826
+ def buffer_ptrs_dev(self) -> int: ...
827
+ @property
828
+ def signal_pad_ptrs(self) -> list[int]: ...
829
+ @property
830
+ def signal_pad_ptrs_dev(self) -> int: ...
831
+ @property
832
+ def multicast_ptr(self) -> int: ...
833
+ @property
834
+ def buffer_size(self) -> int: ...
835
+ @property
836
+ def signal_pad_size(self) -> int: ...
837
+
838
+ class ProcessGroupXCCL(Backend):
839
+ class Options(Backend.Options):
840
+ def __init__(self): ...
841
+
842
+ def __init__(
843
+ self,
844
+ store: Store,
845
+ rank: int,
846
+ size: int,
847
+ options: Options,
848
+ ) -> None: ...
849
+ @property
850
+ def options(self) -> Options: ... # type: ignore[override]
851
+
852
+ def _set_process_group(pg: ProcessGroup) -> None: ...
853
+ def _current_process_group() -> ProcessGroup: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # mypy: disable-error-code="type-arg"
3
+ from datetime import timedelta
4
+ from typing import Any, Generic, overload, TypeVar
5
+
6
+ import torch
7
+ from torch._C import Future
8
+ from torch._C._autograd import ProfilerEvent
9
+ from torch._C._distributed_c10d import Store
10
+ from torch._C._profiler import ProfilerConfig
11
+
12
+ # This module is defined in torch/csrc/distributed/rpc/init.cpp
13
+
14
+ _DEFAULT_INIT_METHOD: str
15
+ _DEFAULT_NUM_WORKER_THREADS: int
16
+ _UNSET_RPC_TIMEOUT: float
17
+ _DEFAULT_RPC_TIMEOUT_SEC: float
18
+
19
+ _T = TypeVar("_T")
20
+
21
+ class RpcBackendOptions:
22
+ rpc_timeout: float
23
+ init_method: str
24
+ def __init__(
25
+ self,
26
+ rpc_timeout: float = ...,
27
+ init_method: str = ...,
28
+ ) -> None: ...
29
+
30
+ class WorkerInfo:
31
+ def __init__(self, name: str, worker_id: int) -> None: ...
32
+ @property
33
+ def name(self) -> str: ...
34
+ @property
35
+ def id(self) -> int: ...
36
+ def __eq__(self, other: object) -> bool: ...
37
+
38
+ class RpcAgent:
39
+ def join(self, shutdown: bool = False, timeout: float = 0): ...
40
+ def sync(self): ...
41
+ def shutdown(self): ...
42
+ @overload
43
+ def get_worker_info(self) -> WorkerInfo: ...
44
+ @overload
45
+ def get_worker_info(self, workerName: str) -> WorkerInfo: ...
46
+ def get_worker_infos(self) -> list[WorkerInfo]: ...
47
+ def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ...
48
+ def get_debug_info(self) -> dict[str, str]: ...
49
+ def get_metrics(self) -> dict[str, str]: ...
50
+
51
+ class PyRRef(Generic[_T]):
52
+ def __init__(self, value: _T, type_hint: Any = None) -> None: ...
53
+ def is_owner(self) -> bool: ...
54
+ def confirmed_by_owner(self) -> bool: ...
55
+ def owner(self) -> WorkerInfo: ...
56
+ def owner_name(self) -> str: ...
57
+ def to_here(self, timeout: float = ...) -> _T: ...
58
+ def local_value(self) -> Any: ...
59
+ def rpc_sync(self, timeout: float = ...) -> Any: ...
60
+ def rpc_async(self, timeout: float = ...) -> Any: ...
61
+ def remote(self, timeout: float = ...) -> Any: ...
62
+ def _serialize(self) -> tuple: ...
63
+ @staticmethod
64
+ def _deserialize(tp: tuple) -> PyRRef: ...
65
+ def _get_type(self) -> type[_T]: ...
66
+ def _get_future(self) -> Future[_T]: ...
67
+ def _get_profiling_future(self) -> Future[_T]: ...
68
+ def _set_profiling_future(self, profilingFuture: Future[_T]): ...
69
+
70
+ class _TensorPipeRpcBackendOptionsBase(RpcBackendOptions):
71
+ num_worker_threads: int
72
+ device_maps: dict[str, dict[torch.device, torch.device]]
73
+ devices: list[torch.device]
74
+ def __init__(
75
+ self,
76
+ num_worker_threads: int,
77
+ _transports: list | None,
78
+ _channels: list | None,
79
+ rpc_timeout: float = ...,
80
+ init_method: str = ...,
81
+ device_maps: dict[str, dict[torch.device, torch.device]] = {}, # noqa: B006
82
+ devices: list[torch.device] = [], # noqa: B006
83
+ ) -> None: ...
84
+ def _set_device_map(
85
+ self,
86
+ to: str,
87
+ device_map: dict[torch.device, torch.device],
88
+ ): ...
89
+
90
+ class TensorPipeAgent(RpcAgent):
91
+ def __init__(
92
+ self,
93
+ store: Store,
94
+ name: str,
95
+ worker_id: int,
96
+ world_size: int | None,
97
+ opts: _TensorPipeRpcBackendOptionsBase,
98
+ reverse_device_maps: dict[str, dict[torch.device, torch.device]],
99
+ devices: list[torch.device],
100
+ ) -> None: ...
101
+ def join(self, shutdown: bool = False, timeout: float = 0): ...
102
+ def shutdown(self): ...
103
+ @overload
104
+ def get_worker_info(self) -> WorkerInfo: ...
105
+ @overload
106
+ def get_worker_info(self, workerName: str) -> WorkerInfo: ...
107
+ @overload
108
+ def get_worker_info(self, id: int) -> WorkerInfo: ...
109
+ def get_worker_infos(self) -> list[WorkerInfo]: ...
110
+ def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ...
111
+ def _update_group_membership(
112
+ self,
113
+ worker_info: WorkerInfo,
114
+ my_devices: list[torch.device],
115
+ reverse_device_map: dict[str, dict[torch.device, torch.device]],
116
+ is_join: bool,
117
+ ): ...
118
+ def _get_backend_options(self) -> _TensorPipeRpcBackendOptionsBase: ...
119
+ @property
120
+ def is_static_group(self) -> bool: ...
121
+ @property
122
+ def store(self) -> Store: ...
123
+
124
+ def _is_current_rpc_agent_set() -> bool: ...
125
+ def _get_current_rpc_agent() -> RpcAgent: ...
126
+ def _set_and_start_rpc_agent(agent: RpcAgent): ...
127
+ def _reset_current_rpc_agent(): ...
128
+ def _delete_all_user_and_unforked_owner_rrefs(timeout: timedelta = ...): ...
129
+ def _destroy_rref_context(ignoreRRefLeak: bool): ...
130
+ def _rref_context_get_debug_info() -> dict[str, str]: ...
131
+ def _cleanup_python_rpc_handler(): ...
132
+ def _invoke_rpc_builtin(
133
+ dst: WorkerInfo,
134
+ opName: str,
135
+ rpcTimeoutSeconds: float,
136
+ *args: Any,
137
+ **kwargs: Any,
138
+ ): ...
139
+ def _invoke_rpc_python_udf(
140
+ dst: WorkerInfo,
141
+ pickledPythonUDF: str,
142
+ tensors: list[torch.Tensor],
143
+ rpcTimeoutSeconds: float,
144
+ isAsyncExecution: bool,
145
+ ): ...
146
+ def _invoke_rpc_torchscript(
147
+ dstWorkerName: str,
148
+ qualifiedNameStr: str,
149
+ argsTuple: tuple,
150
+ kwargsDict: dict,
151
+ rpcTimeoutSeconds: float,
152
+ isAsyncExecution: bool,
153
+ ): ...
154
+ def _invoke_remote_builtin(
155
+ dst: WorkerInfo,
156
+ opName: str,
157
+ rpcTimeoutSeconds: float,
158
+ *args: Any,
159
+ **kwargs: Any,
160
+ ): ...
161
+ def _invoke_remote_python_udf(
162
+ dst: WorkerInfo,
163
+ pickledPythonUDF: str,
164
+ tensors: list[torch.Tensor],
165
+ rpcTimeoutSeconds: float,
166
+ isAsyncExecution: bool,
167
+ ): ...
168
+ def _invoke_remote_torchscript(
169
+ dstWorkerName: WorkerInfo,
170
+ qualifiedNameStr: str,
171
+ rpcTimeoutSeconds: float,
172
+ isAsyncExecution: bool,
173
+ *args: Any,
174
+ **kwargs: Any,
175
+ ): ...
176
+ def get_rpc_timeout() -> float: ...
177
+ def enable_gil_profiling(flag: bool): ...
178
+ def _set_rpc_timeout(rpcTimeoutSeconds: float): ...
179
+
180
+ class RemoteProfilerManager:
181
+ @staticmethod
182
+ def set_current_profiling_key(key: str): ...
183
+
184
+ def _enable_server_process_global_profiler(new_config: ProfilerConfig): ...
185
+ def _disable_server_process_global_profiler() -> list[list[list[ProfilerEvent]]]: ...
186
+ def _set_profiler_node_id(default_node_id: int): ...
187
+ def _enable_jit_rref_pickle(): ...
188
+ def _disable_jit_rref_pickle(): ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._C._distributed_c10d import Store
3
+ from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase, TensorPipeAgent
4
+
5
+ # This module is defined in torch/csrc/distributed/rpc/testing/init.cpp
6
+
7
+ class FaultyTensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase):
8
+ def __init__(
9
+ self,
10
+ num_worker_threads: int,
11
+ rpc_timeout: float,
12
+ init_method: str,
13
+ messages_to_fail: list[str],
14
+ messages_to_delay: dict[str, float],
15
+ num_fail_sends: int,
16
+ ) -> None: ...
17
+ num_send_recv_threads: int
18
+ messages_to_fail: list[str]
19
+ messages_to_delay: dict[str, float]
20
+ num_fail_sends: int
21
+
22
+ class FaultyTensorPipeAgent(TensorPipeAgent):
23
+ def __init__(
24
+ self,
25
+ store: Store,
26
+ name: str,
27
+ rank: int,
28
+ world_size: int,
29
+ options: FaultyTensorPipeRpcBackendOptions,
30
+ reverse_device_maps: dict[str, dict[torch.device, torch.device]],
31
+ devices: list[torch.device],
32
+ ) -> None: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from . import compiled_autograd, eval_frame, guards # noqa: F401
2
+
3
+ def strip_function_call(name: str) -> str: ...
4
+ def is_valid_var_name(name: str) -> bool | int: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ from torch import Tensor
4
+ from torch._dynamo.compiled_autograd import AutogradCompilerInstance
5
+
6
+ def set_autograd_compiler(
7
+ autograd_compiler: Callable[[], AutogradCompilerInstance] | None,
8
+ dynamic: bool,
9
+ ) -> tuple[Callable[[], AutogradCompilerInstance] | None, bool]: ...
10
+ def clear_cache() -> None: ...
11
+ def is_cache_empty() -> bool: ...
12
+ def set_verbose_logger(fn: Callable[[str], None] | None) -> bool: ...
13
+ def call_cpp_tensor_pre_hooks(idx: int, grad: Tensor) -> Tensor: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import types
3
+ from typing import Optional, overload
4
+
5
+ from torch._dynamo.guards import GuardManagerWrapper
6
+ from torch._dynamo.types import DynamoCallback, DynamoGuardCompleteHook, DynamoGuardHook
7
+ from torch._guards import CompileId
8
+
9
+ def set_eval_frame(callback: DynamoCallback) -> DynamoCallback: ...
10
+ def set_skip_guard_eval_unsafe(value: bool) -> bool: ...
11
+ def get_eval_frame_callback() -> DynamoCallback: ...
12
+ def reset_code(code: types.CodeType) -> None: ...
13
+ def unsupported(obj1: object, obj2: object) -> object: ...
14
+ def set_code_exec_strategy(
15
+ code: types.CodeType, strategy: _FrameExecStrategy
16
+ ) -> None: ...
17
+ def set_guard_error_hook(hook: DynamoGuardHook) -> None: ...
18
+ def set_guard_complete_hook(
19
+ hook: Optional[DynamoGuardCompleteHook],
20
+ ) -> Optional[DynamoGuardCompleteHook]: ...
21
+ def raise_sigtrap() -> None: ...
22
+
23
+ class _CacheEntry:
24
+ def check_fn(self, *args: object, **kwargs: object) -> bool: ...
25
+ def update_diff_guard_root_manager(self) -> None: ...
26
+ code: types.CodeType
27
+ compile_id: CompileId
28
+ # If we run into circular issues, just use object
29
+ guard_manager: GuardManagerWrapper
30
+ next: _CacheEntry | None
31
+
32
+ class _PrecompileEntry:
33
+ guard_manager: GuardManagerWrapper
34
+
35
+ class _ExtraState:
36
+ def invalidate(
37
+ self, cache_entry: _CacheEntry, guard_manager: GuardManagerWrapper
38
+ ) -> None: ...
39
+
40
+ class _FrameAction(enum.IntEnum):
41
+ DEFAULT = 0
42
+ SKIP = 1
43
+ RUN_ONLY = 2
44
+
45
+ class _FrameExecStrategy:
46
+ cur_action: _FrameAction
47
+ recursive_action: _FrameAction
48
+
49
+ @overload
50
+ def __init__(self) -> None: ...
51
+ @overload
52
+ def __init__(
53
+ self, cur_action: _FrameAction, recursive_action: _FrameAction
54
+ ) -> None: ...
55
+
56
+ # This is an object that encapsulates the Python FrameType, and exposes
57
+ # properties Dynamo cares about for a frame.
58
+ class _PyInterpreterFrame:
59
+ f_code: types.CodeType
60
+ f_locals: dict[str, object]
61
+ f_globals: dict[str, object]
62
+ f_builtins: dict[str, object]
63
+ f_lasti: int
64
+ f_lineno: int
65
+ f_back: types.FrameType
66
+ # A tuple containing cell objects captured by this frame.
67
+ closure: tuple[types.CellType]
68
+
69
+ def _debug_get_cache_entry_list(code: types.CodeType) -> list[_CacheEntry]: ...
70
+
71
+ py_opcode_caches: list[int]
72
+
73
+ def code_framelocals_names(code: types.CodeType) -> tuple[str]: ...
74
+ def _load_precompile_entry(
75
+ code: types.CodeType,
76
+ guard_manager: GuardManagerWrapper,
77
+ dynamo_code: types.CodeType,
78
+ ) -> None: ...
79
+ def _reset_precompile_entries(code: types.CodeType) -> None: ...
80
+ def _debug_get_precompile_entries(code: types.CodeType) -> list[_PrecompileEntry]: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_dynamo/guards.pyi ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from typing import Any, Callable, Optional
3
+ from typing_extensions import TypeAlias
4
+
5
+ import torch
6
+
7
+ # TODO: We should move the `GuardManagerType`
8
+ # defined in `guards.py` here and update other
9
+ # imports
10
+ GuardManagerType: TypeAlias = enum.Enum
11
+
12
+ class GlobalStateGuard:
13
+ def check(self) -> bool: ...
14
+ def reason(self) -> str: ...
15
+
16
+ class LeafGuard:
17
+ def verbose_code_parts(self) -> list[str]: ...
18
+
19
+ class RelationalGuard: ...
20
+
21
+ class GuardDebugInfo:
22
+ verbose_code_parts: list[str]
23
+ result: bool
24
+ num_guards_executed: int
25
+
26
+ class GuardManager:
27
+ def check(self, value: Any) -> bool: ...
28
+ def check_verbose(self, value: Any) -> GuardDebugInfo: ...
29
+
30
+ # Accessors
31
+ def globals_dict_manager(
32
+ self,
33
+ f_globals: dict[str, Any],
34
+ source: str,
35
+ example_value: Any,
36
+ guard_manager_enum: GuardManagerType,
37
+ ) -> GuardManager: ...
38
+ def framelocals_manager(
39
+ self,
40
+ key: tuple[str, int],
41
+ source: str,
42
+ example_value: Any,
43
+ guard_manager_enum: GuardManagerType,
44
+ ) -> GuardManager: ...
45
+ def dict_getitem_manager(
46
+ self,
47
+ key: Any,
48
+ source: str,
49
+ example_value: Any,
50
+ guard_manager_enum: GuardManagerType,
51
+ ) -> GuardManager: ...
52
+ def grad_manager(
53
+ self,
54
+ source: str,
55
+ example_value: Any,
56
+ guard_manager_enum: GuardManagerType,
57
+ ) -> GuardManager: ...
58
+ def generic_getattr_manager(
59
+ self,
60
+ attr: str,
61
+ source: str,
62
+ example_value: Any,
63
+ guard_manager_enum: GuardManagerType,
64
+ ) -> GuardManager: ...
65
+ def getitem_manager(
66
+ self,
67
+ key: Any,
68
+ source: str,
69
+ example_value: Any,
70
+ guard_manager_enum: GuardManagerType,
71
+ ) -> GuardManager: ...
72
+ def get_generic_dict_manager(
73
+ self,
74
+ source: str,
75
+ example_value: Any,
76
+ guard_manager_enum: GuardManagerType,
77
+ ) -> GuardManager: ...
78
+ def list_getitem_manager(
79
+ self,
80
+ key: Any,
81
+ source: str,
82
+ example_value: Any,
83
+ guard_manager_enum: GuardManagerType,
84
+ ) -> GuardManager: ...
85
+ def tuple_getitem_manager(
86
+ self,
87
+ key: Any,
88
+ source: str,
89
+ example_value: Any,
90
+ guard_manager_enum: GuardManagerType,
91
+ ) -> GuardManager: ...
92
+ def set_getitem_manager(
93
+ self,
94
+ index: Any,
95
+ source: str,
96
+ example_value: Any,
97
+ guard_manager_enum: GuardManagerType,
98
+ ) -> GuardManager: ...
99
+ def func_defaults_manager(
100
+ self,
101
+ source: str,
102
+ example_value: Any,
103
+ guard_manager_enum: GuardManagerType,
104
+ ) -> GuardManager: ...
105
+ def func_kwdefaults_manager(
106
+ self,
107
+ source: str,
108
+ example_value: Any,
109
+ guard_manager_enum: GuardManagerType,
110
+ ) -> GuardManager: ...
111
+ def tuple_iterator_getitem_manager(
112
+ self,
113
+ index: Any,
114
+ source: str,
115
+ example_value: Any,
116
+ guard_manager_enum: GuardManagerType,
117
+ ) -> GuardManager: ...
118
+ def weakref_call_manager(
119
+ self,
120
+ source: str,
121
+ example_value: Any,
122
+ guard_manager_enum: GuardManagerType,
123
+ ) -> GuardManager: ...
124
+ def call_function_no_args_manager(
125
+ self,
126
+ source: str,
127
+ example_value: Any,
128
+ guard_manager_enum: GuardManagerType,
129
+ ) -> GuardManager: ...
130
+ def global_weakref_manager(
131
+ self,
132
+ global_name: str,
133
+ source: str,
134
+ example_value: Any,
135
+ guard_manager_enum: GuardManagerType,
136
+ ) -> GuardManager: ...
137
+ def type_manager(
138
+ self,
139
+ source: str,
140
+ example_value: Any,
141
+ guard_manager_enum: GuardManagerType,
142
+ ) -> GuardManager: ...
143
+ def getattr_manager(
144
+ self,
145
+ attr: str,
146
+ source: str,
147
+ example_value: Any,
148
+ guard_manager_enum: GuardManagerType,
149
+ ) -> GuardManager: ...
150
+ def tensor_property_size_manager(
151
+ self,
152
+ idx: int,
153
+ source: str,
154
+ example_value: Any,
155
+ guard_manager_enum: GuardManagerType,
156
+ ) -> GuardManager: ...
157
+ def tensor_property_shape_manager(
158
+ self,
159
+ idx: int,
160
+ source: str,
161
+ example_value: Any,
162
+ guard_manager_enum: GuardManagerType,
163
+ ) -> GuardManager: ...
164
+ def tensor_property_storage_offset_manager(
165
+ self,
166
+ idx: int,
167
+ source: str,
168
+ example_value: Any,
169
+ guard_manager_enum: GuardManagerType,
170
+ ) -> GuardManager: ...
171
+ def indexed_manager(
172
+ self,
173
+ idx: int,
174
+ source: str,
175
+ example_value: Any,
176
+ guard_manager_enum: GuardManagerType,
177
+ ) -> GuardManager: ...
178
+ def lambda_manager(
179
+ self,
180
+ python_lambda: Callable[..., Any],
181
+ source: str,
182
+ example_value: Any,
183
+ guard_manager_enum: GuardManagerType,
184
+ ) -> GuardManager: ...
185
+ def get_root(self) -> RootGuardManager: ...
186
+ def get_source(self) -> str: ...
187
+ def fail_count(self) -> int: ...
188
+ def get_child_managers(self) -> list[GuardManager]: ...
189
+ def repr(self) -> str: ...
190
+ def type_of_guarded_value(self) -> str: ...
191
+ def get_leaf_guards(self) -> list[LeafGuard]: ...
192
+ def get_accessors(self) -> list[GuardManager]: ...
193
+ def is_guarded_value_immutable(self) -> bool: ...
194
+ def is_tag_safe(self) -> bool: ...
195
+ def is_tag_safe_root(self) -> bool: ...
196
+ def has_no_accessors(self) -> bool: ...
197
+ def has_object_aliasing_guard(self) -> bool: ...
198
+ def get_type_of_guarded_value(self) -> type: ...
199
+ def type_dict_manager(
200
+ self,
201
+ source: str,
202
+ example_value: Any,
203
+ guard_manager_enum: GuardManagerType,
204
+ ) -> GuardManager: ...
205
+ def type_mro_manager(
206
+ self,
207
+ source: str,
208
+ example_value: Any,
209
+ guard_manager_enum: GuardManagerType,
210
+ ) -> GuardManager: ...
211
+ def code_manager(
212
+ self,
213
+ source: str,
214
+ example_value: Any,
215
+ guard_manager_enum: GuardManagerType,
216
+ ) -> GuardManager: ...
217
+ def closure_manager(
218
+ self,
219
+ source: str,
220
+ example_value: Any,
221
+ guard_manager_enum: GuardManagerType,
222
+ ) -> GuardManager: ...
223
+ # Leaf guards
224
+ def add_lambda_guard(
225
+ self, user_lambda: Callable[..., Any], verbose_code_parts: list[str]
226
+ ) -> None: ...
227
+ def add_id_match_guard(
228
+ self, id_val: int, verbose_code_parts: list[str]
229
+ ) -> None: ...
230
+ def add_equals_match_guard(
231
+ self,
232
+ equals_val: Any,
233
+ verbose_code_parts: list[str],
234
+ ) -> None: ...
235
+ def add_global_state_guard(
236
+ self, initial_state: Any, verbose_code_parts: list[str]
237
+ ) -> None: ...
238
+ def add_torch_function_mode_stack_guard(
239
+ self, initial_stack: list[Any], verbose_code_parts: list[str]
240
+ ) -> None: ...
241
+ def add_mapping_keys_guard(
242
+ self, value: Any, verbose_code_parts: list[str]
243
+ ) -> None: ...
244
+ def add_dict_length_check_guard(
245
+ self, value: int, verbose_code_parts: list[str]
246
+ ) -> None: ...
247
+ def add_length_check_guard(
248
+ self, value: int, verbose_code_parts: list[str]
249
+ ) -> None: ...
250
+ def add_true_match_guard(
251
+ self,
252
+ verbose_code_parts: list[str],
253
+ ) -> None: ...
254
+ def add_false_match_guard(
255
+ self,
256
+ verbose_code_parts: list[str],
257
+ ) -> None: ...
258
+ def add_none_match_guard(
259
+ self,
260
+ verbose_code_parts: list[str],
261
+ ) -> None: ...
262
+ def add_not_none_guard(
263
+ self,
264
+ verbose_code_parts: list[str],
265
+ ) -> None: ...
266
+ def add_dispatch_key_set_guard(
267
+ self,
268
+ dispatch_key: Any,
269
+ verbose_code_parts: list[str],
270
+ ) -> None: ...
271
+ def add_tensor_match_guard(
272
+ self,
273
+ value: Any,
274
+ sizes: list[int],
275
+ strides: list[int],
276
+ tensor_name: str,
277
+ verbose_code_parts: list[str],
278
+ ptype: Any,
279
+ dispatch_keys: Any,
280
+ ) -> None: ...
281
+ def add_dynamic_indices_guard(
282
+ self,
283
+ value: set[Any],
284
+ verbose_code_parts: list[str],
285
+ ) -> None: ...
286
+ def add_no_hasattr_guard(
287
+ self,
288
+ attr_name: str,
289
+ verbose_code_parts: list[str],
290
+ ) -> None: ...
291
+ def add_dict_contains_guard(
292
+ self,
293
+ contains: bool,
294
+ key: Any,
295
+ verbose_code_parts: list[str],
296
+ ) -> None: ...
297
+ def add_type_match_guard(
298
+ self,
299
+ value: int,
300
+ verbose_code_parts: list[str],
301
+ ) -> None: ...
302
+ def add_dict_version_guard(
303
+ self,
304
+ value: Any,
305
+ verbose_code_parts: list[str],
306
+ ) -> None: ...
307
+ def add_set_contains_guard(
308
+ self,
309
+ contains: bool,
310
+ item: Any,
311
+ verbose_code_parts: list[str],
312
+ ) -> None: ...
313
+ def add_tuple_iterator_length_guard(
314
+ self,
315
+ length: int,
316
+ type_id: int,
317
+ verbose_code_parts: list[str],
318
+ ) -> None: ...
319
+ def add_range_iterator_match_guard(
320
+ self,
321
+ start: int,
322
+ stop: int,
323
+ step: int,
324
+ type_id: int,
325
+ verbose_code_parts: list[str],
326
+ ) -> None: ...
327
+ def add_default_device_guard(
328
+ self,
329
+ verbose_code_parts: list[str],
330
+ ) -> None: ...
331
+ def mark_tag_safe(self) -> None: ...
332
+ def mark_tag_safe_root(self) -> None: ...
333
+
334
+ class RootGuardManager(GuardManager):
335
+ def get_epilogue_lambda_guards(self) -> list[LeafGuard]: ...
336
+ def add_epilogue_lambda_guard(
337
+ self,
338
+ guard: LeafGuard,
339
+ verbose_code_parts: list[str],
340
+ ) -> None: ...
341
+ def clone_manager(
342
+ self, clone_filter_fn: Callable[[GuardManager], bool]
343
+ ) -> RootGuardManager: ...
344
+ def attach_compile_id(self, compile_id: str) -> None: ...
345
+
346
+ class DictGuardManager(GuardManager):
347
+ def get_key_manager(
348
+ self,
349
+ index: int,
350
+ source: str,
351
+ example_value: Any,
352
+ guard_manager_enum: GuardManagerType,
353
+ ) -> GuardManager: ...
354
+ def get_value_manager(
355
+ self,
356
+ index: int,
357
+ source: str,
358
+ example_value: Any,
359
+ guard_manager_enum: GuardManagerType,
360
+ ) -> GuardManager: ...
361
+ def get_key_value_managers(
362
+ self,
363
+ ) -> dict[int, tuple[GuardManager, GuardManager]]: ...
364
+
365
+ # Guard accessor stubs
366
+ class GuardAccessor: ...
367
+ class DictGetItemGuardAccessor(GuardAccessor): ...
368
+ class GetGenericDictGuardAccessor(GuardAccessor): ...
369
+ class TypeDictGuardAccessor(GuardAccessor): ...
370
+ class TypeMROGuardAccessor(GuardAccessor): ...
371
+ class ClosureGuardAccessor(GuardAccessor): ...
372
+ class TupleGetItemGuardAccessor(GuardAccessor): ...
373
+ class TypeGuardAccessor(GuardAccessor): ...
374
+ class CodeGuardAccessor(GuardAccessor): ...
375
+ class FuncDefaultsGuardAccessor(GuardAccessor): ...
376
+ class FuncKwDefaultsGuardAccessor(GuardAccessor): ...
377
+
378
+ class GetAttrGuardAccessor(GuardAccessor):
379
+ def get_attr_name(self) -> str: ...
380
+
381
+ def install_object_aliasing_guard(
382
+ x: GuardManager,
383
+ y: GuardManager,
384
+ verbose_code_parts: list[str],
385
+ ) -> None: ...
386
+ def install_no_tensor_aliasing_guard(
387
+ guard_managers: list[GuardManager],
388
+ tensor_names: list[str],
389
+ verbose_code_parts: list[str],
390
+ ) -> None: ...
391
+ def install_storage_overlapping_guard(
392
+ overlapping_guard_managers: list[GuardManager],
393
+ non_overlapping_guard_managers: list[GuardManager],
394
+ verbose_code_parts: list[str],
395
+ ) -> None: ...
396
+ def install_symbolic_shape_guard(
397
+ guard_managers: list[GuardManager],
398
+ nargs_int: int,
399
+ nargs_float: int,
400
+ py_addr: int,
401
+ py_addr_keep_alive: Any,
402
+ verbose_code_parts: list[str],
403
+ ) -> None: ...
404
+ def profile_guard_manager(
405
+ guard_manager: GuardManager,
406
+ f_locals: dict[str, Any],
407
+ n_iters: int,
408
+ ) -> float: ...
409
+
410
+ class TensorGuards:
411
+ def __init__(
412
+ self,
413
+ *,
414
+ dynamic_dims_sizes: list[torch.SymInt | None] | None = None,
415
+ dynamic_dims_strides: list[torch.SymInt | None] | None = None,
416
+ ) -> None: ...
417
+ def check(self, *args: Any) -> bool: ...
418
+ def check_verbose(
419
+ self, *args: Any, tensor_check_names: Optional[list[str]] = None
420
+ ) -> bool | str: ...
421
+
422
+ def assert_size_stride(
423
+ item: torch.Tensor,
424
+ size: torch.types._size,
425
+ stride: torch.types._size,
426
+ op_name: str | None = None,
427
+ ) -> None: ...
428
+ def assert_alignment(
429
+ item: torch.Tensor,
430
+ alignment: int,
431
+ op_name: str | None = None,
432
+ ) -> None: ...
433
+ def check_obj_id(obj: object, expected: int) -> bool: ...
434
+ def check_type_id(obj: object, expected: int) -> bool: ...
435
+ def dict_version(d: dict[Any, Any]) -> int: ...
436
+ def compute_overlapping_tensors(
437
+ tensors: list[torch.Tensor], symbolic: bool = True
438
+ ) -> set[int]: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Defined in torch/csrc/export/pybind.cpp
2
+ class CppExportedProgram: ...
3
+
4
+ def deserialize_exported_program(
5
+ serialized_program: str,
6
+ ) -> CppExportedProgram: ...
7
+ def serialize_exported_program(
8
+ cpp_exported_program: CppExportedProgram,
9
+ ) -> str: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Defined in torch/csrc/export/pt2_archive_constants.h
2
+
3
+ ARCHIVE_ROOT_NAME: str = ...
4
+ ARCHIVE_FORMAT_PATH: str = ...
5
+ ARCHIVE_FORMAT_VALUE: str = ...
6
+ ARCHIVE_VERSION_PATH: str = ...
7
+ ARCHIVE_VERSION_VALUE: str = ...
8
+ MODELS_DIR: str = ...
9
+ MODELS_FILENAME_FORMAT: str = ...
10
+ AOTINDUCTOR_DIR: str = ...
11
+ MTIA_DIR: str = ...
12
+ WEIGHTS_DIR: str = ...
13
+ WEIGHTS_CONFIG_FILENAME_FORMAT: str = ...
14
+ WEIGHT_FILENAME_PREFIX: str = ...
15
+ CONSTANTS_DIR: str = ...
16
+ CONSTANTS_CONFIG_FILENAME_FORMAT: str = ...
17
+ TENSOR_CONSTANT_FILENAME_PREFIX: str = ...
18
+ CUSTOM_OBJ_FILENAME_PREFIX: str = ...
19
+ SAMPLE_INPUTS_DIR: str = ...
20
+ SAMPLE_INPUTS_FILENAME_FORMAT: str = ...
21
+ EXTRA_DIR: str = ...
22
+ MODULE_INFO_PATH: str = ...
23
+ XL_MODEL_WEIGHTS_DIR: str = ...
24
+ XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH: str = ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_functionalization.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+ from torch.types import _bool
3
+
4
+ # Defined in torch/csrc/functionalization/Module.cpp
5
+
6
+ class ViewMeta:
7
+ has_symbolic_inputs: _bool
8
+
9
+ # Returns the list of ViewMeta instances of the given functional tensor.
10
+ #
11
+ # Although we do have python bindings for their types, we won't
12
+ # expose them here, since they should not be used by users.
13
+ def get_view_meta_sequence(tensor: Tensor) -> list[ViewMeta]: ...
14
+
15
+ # Applies the ViewMeta sequence on top of the given base.
16
+ def apply_view_meta_sequence(base: Tensor, sequence: list[ViewMeta]) -> Tensor: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_functions.pyi ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import AnyStr, overload
2
+
3
+ from torch import Tensor
4
+
5
+ class UndefinedGrad:
6
+ def __init__(self) -> None: ...
7
+ def __call__(self, *inputs: Tensor) -> list[Tensor]: ...
8
+
9
+ class DelayedError:
10
+ def __init__(self, msg: AnyStr, num_inputs: int) -> None: ...
11
+
12
+ # __call__ should really be a higher-kinded type:
13
+ # def __call__(self, arg: Tensor) -> Tensor: ...
14
+ # def __call__(self, *args: Tensor * num_inputs) -> Tuple[Tensor * num_inputs]: ...
15
+
16
+ @overload
17
+ def __call__(self, i0: Tensor) -> Tensor: ...
18
+ @overload
19
+ def __call__(self, *args: Tensor) -> tuple[Tensor, ...]: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_functorch.pyi ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from enum import Enum
3
+
4
+ from torch import Tensor
5
+
6
+ # Defined in torch/csrc/functorch/init.cpp
7
+
8
+ def _set_dynamic_layer_keys_included(included: bool) -> None: ...
9
+ def get_unwrapped(tensor: Tensor) -> Tensor: ...
10
+ def is_batchedtensor(tensor: Tensor) -> bool: ...
11
+ def is_functionaltensor(tensor: Tensor) -> bool: ...
12
+ def is_functorch_wrapped_tensor(tensor: Tensor) -> bool: ...
13
+ def is_gradtrackingtensor(tensor: Tensor) -> bool: ...
14
+ def is_legacy_batchedtensor(tensor: Tensor) -> bool: ...
15
+ def maybe_get_bdim(tensor: Tensor) -> int: ...
16
+ def maybe_get_level(tensor: Tensor) -> int: ...
17
+ def maybe_current_level() -> int | None: ...
18
+ def unwrap_if_dead(tensor: Tensor) -> Tensor: ...
19
+ def _unwrap_for_grad(tensor: Tensor, level: int) -> Tensor: ...
20
+ def _wrap_for_grad(tensor: Tensor, level: int) -> Tensor: ...
21
+ def _unwrap_batched(tensor: Tensor, level: int) -> tuple[Tensor, int | None]: ...
22
+ def current_level() -> int: ...
23
+ def count_jvp_interpreters() -> int: ...
24
+ def _add_batch_dim(tensor: Tensor, bdim: int, level: int) -> Tensor: ...
25
+ def set_single_level_autograd_function_allowed(allowed: bool) -> None: ...
26
+ def get_single_level_autograd_function_allowed() -> bool: ...
27
+ def _unwrap_functional_tensor(tensor: Tensor, reapply_views: bool) -> Tensor: ...
28
+ def _wrap_functional_tensor(tensor: Tensor, level: int) -> Tensor: ...
29
+ def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: ...
30
+ def _vmap_decrement_nesting() -> int: ...
31
+ def _grad_increment_nesting() -> int: ...
32
+ def _grad_decrement_nesting() -> int: ...
33
+ def _jvp_increment_nesting() -> int: ...
34
+ def _jvp_decrement_nesting() -> int: ...
35
+
36
+ # Defined in aten/src/ATen/functorch/Interpreter.h
37
+ class TransformType(Enum):
38
+ Torch = ...
39
+ Vmap = ...
40
+ Grad = ...
41
+ Jvp = ...
42
+ Functionalize = ...
43
+
44
+ class RandomnessType(Enum):
45
+ Error = ...
46
+ Same = ...
47
+ Different = ...
48
+
49
+ class CInterpreter:
50
+ def key(self) -> TransformType: ...
51
+ def level(self) -> int: ...
52
+ def serialize(self) -> bytes: ...
53
+ @staticmethod
54
+ def deserialize(bytes) -> CInterpreter: ...
55
+
56
+ class CGradInterpreterPtr:
57
+ def __init__(self, interpreter: CInterpreter) -> None: ...
58
+ def lift(self, Tensor) -> Tensor: ...
59
+ def prevGradMode(self) -> bool: ...
60
+
61
+ class CJvpInterpreterPtr:
62
+ def __init__(self, interpreter: CInterpreter) -> None: ...
63
+ def lift(self, Tensor) -> Tensor: ...
64
+ def prevFwdGradMode(self) -> bool: ...
65
+
66
+ class CFunctionalizeInterpreterPtr:
67
+ def __init__(self, interpreter: CInterpreter) -> None: ...
68
+ def key(self) -> TransformType: ...
69
+ def level(self) -> int: ...
70
+ def functionalizeAddBackViews(self) -> bool: ...
71
+
72
+ class CVmapInterpreterPtr:
73
+ def __init__(self, interpreter: CInterpreter) -> None: ...
74
+ def key(self) -> TransformType: ...
75
+ def level(self) -> int: ...
76
+ def batchSize(self) -> int: ...
77
+ def randomness(self) -> RandomnessType: ...
78
+
79
+ class DynamicLayer: ...
80
+
81
+ def get_dynamic_layer_stack_depth() -> int: ...
82
+ def get_interpreter_stack() -> list[CInterpreter]: ...
83
+ def peek_interpreter_stack() -> CInterpreter: ...
84
+ def pop_dynamic_layer_stack() -> DynamicLayer: ...
85
+ def pop_dynamic_layer_stack_and_undo_to_depth(int) -> None: ...
86
+ def push_dynamic_layer_stack(dl: DynamicLayer) -> int: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Defined in torch/csrc/instruction_counter/Module.cpp
2
+
3
+ def start() -> int: ...
4
+ def end(id: int) -> int: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_itt.pyi ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Defined in torch/csrc/itt.cpp
2
+ def is_available() -> None: ...
3
+ def rangePush(message: str) -> None: ...
4
+ def rangePop() -> None: ...
5
+ def mark(message: str) -> None: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+
3
+ # Defined in torch/csrc/jit/python/python_tree_views.cpp
4
+
5
+ class SourceRange:
6
+ def highlight(self) -> str: ...
7
+ @property
8
+ def start(self) -> int: ...
9
+ @property
10
+ def end(self) -> int: ...
11
+
12
+ class SourceRangeFactory:
13
+ def __init__(
14
+ self,
15
+ text: str,
16
+ filename: Any,
17
+ file_lineno: int,
18
+ leading_whitespace_chars: int,
19
+ ) -> None: ...
20
+ def make_range(self, line: int, start_col: int, end_col: int) -> SourceRange: ...
21
+ def make_raw_range(self, start: int, end: int) -> SourceRange: ...
22
+ @property
23
+ def source(self) -> str: ...
24
+
25
+ class TreeView:
26
+ def range(self) -> SourceRange: ...
27
+ def dump(self) -> None: ...
28
+
29
+ class Ident(TreeView):
30
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
31
+ @property
32
+ def name(self) -> str: ...
33
+
34
+ class Param(TreeView):
35
+ def __init__(self, type: Optional[Any], name: Ident, kwarg_only: bool) -> None: ...
36
+
37
+ class Attribute(TreeView):
38
+ def __init__(self, name: Ident, value: Any) -> None: ...
39
+
40
+ # Literals
41
+ def TrueLiteral(range: SourceRange) -> Any: ...
42
+ def FalseLiteral(range: SourceRange) -> Any: ...
43
+ def NoneLiteral(range: SourceRange) -> Any: ...
44
+
45
+ # Tree nodes
46
+ class Stmt(TreeView):
47
+ def __init__(self, thing: TreeView) -> None: ...
48
+
49
+ class Expr(TreeView): ...
50
+
51
+ class Def(TreeView):
52
+ def __init__(self, name: Ident, decl: Any, body: list[Stmt]) -> None: ...
53
+ def decl(self) -> Any: ...
54
+ def name(self) -> Ident: ...
55
+
56
+ class Property(TreeView):
57
+ def __init__(
58
+ self, r: SourceRange, name: Ident, getter: Def, setter: Optional[Def]
59
+ ) -> None: ...
60
+ def name(self) -> Ident: ...
61
+ def getter_name(self) -> str: ...
62
+ def setter_name(self) -> Optional[Ident]: ...
63
+
64
+ class ClassDef(TreeView):
65
+ def __init__(
66
+ self, name: Ident, body: list[Stmt], props: list[Property], assigns: list[Any]
67
+ ) -> None: ...
68
+
69
+ class Decl(TreeView):
70
+ def __init__(
71
+ self, r: SourceRange, params: list[Param], return_type: Optional[Expr]
72
+ ) -> None: ...
73
+
74
+ class Delete(Stmt):
75
+ def __init__(self, range: SourceRange, targets: list[Expr]) -> None: ...
76
+
77
+ class WithItem(Expr):
78
+ def __init__(
79
+ self, range: SourceRange, target: Expr, var: Optional[Any]
80
+ ) -> None: ...
81
+
82
+ class Assign(Stmt):
83
+ def __init__(
84
+ self, lhs: list[Expr], rhs: Expr, type: Optional[Expr] = None
85
+ ) -> None: ...
86
+
87
+ class AugAssign(Stmt):
88
+ def __init__(self, lhs: Expr, kind_str: str, rhs: Expr) -> None: ...
89
+
90
+ class Return(Stmt):
91
+ def __init__(self, range: SourceRange, value: Optional[Expr]) -> None: ...
92
+
93
+ class Raise(Stmt):
94
+ def __init__(self, range: SourceRange, expr: Expr) -> None: ...
95
+
96
+ class Assert(Stmt):
97
+ def __init__(self, range: SourceRange, test: Expr, msg: Optional[Expr]) -> None: ...
98
+
99
+ class Pass(Stmt):
100
+ def __init__(self, range: SourceRange) -> None: ...
101
+
102
+ class Break(Stmt): ...
103
+ class Continue(Stmt): ...
104
+
105
+ class Dots(Expr, TreeView):
106
+ def __init__(self, range: SourceRange) -> None: ...
107
+
108
+ class If(Stmt):
109
+ def __init__(
110
+ self,
111
+ range: SourceRange,
112
+ cond: Expr,
113
+ true_branch: list[Stmt],
114
+ false_branch: list[Stmt],
115
+ ) -> None: ...
116
+
117
+ class While(Stmt):
118
+ def __init__(self, range: SourceRange, cond: Expr, body: list[Stmt]) -> None: ...
119
+
120
+ class With(Stmt):
121
+ def __init__(
122
+ self, range: SourceRange, targets: list[WithItem], body: list[Stmt]
123
+ ) -> None: ...
124
+
125
+ class For(Stmt):
126
+ def __init__(
127
+ self,
128
+ range: SourceRange,
129
+ targets: list[Expr],
130
+ itrs: list[Expr],
131
+ body: list[Stmt],
132
+ ) -> None: ...
133
+
134
+ class ExprStmt(Stmt):
135
+ def __init__(self, expr: Expr) -> None: ...
136
+
137
+ class Var(Expr):
138
+ def __init__(self, name: Ident) -> None: ...
139
+ @property
140
+ def name(self) -> str: ...
141
+
142
+ class BinOp(Expr):
143
+ def __init__(self, kind: str, lhs: Expr, rhs: Expr) -> None: ...
144
+
145
+ class UnaryOp(Expr):
146
+ def __init__(self, range: SourceRange, kind: str, expr: Expr) -> None: ...
147
+
148
+ class Const(Expr):
149
+ def __init__(self, range: SourceRange, value: str) -> None: ...
150
+
151
+ class StringLiteral(Expr):
152
+ def __init__(self, range: SourceRange, value: str) -> None: ...
153
+
154
+ class Apply(Expr):
155
+ def __init__(
156
+ self, expr: Expr, args: list[Expr], kwargs: list[Attribute]
157
+ ) -> None: ...
158
+
159
+ class Select(Expr):
160
+ def __init__(self, expr: Expr, field: Ident) -> None: ...
161
+
162
+ class TernaryIf(Expr):
163
+ def __init__(self, cond: Expr, true_expr: Expr, false_expr: Expr) -> None: ...
164
+
165
+ class ListComp(Expr):
166
+ def __init__(
167
+ self, range: SourceRange, elt: Expr, target: Expr, iter: Expr
168
+ ) -> None: ...
169
+
170
+ class DictComp(Expr):
171
+ def __init__(
172
+ self, range: SourceRange, key: Expr, value: Expr, target: Expr, iter: Expr
173
+ ) -> None: ...
174
+
175
+ class ListLiteral(Expr):
176
+ def __init__(self, range: SourceRange, args: list[Expr]) -> None: ...
177
+
178
+ class TupleLiteral(Expr):
179
+ def __init__(self, range: SourceRange, args: list[Expr]) -> None: ...
180
+
181
+ class DictLiteral(Expr):
182
+ def __init__(
183
+ self, range: SourceRange, keys: list[Expr], values: list[Expr]
184
+ ) -> None: ...
185
+
186
+ class Subscript(Expr):
187
+ def __init__(self, base: Expr, subscript_exprs: list[Expr]) -> None: ...
188
+
189
+ class SliceExpr(Expr):
190
+ def __init__(
191
+ self,
192
+ range: SourceRange,
193
+ lower: Optional[Expr],
194
+ upper: Optional[Expr],
195
+ step: Optional[Expr],
196
+ ) -> None: ...
197
+
198
+ class Starred(Expr):
199
+ def __init__(self, range: SourceRange, expr: Expr) -> None: ...
200
+
201
+ class EmptyTypeAnnotation(TreeView):
202
+ def __init__(self, range: SourceRange) -> None: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_lazy.pyi ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+
3
+ # defined in torch/csrc/lazy/python/init.cpp
4
+ def _mark_step(device: str, devices: list[str], wait: bool) -> None: ...
5
+ def _wait_device_ops(devices: list[str]) -> None: ...
6
+ def _reset_metrics() -> None: ...
7
+ def _counter_names() -> list[str]: ...
8
+ def _counter_value(name: str) -> int: ...
9
+ def _metrics_report() -> str: ...
10
+ def _get_graph_hash(tensors: list[Tensor]) -> str: ...
11
+ def _sync_multi(
12
+ tensors: list[Tensor],
13
+ devices: list[str],
14
+ wait: bool = True,
15
+ sync_ltc_data: bool = True,
16
+ ) -> None: ...
17
+ def _get_tensor_id(tensor: Tensor) -> int: ...
18
+ def _get_tensors_text(tensors: list[Tensor]) -> str: ...
19
+ def _get_tensors_dot(tensors: list[Tensor]) -> str: ...
20
+ def _get_tensors_backend(tensors: list[Tensor]) -> str: ...
21
+ def _get_force_fallback() -> str: ...
22
+ def _set_force_fallback(newval: str) -> None: ...
23
+ def _clear_ir_cache() -> None: ...
24
+ def _dump_ir_cache(filename: str) -> None: ...
25
+ def _set_reuse_ir(val: bool) -> None: ...
26
+ def _get_default_device_type() -> str: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # defined in torch/csrc/lazy/python/init.cpp
3
+
4
+ from typing import Any
5
+
6
+ from torch import Tensor
7
+
8
+ def _init(): ...
9
+ def _get_tensors_ts_device_data_node(
10
+ tensors: list[Tensor],
11
+ ) -> tuple[list[int], list[Any]]: ...
12
+ def _run_cached_graph(hash_str: str, graph_inputs: list[Any]) -> list[Tensor]: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_monitor.pyi ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Defined in torch/csrc/monitor/python_init.cpp
2
+
3
+ import datetime
4
+ from enum import Enum
5
+ from types import TracebackType
6
+ from typing import Callable
7
+
8
+ class Aggregation(Enum):
9
+ VALUE = ...
10
+ MEAN = ...
11
+ COUNT = ...
12
+ SUM = ...
13
+ MAX = ...
14
+ MIN = ...
15
+
16
+ class Stat:
17
+ name: str
18
+ count: int
19
+ def __init__(
20
+ self,
21
+ name: str,
22
+ aggregations: list[Aggregation],
23
+ window_size: int,
24
+ max_samples: int = -1,
25
+ ) -> None: ...
26
+ def add(self, v: float) -> None: ...
27
+ def get(self) -> dict[Aggregation, float]: ...
28
+
29
+ class Event:
30
+ name: str
31
+ timestamp: datetime.datetime
32
+ data: dict[str, int | float | bool | str]
33
+ def __init__(
34
+ self,
35
+ name: str,
36
+ timestamp: datetime.datetime,
37
+ data: dict[str, int | float | bool | str],
38
+ ) -> None: ...
39
+
40
+ def log_event(e: Event) -> None: ...
41
+
42
+ class EventHandlerHandle: ...
43
+
44
+ def register_event_handler(handler: Callable[[Event], None]) -> EventHandlerHandle: ...
45
+ def unregister_event_handler(handle: EventHandlerHandle) -> None: ...
46
+
47
+ class _WaitCounterTracker:
48
+ def __enter__(self) -> None: ...
49
+ def __exit__(
50
+ self,
51
+ exc_type: type[BaseException] | None = None,
52
+ exc_value: BaseException | None = None,
53
+ traceback: TracebackType | None = None,
54
+ ) -> None: ...
55
+
56
+ class _WaitCounter:
57
+ def __init__(self, key: str) -> None: ...
58
+ def guard(self) -> _WaitCounterTracker: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_nn.pyi ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @generated by tools/pyi/gen_pyi.py from torch/_C/_nn.pyi.in
2
+ # mypy: disable-error-code="type-arg"
3
+
4
+ from collections.abc import Sequence
5
+ from typing import Literal, overload
6
+
7
+ from torch import memory_format, Tensor
8
+ from torch.types import _bool, _device, _dtype, _int, _size
9
+
10
+ # Defined in tools/autograd/templates/python_nn_functions.cpp
11
+
12
+ def adaptive_avg_pool2d(input: Tensor, output_size: _int | _size) -> Tensor: ...
13
+ def adaptive_avg_pool3d(input: Tensor, output_size: _int | _size) -> Tensor: ...
14
+ def adaptive_max_pool2d(
15
+ input: Tensor,
16
+ output_size: _int | _size,
17
+ ) -> tuple[Tensor, Tensor]: ...
18
+ def adaptive_max_pool3d(
19
+ input: Tensor,
20
+ output_size: _int | _size,
21
+ ) -> tuple[Tensor, Tensor]: ...
22
+ def avg_pool2d(
23
+ input: Tensor,
24
+ kernel_size: _int | _size,
25
+ stride: _int | _size | None = None,
26
+ padding: _int | _size = 0,
27
+ ceil_mode: bool = False,
28
+ count_include_pad: bool = True,
29
+ divisor_override: int | None = None,
30
+ ) -> Tensor: ...
31
+ def avg_pool3d(
32
+ input: Tensor,
33
+ kernel_size: _int | _size,
34
+ stride: _int | _size | None = None,
35
+ padding: _int | _size = 0,
36
+ ceil_mode: bool = False,
37
+ count_include_pad: bool = True,
38
+ divisor_override: int | None = None,
39
+ ) -> Tensor: ...
40
+ def binary_cross_entropy(
41
+ input: Tensor,
42
+ target: Tensor,
43
+ weight: Tensor | None = None,
44
+ reduction: str = ...,
45
+ ) -> Tensor: ...
46
+ def col2im(
47
+ input: Tensor,
48
+ output_size: _int | _size,
49
+ kernel_size: _int | _size,
50
+ dilation: _int | _size,
51
+ stride: _int | _size | None = None,
52
+ padding: _int | _size = 0,
53
+ ) -> Tensor: ...
54
+ def cross_entropy_loss(
55
+ input: Tensor,
56
+ target: Tensor,
57
+ weight: Tensor | None = None,
58
+ reduction: str = ...,
59
+ ignore_index: int = -100,
60
+ label_smoothing: float = 0.0,
61
+ ) -> Tensor: ...
62
+ def elu(
63
+ input: Tensor,
64
+ alpha: float = 1.0,
65
+ scale: float = 1.0,
66
+ input_scale: float = 1.0,
67
+ ) -> Tensor: ...
68
+ def elu_(input: Tensor, alpha: float = ...) -> Tensor: ...
69
+ def fractional_max_pool2d(
70
+ input: Tensor,
71
+ kernel_size: _int | _size,
72
+ output_size: _int | _size,
73
+ _random_samples: Tensor,
74
+ ) -> tuple[Tensor, Tensor]: ...
75
+ def fractional_max_pool3d(
76
+ input: Tensor,
77
+ kernel_size: _int | _size,
78
+ output_size: _int | _size,
79
+ _random_samples: Tensor,
80
+ ) -> tuple[Tensor, Tensor]: ...
81
+ def gelu(input: Tensor, approximate: str = ...) -> Tensor: ...
82
+ def glu(input: Tensor, dim: int = -1) -> Tensor: ...
83
+ def hardsigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: ...
84
+ def hardsigmoid_(input: Tensor) -> Tensor: ...
85
+ def hardswish(input: Tensor) -> Tensor: ...
86
+ def hardswish_(input: Tensor) -> Tensor: ...
87
+ def hardtanh(
88
+ input: Tensor,
89
+ min_val: float = ...,
90
+ max_val: float = ...,
91
+ *,
92
+ out: Tensor | None = None,
93
+ ) -> Tensor: ...
94
+ def hardtanh_(
95
+ input: Tensor,
96
+ min_val: float = ...,
97
+ max_val: float = ...,
98
+ ) -> Tensor: ...
99
+ def huber_loss(
100
+ input: Tensor,
101
+ target: Tensor,
102
+ reduction: str = ...,
103
+ delta: float = 1.0,
104
+ ) -> Tensor: ...
105
+ def leaky_relu(
106
+ input: Tensor,
107
+ negative_slope: float = ...,
108
+ *,
109
+ out: Tensor | None = None,
110
+ ) -> Tensor: ...
111
+ def leaky_relu_(input: Tensor, negative_slope: float = ...) -> Tensor: ...
112
+ def linear(
113
+ input: Tensor,
114
+ weight: Tensor,
115
+ bias: Tensor | None = None,
116
+ ) -> Tensor: ...
117
+ def log_sigmoid(input: Tensor) -> Tensor: ...
118
+ def max_pool2d_with_indices(
119
+ input: Tensor,
120
+ kernel_size: _int | _size,
121
+ stride: _int | _size | None = None,
122
+ padding: _int | _size = 0,
123
+ dilation: _int | _size = 1,
124
+ ceil_mode: bool = False,
125
+ ) -> tuple[Tensor, Tensor]: ...
126
+ def max_pool3d_with_indices(
127
+ input: Tensor,
128
+ kernel_size: _int | _size,
129
+ stride: _int | _size | None = None,
130
+ padding: _int | _size = 0,
131
+ dilation: _int | _size = 1,
132
+ ceil_mode: bool = False,
133
+ ) -> tuple[Tensor, Tensor]: ...
134
+ def max_unpool2d(
135
+ input: Tensor,
136
+ indices: Tensor,
137
+ output_size: Sequence[int] | None,
138
+ ) -> Tensor: ...
139
+ def max_unpool3d(
140
+ input: Tensor,
141
+ indices: Tensor,
142
+ output_size: Sequence[int] | None,
143
+ stride: _int | _size,
144
+ padding: _int | _size,
145
+ ) -> Tensor: ...
146
+ def one_hot(tensor: Tensor, num_classes: int = ...) -> Tensor: ...
147
+ def pad(
148
+ input: Tensor,
149
+ pad: Sequence[int],
150
+ mode: str = ...,
151
+ value: float | None = None,
152
+ ) -> Tensor: ...
153
+ def scaled_dot_product_attention(
154
+ query: Tensor,
155
+ key: Tensor,
156
+ value: Tensor,
157
+ attn_mask: Tensor | None = None,
158
+ dropout_p: float = 0.0,
159
+ is_causal: bool = False,
160
+ scale: float | None = None,
161
+ enable_gqa: bool = False,
162
+ ) -> Tensor: ...
163
+ def softplus(
164
+ input: Tensor,
165
+ beta: float = ...,
166
+ threshold: float = ...,
167
+ ) -> Tensor: ...
168
+ def softshrink(input: Tensor, lambd: float = ...) -> Tensor: ...
169
+
170
+ # Defined in aten/src/ATen/native/mkldnn/Linear.cpp
171
+ def mkldnn_linear(input: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor: ...
172
+
173
+ # Defined at aten/src/ATen/native/mkldnn/MKLDNNConversions.cpp
174
+ def mkldnn_reorder_conv2d_weight(
175
+ self: Tensor,
176
+ padding: list,
177
+ stride: list,
178
+ dilatation: list,
179
+ groups: int,
180
+ ) -> Tensor: ...
181
+ def mkldnn_reorder_conv3d_weight(
182
+ self: Tensor,
183
+ padding: list,
184
+ stride: list,
185
+ dilatation: list,
186
+ groups: int,
187
+ ) -> Tensor: ...
188
+
189
+ # Defined in aten/src/ATen/native/mkldnn/Prelu.cpp
190
+ def mkldnn_prelu(input: Tensor, weight: Tensor) -> Tensor: ...
191
+
192
+ # Defined at tools/autograd/templates/python_nn_functions.cpp
193
+ @overload
194
+ def _parse_to(
195
+ device: _device,
196
+ dtype: _dtype,
197
+ non_blocking: _bool,
198
+ copy: _bool,
199
+ *,
200
+ memory_format: memory_format,
201
+ ) -> tuple[_device, _dtype, _bool, memory_format]: ...
202
+ @overload
203
+ def _parse_to(
204
+ dtype: _dtype,
205
+ non_blocking: _bool,
206
+ copy: _bool,
207
+ *,
208
+ memory_format: memory_format,
209
+ ) -> tuple[_device, _dtype, _bool, memory_format]: ...
210
+ @overload
211
+ def _parse_to(
212
+ tensor: Tensor,
213
+ non_blocking: _bool,
214
+ copy: _bool,
215
+ *,
216
+ memory_format: memory_format,
217
+ ) -> tuple[_device, _dtype, _bool, memory_format]: ...
218
+
219
+ # Defined in aten/src/ATen/native/PackedSequence.cpp
220
+ def pad_sequence(
221
+ sequences: list[Tensor] | tuple[Tensor, ...],
222
+ batch_first: bool = False,
223
+ padding_value: float = 0.0,
224
+ padding_side: Literal["left", "right"] = "right",
225
+ ) -> Tensor: ...
226
+
227
+ # Upsample functions used by torch.nn.functional.interpolate
228
+ def upsample_nearest1d(
229
+ input: Tensor,
230
+ output_size: Sequence[int] | None,
231
+ scale_factors: Sequence[float] | None,
232
+ ) -> Tensor: ...
233
+ def upsample_nearest2d(
234
+ input: Tensor,
235
+ output_size: Sequence[int] | None,
236
+ scale_factors: Sequence[float] | None,
237
+ ) -> Tensor: ...
238
+ def upsample_nearest3d(
239
+ input: Tensor,
240
+ output_size: Sequence[int] | None,
241
+ scale_factors: Sequence[float] | None,
242
+ ) -> Tensor: ...
243
+ def _upsample_nearest_exact1d(
244
+ input: Tensor,
245
+ output_size: Sequence[int] | None,
246
+ scale_factors: Sequence[float] | None,
247
+ ) -> Tensor: ...
248
+ def _upsample_nearest_exact2d(
249
+ input: Tensor,
250
+ output_size: Sequence[int] | None,
251
+ scale_factors: Sequence[float] | None,
252
+ ) -> Tensor: ...
253
+ def _upsample_nearest_exact3d(
254
+ input: Tensor,
255
+ output_size: Sequence[int] | None,
256
+ scale_factors: Sequence[float] | None,
257
+ ) -> Tensor: ...
258
+ def upsample_linear1d(
259
+ input: Tensor,
260
+ output_size: Sequence[int] | None,
261
+ align_corners: bool,
262
+ scale_factors: Sequence[float] | None,
263
+ ) -> Tensor: ...
264
+ def _upsample_bilinear2d_aa(
265
+ input: Tensor,
266
+ output_size: Sequence[int] | None,
267
+ align_corners: bool,
268
+ scale_factors: Sequence[float] | None,
269
+ ) -> Tensor: ...
270
+ def upsample_bilinear2d(
271
+ input: Tensor,
272
+ output_size: Sequence[int] | None,
273
+ align_corners: bool,
274
+ scale_factors: Sequence[float] | None,
275
+ ) -> Tensor: ...
276
+ def upsample_trilinear3d(
277
+ input: Tensor,
278
+ output_size: Sequence[int] | None,
279
+ align_corners: bool,
280
+ scale_factors: Sequence[float] | None,
281
+ ) -> Tensor: ...
282
+ def _upsample_bicubic2d_aa(
283
+ input: Tensor,
284
+ output_size: Sequence[int] | None,
285
+ align_corners: bool,
286
+ scale_factors: Sequence[float] | None,
287
+ ) -> Tensor: ...
288
+ def upsample_bicubic2d(
289
+ input: Tensor,
290
+ output_size: Sequence[int] | None,
291
+ align_corners: bool,
292
+ scale_factors: Sequence[float] | None,
293
+ ) -> Tensor: ...
294
+ def flatten_dense_tensors(tensors: list[Tensor]) -> Tensor: ...
295
+ def unflatten_dense_tensors(flat: Tensor, tensors: list[Tensor]) -> list[Tensor]: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_nvtx.pyi ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Defined in torch/csrc/cuda/shared/nvtx.cpp
3
+ def rangePushA(message: str) -> int: ...
4
+ def rangePop() -> int: ...
5
+ def rangeStartA(message: str) -> int: ...
6
+ def rangeEnd(int) -> None: ...
7
+ def markA(message: str) -> None: ...
8
+ def deviceRangeStart(message: str, stream: int) -> object: ...
9
+ def deviceRangeEnd(range_handle: object, stream: int) -> None: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_onnx.pyi ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Defined in torch/csrc/onnx/init.cpp
2
+
3
+ from enum import Enum
4
+
5
+ PRODUCER_VERSION: str
6
+
7
+ class TensorProtoDataType(Enum):
8
+ UNDEFINED = ...
9
+ FLOAT = ...
10
+ UINT8 = ...
11
+ INT8 = ...
12
+ UINT16 = ...
13
+ INT16 = ...
14
+ INT32 = ...
15
+ INT64 = ...
16
+ STRING = ...
17
+ BOOL = ...
18
+ FLOAT16 = ...
19
+ DOUBLE = ...
20
+ UINT32 = ...
21
+ UINT64 = ...
22
+ COMPLEX64 = ...
23
+ COMPLEX128 = ...
24
+ BFLOAT16 = ...
25
+ FLOAT8E5M2 = ...
26
+ FLOAT8E4M3FN = ...
27
+ FLOAT8E5M2FNUZ = ...
28
+ FLOAT8E4M3FNUZ = ...
29
+
30
+ class OperatorExportTypes(Enum):
31
+ ONNX = ...
32
+ ONNX_ATEN = ...
33
+ ONNX_ATEN_FALLBACK = ...
34
+ ONNX_FALLTHROUGH = ...
35
+
36
+ class TrainingMode(Enum):
37
+ EVAL = ...
38
+ PRESERVE = ...
39
+ TRAINING = ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_profiler.pyi ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import Literal
3
+ from typing_extensions import TypeAlias
4
+
5
+ from torch._C import device, dtype, layout
6
+
7
+ # defined in torch/csrc/profiler/python/init.cpp
8
+
9
+ class RecordScope(Enum):
10
+ FUNCTION = ...
11
+ BACKWARD_FUNCTION = ...
12
+ TORCHSCRIPT_FUNCTION = ...
13
+ KERNEL_FUNCTION_DTYPE = ...
14
+ CUSTOM_CLASS = ...
15
+ BUILD_FEATURE = ...
16
+ LITE_INTERPRETER = ...
17
+ USER_SCOPE = ...
18
+ STATIC_RUNTIME_OP = ...
19
+ STATIC_RUNTIME_MODEL = ...
20
+
21
+ class ProfilerState(Enum):
22
+ Disable = ...
23
+ CPU = ...
24
+ CUDA = ...
25
+ NVTX = ...
26
+ ITT = ...
27
+ KINETO = ...
28
+ KINETO_GPU_FALLBACK = ...
29
+ KINETO_PRIVATEUSE1_FALLBACK = ...
30
+ KINETO_PRIVATEUSE1 = ...
31
+
32
+ class ActiveProfilerType(Enum):
33
+ NONE = ...
34
+ LEGACY = ...
35
+ KINETO = ...
36
+ NVTX = ...
37
+ ITT = ...
38
+
39
+ class ProfilerActivity(Enum):
40
+ CPU = ...
41
+ CUDA = ...
42
+ XPU = ...
43
+ MTIA = ...
44
+ HPU = ...
45
+ PrivateUse1 = ...
46
+
47
+ class _EventType(Enum):
48
+ TorchOp = ...
49
+ Backend = ...
50
+ Allocation = ...
51
+ OutOfMemory = ...
52
+ PyCall = ...
53
+ PyCCall = ...
54
+ Kineto = ...
55
+
56
+ class _ExperimentalConfig:
57
+ def __init__(
58
+ self,
59
+ profiler_metrics: list[str] = ...,
60
+ profiler_measure_per_kernel: bool = ...,
61
+ verbose: bool = ...,
62
+ performance_events: list[str] = ...,
63
+ enable_cuda_sync_events: bool = ...,
64
+ ) -> None: ...
65
+
66
+ class ProfilerConfig:
67
+ def __init__(
68
+ self,
69
+ state: ProfilerState,
70
+ report_input_shapes: bool,
71
+ profile_memory: bool,
72
+ with_stack: bool,
73
+ with_flops: bool,
74
+ with_modules: bool,
75
+ experimental_config: _ExperimentalConfig,
76
+ trace_id: str | None = None,
77
+ ) -> None: ...
78
+
79
+ class _ProfilerEvent:
80
+ start_tid: int
81
+ start_time_ns: int
82
+ children: list[_ProfilerEvent]
83
+
84
+ # TODO(robieta): remove in favor of `self.typed`
85
+ extra_fields: (
86
+ _ExtraFields_TorchOp
87
+ | _ExtraFields_Backend
88
+ | _ExtraFields_Allocation
89
+ | _ExtraFields_OutOfMemory
90
+ | _ExtraFields_PyCall
91
+ | _ExtraFields_PyCCall
92
+ | _ExtraFields_Kineto
93
+ )
94
+
95
+ @property
96
+ def typed(
97
+ self,
98
+ ) -> (
99
+ tuple[Literal[_EventType.TorchOp], _ExtraFields_TorchOp]
100
+ | tuple[Literal[_EventType.Backend], _ExtraFields_Backend]
101
+ | tuple[Literal[_EventType.Allocation], _ExtraFields_Allocation]
102
+ | tuple[Literal[_EventType.OutOfMemory], _ExtraFields_OutOfMemory]
103
+ | tuple[Literal[_EventType.PyCall], _ExtraFields_PyCall]
104
+ | tuple[Literal[_EventType.PyCCall], _ExtraFields_PyCCall]
105
+ | tuple[Literal[_EventType.Kineto], _ExtraFields_Kineto]
106
+ ): ...
107
+ @property
108
+ def name(self) -> str: ...
109
+ @property
110
+ def tag(self) -> _EventType: ...
111
+ @property
112
+ def id(self) -> int: ...
113
+ @property
114
+ def parent(self) -> _ProfilerEvent | None: ...
115
+ @property
116
+ def correlation_id(self) -> int: ...
117
+ @property
118
+ def end_time_ns(self) -> int: ...
119
+ @property
120
+ def duration_time_ns(self) -> int: ...
121
+
122
+ class _TensorMetadata:
123
+ impl_ptr: int | None
124
+ storage_data_ptr: int | None
125
+ id: int | None
126
+
127
+ @property
128
+ def allocation_id(self) -> int | None: ...
129
+ @property
130
+ def layout(self) -> layout: ...
131
+ @property
132
+ def device(self) -> device: ...
133
+ @property
134
+ def dtype(self) -> dtype: ...
135
+ @property
136
+ def sizes(self) -> list[int]: ...
137
+ @property
138
+ def strides(self) -> list[int]: ...
139
+
140
+ Scalar: TypeAlias = int | float | bool | complex
141
+ Input: TypeAlias = _TensorMetadata | list[_TensorMetadata] | Scalar | None
142
+
143
+ class _ExtraFields_TorchOp:
144
+ name: str
145
+ sequence_number: int
146
+ allow_tf32_cublas: bool
147
+
148
+ @property
149
+ def inputs(self) -> list[Input]: ...
150
+ @property
151
+ def scope(self) -> RecordScope: ...
152
+
153
+ class _ExtraFields_Backend: ...
154
+
155
+ class _ExtraFields_Allocation:
156
+ ptr: int
157
+ id: int | None
158
+ alloc_size: int
159
+ total_allocated: int
160
+ total_reserved: int
161
+
162
+ @property
163
+ def allocation_id(self) -> int | None: ...
164
+ @property
165
+ def device(self) -> device: ...
166
+
167
+ class _ExtraFields_OutOfMemory: ...
168
+
169
+ class _PyFrameState:
170
+ line_number: int
171
+ function_name: str
172
+
173
+ @property
174
+ def file_name(self) -> str: ...
175
+
176
+ class _NNModuleInfo:
177
+ @property
178
+ def self_ptr(self) -> int: ...
179
+ @property
180
+ def cls_ptr(self) -> int: ...
181
+ @property
182
+ def cls_name(self) -> str: ...
183
+ @property
184
+ def parameters(
185
+ self,
186
+ ) -> list[tuple[str, _TensorMetadata, _TensorMetadata | None]]: ...
187
+
188
+ class _OptimizerInfo:
189
+ @property
190
+ def parameters(
191
+ self,
192
+ ) -> list[
193
+ tuple[
194
+ # Parameter
195
+ _TensorMetadata,
196
+ #
197
+ # Gradient (if present during optimizer.step())
198
+ _TensorMetadata | None,
199
+ #
200
+ # Optimizer state for Parameter as (name, tensor) pairs
201
+ list[tuple[str, _TensorMetadata]],
202
+ ]
203
+ ]: ...
204
+
205
+ class _ExtraFields_PyCCall:
206
+ @property
207
+ def caller(self) -> _PyFrameState: ...
208
+
209
+ class _ExtraFields_PyCall:
210
+ @property
211
+ def callsite(self) -> _PyFrameState: ...
212
+ @property
213
+ def caller(self) -> _PyFrameState: ...
214
+ @property
215
+ def module(self) -> _NNModuleInfo | None: ...
216
+ @property
217
+ def optimizer(self) -> _OptimizerInfo | None: ...
218
+
219
+ class _ExtraFields_Kineto: ...
220
+
221
+ def _add_execution_trace_observer(output_file_path: str) -> bool: ...
222
+ def _remove_execution_trace_observer() -> None: ...
223
+ def _enable_execution_trace_observer() -> None: ...
224
+ def _disable_execution_trace_observer() -> None: ...
225
+ def _set_record_concrete_inputs_enabled_val(val: bool) -> None: ...
226
+ def _set_fwd_bwd_enabled_val(val: bool) -> None: ...
227
+ def _set_cuda_sync_enabled_val(val: bool) -> None: ...
228
+
229
+ class CapturedTraceback: ...
230
+
231
+ def gather_traceback(python: bool, script: bool, cpp: bool) -> CapturedTraceback: ...
232
+
233
+ # The Dict has name, filename, line
234
+ def symbolize_tracebacks(
235
+ to_symbolize: list[CapturedTraceback],
236
+ ) -> list[list[dict[str, str]]]: ...
237
+
238
+ class _RecordFunctionFast:
239
+ def __init__(
240
+ self,
241
+ name: str,
242
+ input_values: list | tuple | None = None,
243
+ keyword_values: dict | None = None,
244
+ ) -> None: ...
245
+ def __enter__(self) -> None: ...
246
+ def __exit__(self, *exc_info: object) -> None: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C/_verbose.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Defined in torch/csrc/utils/verbose.cpp
2
+ def mkl_set_verbose(enable: int) -> int: ...
3
+ def mkldnn_set_verbose(level: int) -> int: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/_conversions.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/fft.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/_conversions.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch._prims_common as utils
4
+
5
+ # Utilities should come BEFORE this import
6
+ from torch._decomp import register_decomposition
7
+ from torch._prims_common import TensorLikeType
8
+ from torch._prims_common.wrappers import out_wrapper
9
+ from torch._refs import _broadcast_shapes
10
+
11
+
12
+ # Data conversion references.
13
+ #
14
+ # Note: this module breaks the usual _refs to torch naming scheme where
15
+ # _refs.foo.bar is a ref for torch.foo.bar. The following definitions are not
16
+ # part of _refs/__init__.py to avoid name clashes with Python builtin types
17
+ # (like int).
18
+
19
+ __all__ = [
20
+ # dtypes
21
+ "bfloat16",
22
+ "bool",
23
+ "byte",
24
+ "cdouble",
25
+ "cfloat",
26
+ "chalf",
27
+ "char",
28
+ "double",
29
+ "float",
30
+ "half",
31
+ "int",
32
+ "long",
33
+ "short",
34
+ # misc
35
+ "complex",
36
+ "polar",
37
+ ]
38
+
39
+
40
+ def _make_conversion_method(name: str, dtype: torch.dtype):
41
+ def fn(
42
+ self: TensorLikeType, memory_format: torch.memory_format = torch.preserve_format
43
+ ) -> TensorLikeType:
44
+ return self.to(dtype, memory_format=memory_format) # type: ignore[call-overload]
45
+
46
+ fn.__name__ = name
47
+ return fn
48
+
49
+
50
+ bfloat16 = _make_conversion_method("bfloat16", torch.bfloat16)
51
+
52
+ bool = _make_conversion_method("bool", torch.bool)
53
+
54
+ byte = _make_conversion_method("byte", torch.uint8)
55
+
56
+ cdouble = _make_conversion_method("cdouble", torch.cdouble)
57
+
58
+ cfloat = _make_conversion_method("cfloat", torch.cfloat)
59
+
60
+ chalf = _make_conversion_method("chalf", torch.complex32)
61
+
62
+ char = _make_conversion_method("char", torch.int8)
63
+
64
+ double = _make_conversion_method("double", torch.double)
65
+
66
+ float = _make_conversion_method("float", torch.float)
67
+
68
+ half = _make_conversion_method("half", torch.half)
69
+
70
+ int = _make_conversion_method("int", torch.int)
71
+
72
+ long = _make_conversion_method("long", torch.long)
73
+
74
+ short = _make_conversion_method("short", torch.short)
75
+
76
+
77
+ @register_decomposition(torch._ops.ops.aten.complex)
78
+ # Note: complex has type promotion tests disabled due to different semantics.
79
+ # exact_dtype is for compat with complex_check_dtype from core.
80
+ @out_wrapper(exact_dtype=True)
81
+ def complex(real: TensorLikeType, imag: TensorLikeType) -> TensorLikeType:
82
+ allowed_dtypes = (torch.float32, torch.float64, torch.float16)
83
+ torch._check(
84
+ real.dtype in allowed_dtypes and imag.dtype in allowed_dtypes,
85
+ lambda: (
86
+ f"Expected both inputs to be Half, Float or Double tensors but got "
87
+ f"{real.dtype} and {imag.dtype}"
88
+ ),
89
+ )
90
+ torch._check(
91
+ real.dtype == imag.dtype,
92
+ lambda: (
93
+ f"Expected object of scalar type {real.dtype} but got "
94
+ f"scalar type {imag.dtype} for second argument"
95
+ ),
96
+ )
97
+ result_dtype = utils.corresponding_complex_dtype(real.dtype) # type: ignore[arg-type]
98
+ common_shape = _broadcast_shapes(real.shape, imag.shape)
99
+ result = real.new_empty(
100
+ common_shape,
101
+ dtype=result_dtype,
102
+ layout=real.layout,
103
+ device=real.device,
104
+ # pin_memory=real.is_pinned(), # NYI
105
+ )
106
+ result.real = real
107
+ result.imag = imag
108
+ return result
109
+
110
+
111
+ @register_decomposition(torch._ops.ops.aten.polar)
112
+ # Note: polar has type promotion tests disabled due to different semantics.
113
+ # exact_dtype is for compat with complex_check_dtype from core.
114
+ @out_wrapper(exact_dtype=True)
115
+ def polar(abs: TensorLikeType, angle: TensorLikeType) -> TensorLikeType:
116
+ result = torch.complex(abs, angle)
117
+ result.real = abs * torch.cos(angle)
118
+ result.imag = abs * torch.sin(angle)
119
+ return result
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/fft.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections.abc import Iterable, Sequence
3
+ from typing import Literal, NamedTuple, Optional, Union
4
+
5
+ import torch
6
+ import torch._prims as prims
7
+ import torch._prims_common as utils
8
+ from torch._decomp import register_decomposition
9
+ from torch._prims_common import DimsType, ShapeType, TensorLikeType
10
+ from torch._prims_common.wrappers import _maybe_convert_to_dtype, out_wrapper
11
+
12
+
13
+ __all__ = [
14
+ # Transforms
15
+ "fft",
16
+ "fft2",
17
+ "fftn",
18
+ "hfft",
19
+ "hfft2",
20
+ "hfftn",
21
+ "rfft",
22
+ "rfft2",
23
+ "rfftn",
24
+ "ifft",
25
+ "ifft2",
26
+ "ifftn",
27
+ "ihfft",
28
+ "ihfft2",
29
+ "ihfftn",
30
+ "irfft",
31
+ "irfft2",
32
+ "irfftn",
33
+ # Helpers
34
+ "fftshift",
35
+ "ifftshift",
36
+ ]
37
+
38
+ NormType = Union[None, Literal["forward", "backward", "ortho"]]
39
+ _NORM_VALUES = {None, "forward", "backward", "ortho"}
40
+ aten = torch._ops.ops.aten
41
+
42
+
43
+ def _apply_norm(
44
+ x: TensorLikeType, norm: NormType, signal_numel: int, forward: bool
45
+ ) -> TensorLikeType:
46
+ """Apply normalization to the un-normalized FFT result"""
47
+ torch._check(norm in _NORM_VALUES, lambda: f"Invalid normalization mode: {norm}")
48
+
49
+ if norm == "ortho":
50
+ return x * (1 / math.sqrt(signal_numel))
51
+
52
+ normalize = (not forward and (norm is None or norm == "backward")) or (
53
+ forward and norm == "forward"
54
+ )
55
+ return x * (1 / signal_numel) if normalize else x
56
+
57
+
58
+ def _promote_type_fft(
59
+ dtype: torch.dtype, require_complex: bool, device: torch.device
60
+ ) -> torch.dtype:
61
+ """Helper to promote a dtype to one supported by the FFT primitives"""
62
+ if dtype.is_complex:
63
+ return dtype
64
+
65
+ # Promote integral to default float type
66
+ if not dtype.is_floating_point:
67
+ dtype = torch.get_default_dtype()
68
+
69
+ allowed_types = [torch.float32, torch.float64]
70
+ maybe_support_half = device.type in ["cuda", "meta"]
71
+
72
+ if maybe_support_half:
73
+ allowed_types.append(torch.float16)
74
+ torch._check(dtype in allowed_types, lambda: f"Unsupported dtype {dtype}")
75
+
76
+ if require_complex:
77
+ dtype = utils.corresponding_complex_dtype(dtype)
78
+
79
+ return dtype
80
+
81
+
82
+ def _maybe_promote_tensor_fft(
83
+ t: TensorLikeType, require_complex: bool = False
84
+ ) -> TensorLikeType:
85
+ """Helper to promote a tensor to a dtype supported by the FFT primitives"""
86
+ cur_type = t.dtype
87
+ new_type = _promote_type_fft(cur_type, require_complex, t.device)
88
+ return _maybe_convert_to_dtype(t, new_type) # type: ignore[return-value]
89
+
90
+
91
+ def _resize_fft_input(
92
+ x: TensorLikeType, dims: tuple[int, ...], sizes: tuple[int, ...]
93
+ ) -> TensorLikeType:
94
+ """
95
+ Fixes the shape of x such that x.size(dims[i]) == sizes[i],
96
+ either by zero-padding, or by slicing x starting from 0.
97
+ """
98
+ assert len(dims) == len(sizes)
99
+ must_copy = False
100
+ x_sizes = x.shape
101
+ pad_amount = [0] * len(x_sizes) * 2
102
+ for i in range(len(dims)):
103
+ if sizes[i] == -1:
104
+ continue
105
+
106
+ if x_sizes[dims[i]] < sizes[i]:
107
+ must_copy = True
108
+ pad_idx = len(pad_amount) - 2 * dims[i] - 1
109
+ pad_amount[pad_idx] = sizes[i] - x_sizes[dims[i]]
110
+
111
+ if x_sizes[dims[i]] > sizes[i]:
112
+ x = x.narrow(dims[i], 0, sizes[i])
113
+
114
+ return torch.constant_pad_nd(x, pad_amount) if must_copy else x
115
+
116
+
117
+ def _fft_c2r(
118
+ func_name: str,
119
+ input: TensorLikeType,
120
+ n: Optional[int],
121
+ dim: int,
122
+ norm: NormType,
123
+ forward: bool,
124
+ ) -> TensorLikeType:
125
+ """Common code for performing any complex to real FFT (irfft or hfft)"""
126
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
127
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
128
+ last_dim_size = n if n is not None else 2 * (input.shape[dim] - 1)
129
+ torch._check(
130
+ last_dim_size >= 1,
131
+ lambda: f"Invalid number of data points ({last_dim_size}) specified",
132
+ )
133
+
134
+ if n is not None:
135
+ input = _resize_fft_input(input, dims=dims, sizes=(last_dim_size // 2 + 1,))
136
+
137
+ if forward:
138
+ input = torch.conj(input)
139
+
140
+ output = prims.fft_c2r(input, dim=dims, last_dim_size=last_dim_size)
141
+ return _apply_norm(output, norm=norm, signal_numel=last_dim_size, forward=forward)
142
+
143
+
144
+ def _fft_r2c(
145
+ func_name: str,
146
+ input: TensorLikeType,
147
+ n: Optional[int],
148
+ dim: int,
149
+ norm: NormType,
150
+ forward: bool,
151
+ onesided: bool,
152
+ ) -> TensorLikeType:
153
+ """Common code for performing any real to complex FFT (rfft or ihfft)"""
154
+ torch._check(
155
+ not input.dtype.is_complex,
156
+ lambda: f"{func_name} expects a floating point input tensor, but got {input.dtype}",
157
+ )
158
+ input = _maybe_promote_tensor_fft(input)
159
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
160
+ dim_size = n if n is not None else input.shape[dim]
161
+ torch._check(
162
+ dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified"
163
+ )
164
+
165
+ if n is not None:
166
+ input = _resize_fft_input(input, dims, (n,))
167
+
168
+ ret = prims.fft_r2c(input, dim=dims, onesided=onesided)
169
+ ret = _apply_norm(ret, norm, dim_size, forward)
170
+ return ret if forward else torch.conj(ret)
171
+
172
+
173
+ def _fft_c2c(
174
+ func_name: str,
175
+ input: TensorLikeType,
176
+ n: Optional[int],
177
+ dim: int,
178
+ norm: NormType,
179
+ forward: bool,
180
+ ) -> TensorLikeType:
181
+ """Common code for performing any complex to complex FFT (fft or ifft)"""
182
+ torch._check(
183
+ input.dtype.is_complex,
184
+ lambda: f"{func_name} expects a complex input tensor, but got {input.dtype}",
185
+ )
186
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
187
+ dim_size = n if n is not None else input.shape[dim]
188
+ torch._check(
189
+ dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified"
190
+ )
191
+
192
+ if n is not None:
193
+ input = _resize_fft_input(input, dims, (n,))
194
+
195
+ ret = prims.fft_c2c(input, dim=dims, forward=forward)
196
+ return _apply_norm(ret, norm, dim_size, forward)
197
+
198
+
199
+ @register_decomposition(aten.fft_fft)
200
+ @out_wrapper()
201
+ def fft(
202
+ input: TensorLikeType,
203
+ n: Optional[int] = None,
204
+ dim: int = -1,
205
+ norm: NormType = None,
206
+ ) -> TensorLikeType:
207
+ if input.dtype.is_complex:
208
+ return _fft_c2c("fft", input, n, dim, norm, forward=True)
209
+ else:
210
+ return _fft_r2c("fft", input, n, dim, norm, forward=True, onesided=False)
211
+
212
+
213
+ @register_decomposition(aten.fft_ifft)
214
+ @out_wrapper()
215
+ def ifft(
216
+ input: TensorLikeType,
217
+ n: Optional[int] = None,
218
+ dim: int = -1,
219
+ norm: NormType = None,
220
+ ) -> TensorLikeType:
221
+ if input.dtype.is_complex:
222
+ return _fft_c2c("ifft", input, n, dim, norm, forward=False)
223
+ else:
224
+ return _fft_r2c("ifft", input, n, dim, norm, forward=False, onesided=False)
225
+
226
+
227
+ @register_decomposition(aten.fft_rfft)
228
+ @out_wrapper()
229
+ def rfft(
230
+ input: TensorLikeType,
231
+ n: Optional[int] = None,
232
+ dim: int = -1,
233
+ norm: NormType = None,
234
+ ) -> TensorLikeType:
235
+ return _fft_r2c("rfft", input, n, dim, norm, forward=True, onesided=True)
236
+
237
+
238
+ @register_decomposition(aten.fft_irfft)
239
+ @out_wrapper()
240
+ def irfft(
241
+ input: TensorLikeType,
242
+ n: Optional[int] = None,
243
+ dim: int = -1,
244
+ norm: NormType = None,
245
+ ) -> TensorLikeType:
246
+ return _fft_c2r("irfft", input, n, dim, norm, forward=False)
247
+
248
+
249
+ @register_decomposition(aten.fft_hfft)
250
+ @out_wrapper()
251
+ def hfft(
252
+ input: TensorLikeType,
253
+ n: Optional[int] = None,
254
+ dim: int = -1,
255
+ norm: NormType = None,
256
+ ) -> TensorLikeType:
257
+ return _fft_c2r("hfft", input, n, dim, norm, forward=True)
258
+
259
+
260
+ @register_decomposition(aten.fft_ihfft)
261
+ @out_wrapper()
262
+ def ihfft(
263
+ input: TensorLikeType,
264
+ n: Optional[int] = None,
265
+ dim: int = -1,
266
+ norm: NormType = None,
267
+ ) -> TensorLikeType:
268
+ return _fft_r2c("ihfft", input, n, dim, norm, forward=False, onesided=True)
269
+
270
+
271
+ class _ShapeAndDims(NamedTuple):
272
+ shape: tuple[int, ...]
273
+ dims: tuple[int, ...]
274
+
275
+
276
+ def _canonicalize_fft_shape_and_dim_args(
277
+ input: TensorLikeType, shape: Optional[ShapeType], dim: Optional[DimsType]
278
+ ) -> _ShapeAndDims:
279
+ """Convert the shape and dim arguments into a canonical form where neither are optional"""
280
+ input_dim = input.ndim
281
+ input_sizes = input.shape
282
+
283
+ if dim is not None:
284
+ if not isinstance(dim, Sequence):
285
+ dim = (dim,)
286
+ ret_dims = utils.canonicalize_dims(input_dim, dim, wrap_scalar=False)
287
+
288
+ # Check dims are unique
289
+ torch._check(
290
+ len(set(ret_dims)) == len(ret_dims), lambda: "FFT dims must be unique"
291
+ )
292
+
293
+ if shape is not None:
294
+ if not isinstance(shape, Sequence):
295
+ shape = (shape,)
296
+
297
+ # Has shape, might have dim
298
+ torch._check(
299
+ dim is None or len(dim) == len(shape),
300
+ lambda: "When given, dim and shape arguments must have the same length",
301
+ )
302
+ transform_ndim = len(shape)
303
+
304
+ torch._check(
305
+ transform_ndim <= input_dim,
306
+ lambda: f"Got shape with {transform_ndim} values but input tensor "
307
+ f"only has {input_dim} dimensions.",
308
+ )
309
+
310
+ # If shape is given, dims defaults to the last len(shape) dimensions
311
+ if dim is None:
312
+ ret_dims = tuple(range(input_dim - transform_ndim, input_dim))
313
+
314
+ # Translate any -1 values in shape to the default length
315
+ ret_shape = tuple(
316
+ s if s != -1 else input_sizes[d]
317
+ for (s, d) in zip(shape, ret_dims) # type: ignore[possibly-undefined]
318
+ )
319
+ elif dim is None:
320
+ # No shape, no dim
321
+ ret_dims = tuple(range(input_dim))
322
+ ret_shape = tuple(input_sizes)
323
+ else:
324
+ # No shape, has dim
325
+ ret_shape = tuple(input_sizes[d] for d in ret_dims) # type: ignore[possibly-undefined]
326
+
327
+ for n in ret_shape:
328
+ torch._check(n > 0, lambda: f"Invalid number of data points ({n}) specified")
329
+
330
+ return _ShapeAndDims(shape=ret_shape, dims=ret_dims) # type: ignore[possibly-undefined]
331
+
332
+
333
+ def _prod(xs: Iterable[int]) -> int:
334
+ """Compute product of a list"""
335
+ prod = 1
336
+ for x in xs:
337
+ prod *= x
338
+ return prod
339
+
340
+
341
+ def _fftn_c2c(
342
+ function_name: str,
343
+ input: TensorLikeType,
344
+ shape: tuple[int, ...],
345
+ dim: tuple[int, ...],
346
+ norm: NormType,
347
+ forward: bool,
348
+ ) -> TensorLikeType:
349
+ """Common code for n-dimensional complex to complex FFTs (fftn or ifftn)"""
350
+ torch._check(
351
+ input.dtype.is_complex,
352
+ lambda: f"{function_name} expects a complex input tensor, "
353
+ f"but got {input.dtype}",
354
+ )
355
+ x = _resize_fft_input(input, dim, shape)
356
+ output = prims.fft_c2c(x, dim=dim, forward=forward)
357
+ return _apply_norm(output, norm=norm, signal_numel=_prod(shape), forward=forward)
358
+
359
+
360
+ @register_decomposition(aten.fft_fftn)
361
+ @out_wrapper()
362
+ def fftn(
363
+ input: TensorLikeType,
364
+ s: Optional[ShapeType] = None,
365
+ dim: Optional[DimsType] = None,
366
+ norm: NormType = None,
367
+ ) -> TensorLikeType:
368
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
369
+ x = _maybe_promote_tensor_fft(input, require_complex=True)
370
+ return _fftn_c2c("fftn", x, shape, dim, norm, forward=True)
371
+
372
+
373
+ @register_decomposition(aten.fft_ifftn)
374
+ @out_wrapper()
375
+ def ifftn(
376
+ input: TensorLikeType,
377
+ s: Optional[ShapeType] = None,
378
+ dim: Optional[DimsType] = None,
379
+ norm: NormType = None,
380
+ ) -> TensorLikeType:
381
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
382
+ x = _maybe_promote_tensor_fft(input, require_complex=True)
383
+ return _fftn_c2c("ifftn", x, shape, dim, norm, forward=False)
384
+
385
+
386
+ @register_decomposition(aten.fft_rfftn)
387
+ @out_wrapper()
388
+ def rfftn(
389
+ input: TensorLikeType,
390
+ s: Optional[ShapeType] = None,
391
+ dim: Optional[DimsType] = None,
392
+ norm: NormType = None,
393
+ ) -> TensorLikeType:
394
+ torch._check(
395
+ not input.dtype.is_complex,
396
+ lambda: f"rfftn expects a real-valued input tensor, but got {input.dtype}",
397
+ )
398
+ shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim)
399
+ input = _maybe_promote_tensor_fft(input, require_complex=False)
400
+ input = _resize_fft_input(input, dim, shape)
401
+ out = prims.fft_r2c(input, dim=dim, onesided=True)
402
+ return _apply_norm(out, norm=norm, signal_numel=_prod(shape), forward=True)
403
+
404
+
405
+ @register_decomposition(aten.fft_ihfftn)
406
+ @out_wrapper()
407
+ def ihfftn(
408
+ input: TensorLikeType,
409
+ s: Optional[ShapeType] = None,
410
+ dim: Optional[DimsType] = None,
411
+ norm: NormType = None,
412
+ ) -> TensorLikeType:
413
+ torch._check(
414
+ not input.dtype.is_complex,
415
+ lambda: f"ihfftn expects a real-valued input tensor, but got {input.dtype}",
416
+ )
417
+ shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim)
418
+ torch._check(len(shape) > 0, lambda: "ihfftn must transform at least one axis")
419
+ input = _maybe_promote_tensor_fft(input, require_complex=False)
420
+ input = _resize_fft_input(input, dim, shape)
421
+
422
+ tmp = prims.fft_r2c(input, dim=dim[-1:], onesided=True)
423
+
424
+ if len(dim) == 1:
425
+ tmp = _apply_norm(tmp, norm=norm, signal_numel=shape[0], forward=False)
426
+ return prims.conj(tmp)
427
+
428
+ tmp = prims.conj_physical(tmp)
429
+ tmp = prims.fft_c2c(tmp, dim=dim[:-1], forward=False)
430
+ return _apply_norm(tmp, norm=norm, signal_numel=_prod(shape), forward=False)
431
+
432
+
433
+ class _CanonicalizeC2rReturn(NamedTuple):
434
+ shape: tuple[int, ...]
435
+ dim: tuple[int, ...]
436
+ last_dim_size: int
437
+
438
+
439
+ def _canonicalize_fft_c2r_shape_and_dim_args(
440
+ fname: str,
441
+ input: TensorLikeType,
442
+ s: Optional[ShapeType],
443
+ dim: Optional[DimsType],
444
+ ) -> _CanonicalizeC2rReturn:
445
+ """Canonicalize shape and dim arguments for n-dimensional c2r transforms,
446
+ as well as calculating the last_dim_size which is shape[dim[-1]] for the output"""
447
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
448
+ torch._check(len(shape) > 0, lambda: f"{fname} must transform at least one axis")
449
+
450
+ if s is None or s[-1] == -1:
451
+ last_dim_size = 2 * (input.shape[dim[-1]] - 1)
452
+ else:
453
+ last_dim_size = shape[-1]
454
+
455
+ torch._check(
456
+ last_dim_size >= 1,
457
+ lambda: f"Invalid number of data points ({last_dim_size}) specified",
458
+ )
459
+
460
+ shape_list = list(shape)
461
+ shape_list[-1] = last_dim_size // 2 + 1
462
+ return _CanonicalizeC2rReturn(
463
+ shape=tuple(shape_list), dim=dim, last_dim_size=last_dim_size
464
+ )
465
+
466
+
467
+ @register_decomposition(aten.fft_irfftn)
468
+ @out_wrapper()
469
+ def irfftn(
470
+ input: TensorLikeType,
471
+ s: Optional[ShapeType] = None,
472
+ dim: Optional[DimsType] = None,
473
+ norm: NormType = None,
474
+ ) -> TensorLikeType:
475
+ shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args(
476
+ "irfftn", input, s, dim
477
+ )
478
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
479
+ input = _resize_fft_input(input, dim, shape)
480
+ out = prims.fft_c2r(input, dim=dim, last_dim_size=last_dim_size)
481
+ return _apply_norm(out, norm, _prod(out.shape[d] for d in dim), forward=False)
482
+
483
+
484
+ @register_decomposition(aten.fft_hfftn)
485
+ @out_wrapper()
486
+ def hfftn(
487
+ input: TensorLikeType,
488
+ s: Optional[ShapeType] = None,
489
+ dim: Optional[DimsType] = None,
490
+ norm: NormType = None,
491
+ ) -> TensorLikeType:
492
+ shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args(
493
+ "hfftn", input, s, dim
494
+ )
495
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
496
+ input = _resize_fft_input(input, dim, shape)
497
+
498
+ tmp = prims.fft_c2c(input, dim=dim[:-1], forward=True) if len(dim) > 1 else input
499
+ tmp = _apply_norm(tmp, norm, _prod(shape[:-1]), forward=True)
500
+ tmp = prims.conj_physical(tmp)
501
+ out = prims.fft_c2r(tmp, dim=dim[-1:], last_dim_size=last_dim_size)
502
+ return _apply_norm(out, norm, last_dim_size, forward=True)
503
+
504
+
505
+ @register_decomposition(aten.fft_fft2)
506
+ @out_wrapper()
507
+ def fft2(
508
+ input: TensorLikeType,
509
+ s: Optional[ShapeType] = None,
510
+ dim: Optional[DimsType] = (-2, -1),
511
+ norm: NormType = None,
512
+ ) -> TensorLikeType:
513
+ return torch.fft.fftn(input, s=s, dim=dim, norm=norm)
514
+
515
+
516
+ @register_decomposition(aten.fft_ifft2)
517
+ @out_wrapper()
518
+ def ifft2(
519
+ input: TensorLikeType,
520
+ s: Optional[ShapeType] = None,
521
+ dim: Optional[DimsType] = (-2, -1),
522
+ norm: NormType = None,
523
+ ) -> TensorLikeType:
524
+ return torch.fft.ifftn(input, s=s, dim=dim, norm=norm)
525
+
526
+
527
+ @register_decomposition(aten.fft_rfft2)
528
+ @out_wrapper()
529
+ def rfft2(
530
+ input: TensorLikeType,
531
+ s: Optional[ShapeType] = None,
532
+ dim: Optional[DimsType] = (-2, -1),
533
+ norm: NormType = None,
534
+ ) -> TensorLikeType:
535
+ return torch.fft.rfftn(input, s=s, dim=dim, norm=norm)
536
+
537
+
538
+ @register_decomposition(aten.fft_irfft2)
539
+ @out_wrapper()
540
+ def irfft2(
541
+ input: TensorLikeType,
542
+ s: Optional[ShapeType] = None,
543
+ dim: Optional[DimsType] = (-2, -1),
544
+ norm: NormType = None,
545
+ ) -> TensorLikeType:
546
+ return torch.fft.irfftn(input, s=s, dim=dim, norm=norm)
547
+
548
+
549
+ @register_decomposition(aten.fft_hfft2)
550
+ @out_wrapper()
551
+ def hfft2(
552
+ input: TensorLikeType,
553
+ s: Optional[ShapeType] = None,
554
+ dim: Optional[DimsType] = (-2, -1),
555
+ norm: NormType = None,
556
+ ) -> TensorLikeType:
557
+ return torch.fft.hfftn(input, s=s, dim=dim, norm=norm)
558
+
559
+
560
+ @register_decomposition(aten.fft_ihfft2)
561
+ @out_wrapper()
562
+ def ihfft2(
563
+ input: TensorLikeType,
564
+ s: Optional[ShapeType] = None,
565
+ dim: Optional[DimsType] = (-2, -1),
566
+ norm: NormType = None,
567
+ ) -> TensorLikeType:
568
+ return torch.fft.ihfftn(input, s=s, dim=dim, norm=norm)
569
+
570
+
571
+ def _default_alldims(dim: Optional[DimsType], x: TensorLikeType) -> list[int]:
572
+ """Convert Optional[DimsType] to a simple list, defaulting to all dimensions"""
573
+ if dim is None:
574
+ return list(range(x.ndim))
575
+ elif not isinstance(dim, Sequence):
576
+ return [dim]
577
+ else:
578
+ return list(dim)
579
+
580
+
581
+ @register_decomposition(aten.fft_fftshift)
582
+ def fftshift(input: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
583
+ dims = _default_alldims(dim, input)
584
+ shift = [input.shape[d] // 2 for d in dims]
585
+ return torch.roll(input, shift, dims)
586
+
587
+
588
+ @register_decomposition(aten.fft_ifftshift)
589
+ def ifftshift(input: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
590
+ dims = _default_alldims(dim, input)
591
+ shift = [(input.shape[d] + 1) // 2 for d in dims]
592
+ return torch.roll(input, shift, dims)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from functools import partial
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch._prims as prims
7
+ import torch._prims_common as utils
8
+ import torch._refs as refs
9
+ import torch._refs.linalg as linalg
10
+ from torch import Tensor
11
+ from torch._prims_common import (
12
+ check_fp_or_complex,
13
+ check_is_matrix,
14
+ Dim,
15
+ DimsType,
16
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
17
+ IntLike,
18
+ TensorLikeType,
19
+ )
20
+ from torch._prims_common.wrappers import (
21
+ _maybe_convert_to_dtype,
22
+ elementwise_type_promotion_wrapper,
23
+ out_wrapper,
24
+ )
25
+
26
+
27
+ __all__ = [
28
+ "diagonal",
29
+ "matrix_norm",
30
+ "norm",
31
+ "svd",
32
+ "svdvals",
33
+ "vector_norm",
34
+ "vecdot",
35
+ "cross",
36
+ ]
37
+
38
+
39
+ def _check_norm_dtype(dtype: Optional[torch.dtype], x_dtype: torch.dtype, fn_name: str):
40
+ """
41
+ Checks related to the dtype kwarg in `linalg.*norm` functions
42
+ """
43
+ if dtype is not None:
44
+ torch._check(
45
+ utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype),
46
+ lambda: f"{fn_name}: dtype should be floating point or complex. Got {dtype}",
47
+ )
48
+ torch._check(
49
+ utils.is_complex_dtype(dtype) == utils.is_complex_dtype(x_dtype),
50
+ lambda: "{fn_name}: dtype should be {d} for {d} inputs. Got {dtype}".format(
51
+ fn_name=fn_name,
52
+ d="complex" if utils.is_complex_dtype(x_dtype) else "real",
53
+ dtype=dtype,
54
+ ),
55
+ )
56
+ torch._check(
57
+ utils.get_higher_dtype(dtype, x_dtype) == dtype,
58
+ lambda: f"{fn_name}: the dtype of the input ({x_dtype}) should be convertible "
59
+ "without narrowing to the specified dtype ({dtype})",
60
+ )
61
+
62
+
63
+ import operator
64
+
65
+ # Utilities should come BEFORE this import
66
+ from torch._decomp import register_decomposition
67
+ from torch._decomp.decompositions import pw_cast_for_opmath
68
+
69
+
70
+ @register_decomposition(torch._ops.ops.aten.linalg_cross)
71
+ @out_wrapper()
72
+ @pw_cast_for_opmath
73
+ def cross(a: Tensor, b: Tensor, dim: int = -1):
74
+ torch._check(
75
+ a.ndim == b.ndim,
76
+ lambda: "linalg.cross: inputs must have the same number of dimensions.",
77
+ )
78
+ torch._check(
79
+ a.size(dim) == 3 and b.size(dim) == 3,
80
+ lambda: f"linalg.cross: inputs dim {dim} must have length 3, got {a.size(dim)} and {b.size(dim)}",
81
+ )
82
+ a, b = torch.broadcast_tensors(a, b)
83
+ dim = utils.canonicalize_dim(a.ndim, dim)
84
+ idx = torch.arange(3, device=a.device)
85
+ return a.index_select(dim, (idx + 1) % 3) * b.index_select(
86
+ dim, (idx + 2) % 3
87
+ ) - a.index_select(dim, (idx + 2) % 3) * b.index_select(dim, (idx + 1) % 3)
88
+
89
+
90
+ def diagonal(
91
+ input: TensorLikeType,
92
+ *,
93
+ offset: int = 0,
94
+ dim1: int = -2,
95
+ dim2: int = -1,
96
+ ) -> TensorLikeType:
97
+ return torch.diagonal(input, offset=offset, dim1=dim1, dim2=dim2)
98
+
99
+
100
+ def _check_vector_norm_args(
101
+ x: TensorLikeType, ord: Union[float, int] = 2, dim: Optional[DimsType] = None
102
+ ):
103
+ from torch.fx.experimental.symbolic_shapes import sym_or
104
+
105
+ if not (ord < 0.0 or ord == float("inf")):
106
+ return
107
+
108
+ torch._check(
109
+ sym_or(
110
+ x.numel() != 0,
111
+ not isinstance(dim, IntLike) and dim is not None and len(dim) != 0,
112
+ ),
113
+ "linalg.vector_norm cannot compute the {ord} norm on an empty tensor "
114
+ "because the operation does not have an identity",
115
+ )
116
+
117
+ shape = x.shape
118
+ if dim is not None and not isinstance(dim, IntLike):
119
+ for d in dim:
120
+ torch._check(
121
+ sym_or(x.numel() != 0, d < len(shape) and d >= 0 and shape[d] != 0),
122
+ "linalg.vector_norm cannot compute the {ord} norm on the "
123
+ f"dimension {d} because this dimension is empty and the "
124
+ "operation does not have an identity",
125
+ )
126
+
127
+
128
+ @register_decomposition(torch._ops.ops.aten.linalg_vector_norm)
129
+ @out_wrapper(exact_dtype=True)
130
+ def vector_norm(
131
+ x: TensorLikeType,
132
+ ord: Union[float, int] = 2,
133
+ dim: Optional[DimsType] = None,
134
+ keepdim: bool = False,
135
+ *,
136
+ dtype: Optional[torch.dtype] = None,
137
+ ) -> Tensor:
138
+ from torch.fx.experimental.symbolic_shapes import guard_or_false
139
+
140
+ check_fp_or_complex(x.dtype, "linalg.vector_norm")
141
+
142
+ if isinstance(dim, Dim):
143
+ dim = [dim] # type: ignore[assignment]
144
+
145
+ _check_vector_norm_args(x, ord, dim)
146
+
147
+ _check_norm_dtype(dtype, x.dtype, "linalg.vector_norm")
148
+
149
+ computation_dtype, result_dtype = utils.reduction_dtypes(
150
+ x, utils.REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, dtype
151
+ )
152
+
153
+ to_result_dtype = partial(_maybe_convert_to_dtype, dtype=result_dtype)
154
+
155
+ # Implementation
156
+ if ord == 0.0:
157
+ return torch.sum(torch.ne(x, 0.0), dim=dim, keepdim=keepdim, dtype=result_dtype)
158
+ elif ord == float("inf"):
159
+ return to_result_dtype(torch.amax(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type]
160
+ elif ord == float("-inf"):
161
+ return to_result_dtype(torch.amin(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type]
162
+ else:
163
+ # From here on the computation dtype is important as the reduction is non-trivial
164
+ x = _maybe_convert_to_dtype(x, computation_dtype) # type: ignore[assignment]
165
+ reduce_sum = partial(torch.sum, dim=dim, keepdim=keepdim)
166
+
167
+ is_ord_even = ord % 2 == 0 if isinstance(ord, IntLike) else ord % 2.0 == 0.0
168
+ if dim == []:
169
+ dim = None
170
+
171
+ if (dim is None and x.numel() == 1) or (
172
+ dim is not None
173
+ and (x.ndim > 0 and all(guard_or_false(x.shape[d] == 1) for d in dim))
174
+ ):
175
+ if x.ndim > 64:
176
+ raise RuntimeError(
177
+ f"Received a tensor with {x.ndim} dimensions, but only tensors with up to 64 dims are supported!"
178
+ )
179
+ x = torch.abs(x)
180
+ if keepdim or x.ndim == 0:
181
+ return to_result_dtype(x).contiguous()
182
+ elif dim is None:
183
+ return to_result_dtype(x).flatten()[0]
184
+ else:
185
+ new_shape = [s for d, s in enumerate(x.shape) if d not in dim]
186
+ return to_result_dtype(x.view(new_shape)).contiguous()
187
+
188
+ if not (is_ord_even and utils.is_float_dtype(x.dtype)):
189
+ x = torch.abs(x)
190
+ return to_result_dtype(torch.pow(reduce_sum(torch.pow(x, ord)), 1.0 / ord)) # type: ignore[return-value]
191
+
192
+
193
+ def _backshift_permutation(dim0, dim1, ndim):
194
+ # Auxiliary function for matrix_norm
195
+ # Computes the permutation that moves the two given dimensions to the back
196
+ ret = [i for i in range(ndim) if i != dim0 and i != dim1]
197
+ ret.extend((dim0, dim1))
198
+ return ret
199
+
200
+
201
+ def _inverse_permutation(perm):
202
+ # Given a permutation, returns its inverse. It's equivalent to argsort on an array
203
+ return [i for i, j in sorted(enumerate(perm), key=operator.itemgetter(1))]
204
+
205
+
206
+ # CompositeImplicitAutograd
207
+ @out_wrapper(exact_dtype=True)
208
+ def matrix_norm(
209
+ A: TensorLikeType,
210
+ ord: Union[float, str] = "fro",
211
+ dim: DimsType = (-2, -1),
212
+ keepdim: bool = False,
213
+ *,
214
+ dtype: Optional[torch.dtype] = None,
215
+ ) -> TensorLikeType:
216
+ # shape
217
+ check_is_matrix(A, "linalg.matrix_norm")
218
+ # dim
219
+ dim = utils.canonicalize_dims(A.ndim, dim)
220
+ if isinstance(dim, Dim):
221
+ dim = (dim,) # type: ignore[assignment]
222
+ torch._check(
223
+ len(dim) == 2, lambda: "linalg.matrix_norm: dim must be a 2-tuple. Got {dim}"
224
+ )
225
+ torch._check(
226
+ dim[0] != dim[1],
227
+ lambda: "linalg.matrix_norm: dims must be different. Got ({dim[0]}, {dim[1]})",
228
+ )
229
+ # dtype arg
230
+ _check_norm_dtype(dtype, A.dtype, "linalg.matrix_norm")
231
+
232
+ if isinstance(ord, str):
233
+ # ord
234
+ torch._check(
235
+ ord in ("fro", "nuc"),
236
+ lambda: "linalg.matrix_norm: Order {ord} not supported.",
237
+ )
238
+ # dtype
239
+ check_fp_or_complex(
240
+ A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != "nuc"
241
+ )
242
+
243
+ if ord == "fro":
244
+ return vector_norm(A, 2, dim, keepdim, dtype=dtype)
245
+ else: # ord == "nuc"
246
+ if dtype is not None:
247
+ A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
248
+ perm = _backshift_permutation(dim[0], dim[1], A.ndim)
249
+ result = torch.sum(svdvals(prims.transpose(A, perm)), -1, keepdim)
250
+ if keepdim:
251
+ inv_perm = _inverse_permutation(perm)
252
+ result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
253
+ return result
254
+ else:
255
+ # ord
256
+ abs_ord = abs(ord)
257
+ torch._check(
258
+ abs_ord in (2, 1, float("inf")),
259
+ lambda: "linalg.matrix_norm: Order {ord} not supported.",
260
+ )
261
+ # dtype
262
+ check_fp_or_complex(
263
+ A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != 2
264
+ )
265
+
266
+ max_min = partial(torch.amax if ord > 0.0 else torch.amin, keepdim=keepdim)
267
+
268
+ if abs_ord == 2.0:
269
+ if dtype is not None:
270
+ A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
271
+ perm = _backshift_permutation(dim[0], dim[1], A.ndim)
272
+ result = max_min(svdvals(prims.transpose(A, perm)), dim=-1)
273
+ if keepdim:
274
+ inv_perm = _inverse_permutation(perm)
275
+ result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
276
+ return result
277
+ else: # 1, -1, inf, -inf
278
+ dim0, dim1 = dim
279
+ if abs_ord == float("inf"):
280
+ dim0, dim1 = dim1, dim0
281
+ if not keepdim and (dim0 < dim1):
282
+ dim1 -= 1
283
+ return max_min(
284
+ vector_norm(A, 1.0, dim=dim0, keepdim=keepdim, dtype=dtype), dim1
285
+ )
286
+
287
+
288
+ # CompositeImplicitAutograd
289
+ @out_wrapper(exact_dtype=True)
290
+ def norm(
291
+ A: TensorLikeType,
292
+ ord: Optional[Union[float, str]] = None,
293
+ dim: Optional[DimsType] = None,
294
+ keepdim: bool = False,
295
+ *,
296
+ dtype: Optional[torch.dtype] = None,
297
+ ) -> TensorLikeType:
298
+ if dim is not None:
299
+ if isinstance(dim, Dim):
300
+ dim = (dim,) # type: ignore[assignment]
301
+ torch._check(
302
+ len(dim) in (1, 2),
303
+ lambda: "linalg.norm: If dim is specified, it must be of length 1 or 2. Got {dim}",
304
+ )
305
+ elif ord is not None:
306
+ torch._check(
307
+ A.ndim in (1, 2),
308
+ lambda: "linalg.norm: If dim is not specified but ord is, the input must be 1D or 2D. Got {A.ndim}D",
309
+ )
310
+
311
+ if ord is not None and (
312
+ (dim is not None and len(dim) == 2) or (dim is None and A.ndim == 2)
313
+ ):
314
+ if dim is None:
315
+ dim = (0, 1)
316
+ return matrix_norm(A, ord, dim, keepdim, dtype=dtype)
317
+ else:
318
+ if ord is None:
319
+ ord = 2.0
320
+ return vector_norm(A, ord, dim, keepdim, dtype=dtype) # type: ignore[arg-type]
321
+
322
+
323
+ # CompositeImplicitAutograd
324
+ @out_wrapper("U", "S", "Vh", exact_dtype=True)
325
+ def svd(A: TensorLikeType, full_matrices: bool = True) -> tuple[Tensor, Tensor, Tensor]:
326
+ return prims.svd(A, full_matrices=full_matrices)
327
+
328
+
329
+ # CompositeImplicitAutograd
330
+ @out_wrapper(exact_dtype=True)
331
+ def svdvals(A: TensorLikeType) -> Tensor:
332
+ return svd(A, full_matrices=False)[1]
333
+
334
+
335
+ # CompositeImplicitAutograd
336
+ @out_wrapper()
337
+ @elementwise_type_promotion_wrapper(
338
+ type_promoting_args=("x", "y"),
339
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
340
+ )
341
+ def vecdot(x: Tensor, y: Tensor, dim: int = -1) -> Tensor:
342
+ check_fp_or_complex(x.dtype, "linalg.vecdot")
343
+ return (x.conj() * y).sum(dim=dim)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (9.97 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __all__: list[str] = []
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (285 Bytes). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py ADDED
@@ -0,0 +1,1289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import math
4
+ from functools import wraps
5
+ from typing import Callable, Optional, TypeVar, Union
6
+ from typing_extensions import Concatenate, ParamSpec
7
+
8
+ import torch
9
+ import torch._prims as prims
10
+ import torch._prims_common as utils
11
+ import torch._refs as refs
12
+ from torch._decomp import register_decomposition
13
+ from torch._prims_common import (
14
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
15
+ NumberType,
16
+ ShapeType,
17
+ TensorLike,
18
+ TensorLikeType,
19
+ )
20
+ from torch._prims_common.wrappers import (
21
+ elementwise_type_promotion_wrapper,
22
+ elementwise_unary_scalar_wrapper,
23
+ out_wrapper,
24
+ )
25
+ from torch._refs import _make_inplace
26
+
27
+
28
+ __all__ = [
29
+ "alpha_dropout",
30
+ "celu",
31
+ "celu_",
32
+ "channel_shuffle",
33
+ "dropout",
34
+ "elu",
35
+ "elu_",
36
+ "gelu",
37
+ "glu",
38
+ "group_norm",
39
+ "hardshrink",
40
+ "hardtanh",
41
+ "hinge_embedding_loss",
42
+ "huber_loss",
43
+ "l1_loss",
44
+ "layer_norm",
45
+ "leaky_relu",
46
+ "log_softmax",
47
+ "margin_ranking_loss",
48
+ "mish",
49
+ "mish_",
50
+ "mse_loss",
51
+ "nll_loss",
52
+ "pairwise_distance",
53
+ "pdist",
54
+ "poisson_nll_loss",
55
+ "prelu",
56
+ "relu",
57
+ "relu6",
58
+ "selu",
59
+ "selu_",
60
+ "smooth_l1_loss",
61
+ "softmax",
62
+ "softmin",
63
+ "softplus",
64
+ "softshrink",
65
+ "tanhshrink",
66
+ "threshold",
67
+ "threshold_",
68
+ "triplet_margin_loss",
69
+ ]
70
+
71
+ _T = TypeVar("_T")
72
+ _P = ParamSpec("_P")
73
+
74
+ Tensor = torch.Tensor
75
+ aten = torch._ops.ops.aten
76
+ DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined]
77
+
78
+
79
+ def _dropout_helper(
80
+ self: TensorLikeType,
81
+ val: float,
82
+ ) -> TensorLikeType:
83
+ """
84
+ Helper function for all dropout-type operators. During training,
85
+ some of the elements of the input tensor are randomly masked.
86
+
87
+ Returns the masked tensor of the boolean values.
88
+
89
+ """
90
+
91
+ return (
92
+ refs._uniform_helper(
93
+ self.shape, low=0.0, high=1.0, dtype=torch.float32, device=self.device
94
+ )
95
+ < val
96
+ )
97
+
98
+
99
+ @register_decomposition(aten.alpha_dropout)
100
+ def alpha_dropout(
101
+ self: TensorLikeType, p: float = 0.5, training: bool = False, inplace: bool = False
102
+ ) -> TensorLikeType:
103
+ if inplace:
104
+ raise NotImplementedError
105
+
106
+ if not training:
107
+ return self
108
+
109
+ torch._check(
110
+ p <= 1 and p >= 0,
111
+ lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
112
+ )
113
+
114
+ if p == 1:
115
+ return torch.zeros_like(self)
116
+
117
+ if p == 0:
118
+ return self
119
+
120
+ dropout_mask = _dropout_helper(self, 1 - p)
121
+
122
+ # From paper: Self-Normalizing Neural Networks (https://arxiv.org/pdf/1706.02515.pdf)
123
+ # alpha = - SELU.alpha * SELU.scale, here
124
+ # SELU.alpha = 1.6732632423543772848170429916717 and
125
+ # SELU.scale = 1.0507009873554804934193349852946
126
+ alpha = -1.7580993408473766
127
+
128
+ a = 1.0 / math.sqrt((alpha * alpha * p + 1) * (1 - p))
129
+ b = torch.logical_not(dropout_mask)
130
+ b = b * (alpha * a) + alpha * a * p
131
+ dropout_mask = a * dropout_mask
132
+
133
+ return self * dropout_mask + b
134
+
135
+
136
+ def _inplace_wrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]:
137
+ """
138
+ Given a nn.functional non-linearity, implements its `inplace: bool` argument
139
+ """
140
+
141
+ # nb. We use the name of the first argument used in the unary references
142
+ @wraps(fn)
143
+ def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T:
144
+ a = args[0]
145
+ if "inplace" not in kwargs:
146
+ kwargs["inplace"] = False
147
+ if kwargs["inplace"]:
148
+ torch._check(
149
+ "out" not in kwargs,
150
+ lambda: "Cannot set inplace=True and pass out= at the same time",
151
+ )
152
+ kwargs["inplace"] = False
153
+ kwargs["out"] = a
154
+ return fn(*args, **kwargs)
155
+ else:
156
+ return fn(*args, **kwargs)
157
+
158
+ return _fn
159
+
160
+
161
+ # celu is implemented specially because it has an alpha argument
162
+ # celu is very similar to elu
163
+ @register_decomposition(aten.celu)
164
+ @_inplace_wrapper
165
+ @out_wrapper()
166
+ @elementwise_type_promotion_wrapper(
167
+ type_promoting_args=("a",),
168
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
169
+ )
170
+ def celu(
171
+ a: TensorLikeType, alpha: Optional[NumberType] = None, inplace: bool = False
172
+ ) -> TensorLikeType:
173
+ """
174
+ Reference implementation of torch.nn.functional.celu
175
+ """
176
+
177
+ if inplace:
178
+ raise NotImplementedError
179
+
180
+ rhs: TensorLikeType
181
+ if alpha is not None:
182
+ python_type = utils.dtype_to_type(a.dtype)
183
+ if not utils.is_weakly_lesser_type(type(alpha), python_type):
184
+ msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!"
185
+ raise ValueError(msg)
186
+ rhs = alpha * torch.expm1(torch.true_divide(a, alpha)) # type: ignore[arg-type]
187
+ else:
188
+ rhs = torch.expm1(a)
189
+
190
+ return torch.where(a > 0, a, rhs)
191
+
192
+
193
+ @_inplace_wrapper
194
+ @out_wrapper()
195
+ def dropout(
196
+ a: TensorLikeType, p: float = 0.5, training: bool = True, inplace: bool = False
197
+ ) -> TensorLikeType:
198
+ if inplace:
199
+ raise NotImplementedError
200
+
201
+ if not training:
202
+ return a
203
+
204
+ torch._check(
205
+ p <= 1 and p >= 0,
206
+ lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
207
+ )
208
+
209
+ if p == 1:
210
+ return torch.zeros_like(a)
211
+
212
+ if p == 0:
213
+ return a
214
+
215
+ scale = 1 / (1 - p)
216
+ dropout_mask = _dropout_helper(a, 1 - p)
217
+
218
+ return a * dropout_mask * scale
219
+
220
+
221
+ @register_decomposition(aten.elu)
222
+ @_inplace_wrapper
223
+ @out_wrapper()
224
+ @elementwise_type_promotion_wrapper(
225
+ type_promoting_args=("a",),
226
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
227
+ )
228
+ def elu(
229
+ a: TensorLikeType,
230
+ alpha: NumberType = 1.0,
231
+ scale: NumberType = 1.0,
232
+ input_scale: NumberType = 1.0,
233
+ inplace: bool = False,
234
+ ) -> TensorLikeType:
235
+ """
236
+ Reference implementation of torch.nn.functional.elu
237
+ """
238
+ if inplace:
239
+ raise NotImplementedError
240
+
241
+ # nb. This should be factored out into a can_cast aux function
242
+ python_type = utils.dtype_to_type(a.dtype)
243
+ torch._check(
244
+ utils.is_weakly_lesser_type(type(input_scale), python_type),
245
+ lambda: f"input_scale argument of type {type(input_scale)} cannot be safely cast to type {python_type}!",
246
+ )
247
+ torch._check(
248
+ utils.is_weakly_lesser_type(type(scale), python_type),
249
+ lambda: f"scale argument of type {type(scale)} cannot be safely cast to type {python_type}!",
250
+ )
251
+ torch._check(
252
+ utils.is_weakly_lesser_type(type(alpha), python_type),
253
+ lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!",
254
+ )
255
+
256
+ return torch.where(a > 0, scale * a, (alpha * scale) * torch.expm1(a * input_scale))
257
+
258
+
259
+ @register_decomposition(aten.relu)
260
+ @_inplace_wrapper
261
+ @out_wrapper()
262
+ @elementwise_type_promotion_wrapper(
263
+ type_promoting_args=("a",),
264
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
265
+ )
266
+ def relu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
267
+ """
268
+ Reference implementation of torch.nn.functional.relu
269
+ """
270
+
271
+ if inplace:
272
+ raise NotImplementedError
273
+
274
+ return torch.where(torch.le(a, 0), 0, a)
275
+
276
+
277
+ @register_decomposition(aten.channel_shuffle)
278
+ @out_wrapper()
279
+ def channel_shuffle(input: TensorLikeType, groups: int) -> TensorLikeType:
280
+ """
281
+ Reference implementation of :func:`torch.nn.functional.channel_shuffle`.
282
+ """
283
+ from torch._meta_registrations import device_hint
284
+
285
+ torch._check(
286
+ input.dim() > 2,
287
+ lambda: f"channel_shuffle expects input with > 2 dims, but got input with sizes {list(input.size())}",
288
+ )
289
+ c = input.shape[1]
290
+ torch._check(
291
+ groups > 0,
292
+ lambda: f"Number of groups to divide channels in must be positive. Value of groups:{groups}",
293
+ )
294
+ torch._check(
295
+ (c % groups) == 0,
296
+ lambda: f"Number of channels must be divisible by groups. Got {c} channels and {groups} groups.",
297
+ )
298
+ n = input.shape[0]
299
+ cg = c // groups
300
+ dhw = input.shape[2:]
301
+
302
+ if input.numel() == 0 or (
303
+ device_hint(input) == "cuda" and (groups == 1 or groups == c)
304
+ ):
305
+ return input.view(input.shape)
306
+
307
+ return (
308
+ input.reshape(n, groups, cg, *dhw)
309
+ .transpose(1, 2)
310
+ .reshape(input.shape)
311
+ .contiguous()
312
+ )
313
+
314
+
315
+ def group_norm(
316
+ input: Tensor,
317
+ num_groups: int,
318
+ weight: Optional[Tensor] = None,
319
+ bias: Optional[Tensor] = None,
320
+ eps: float = 1e-5,
321
+ ) -> Tensor:
322
+ """
323
+ Reference implementation of :func:`torch.nn.functional.group_norm`.
324
+ """
325
+ torch._check(
326
+ input.ndim >= 2,
327
+ lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}",
328
+ )
329
+
330
+ batch_size = input.shape[0]
331
+ num_channels = input.shape[1]
332
+ torch._check(
333
+ num_channels % num_groups == 0,
334
+ lambda: "Expected number of channels in input to be divisible by num_groups, "
335
+ + f"but got input of shape {input.shape} and num_groups = {num_groups}",
336
+ )
337
+
338
+ # input shape is (N, C, *), so we flatten all inner dimensions except (N, C)
339
+ flattened_inner_size = 1
340
+ for dim_length in input.shape[2:]:
341
+ flattened_inner_size *= dim_length
342
+
343
+ return torch.native_group_norm(
344
+ input,
345
+ weight,
346
+ bias,
347
+ batch_size,
348
+ num_channels,
349
+ flattened_inner_size,
350
+ num_groups,
351
+ eps,
352
+ )[0]
353
+
354
+
355
+ def layer_norm(
356
+ input: Tensor,
357
+ normalized_shape: ShapeType,
358
+ weight: Optional[Tensor] = None,
359
+ bias: Optional[Tensor] = None,
360
+ eps: float = 1e-5,
361
+ ) -> Tensor:
362
+ """
363
+ Reference implementation of :func:`torch.nn.functional.layer_norm`.
364
+ """
365
+ return torch.native_layer_norm(input, normalized_shape, weight, bias, eps)[0]
366
+
367
+
368
+ @register_decomposition(aten.leaky_relu)
369
+ @_inplace_wrapper
370
+ @out_wrapper()
371
+ @elementwise_type_promotion_wrapper(
372
+ type_promoting_args=("a",),
373
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
374
+ )
375
+ def leaky_relu(
376
+ a: TensorLikeType, negative_slope: float = 0.01, inplace: bool = False
377
+ ) -> TensorLikeType:
378
+ """
379
+ Reference implementation of torch.nn.functional.leaky_relu
380
+ """
381
+
382
+ if inplace:
383
+ raise NotImplementedError
384
+
385
+ python_type = utils.dtype_to_type(a.dtype)
386
+ if not utils.is_weakly_lesser_type(type(negative_slope), python_type):
387
+ msg = f"negative_slope argument of type {type(negative_slope)} cannot be safely cast to type {python_type}!"
388
+ raise ValueError(msg)
389
+ return torch.where(torch.gt(a, 0), a, torch.mul(a, negative_slope))
390
+
391
+
392
+ @register_decomposition(aten.mish)
393
+ @_inplace_wrapper
394
+ @out_wrapper()
395
+ @elementwise_type_promotion_wrapper(
396
+ type_promoting_args=("a",),
397
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
398
+ )
399
+ def mish(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
400
+ """
401
+ Reference implementation of torch.nn.functional.mish
402
+ """
403
+
404
+ if inplace:
405
+ raise NotImplementedError
406
+ return a * torch.tanh(torch.nn.functional.softplus(a))
407
+
408
+
409
+ @register_decomposition(aten.selu)
410
+ @_inplace_wrapper
411
+ @out_wrapper()
412
+ @elementwise_type_promotion_wrapper(
413
+ type_promoting_args=("a",),
414
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
415
+ )
416
+ def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
417
+ """
418
+ Reference implementation of torch.nn.functional.selu
419
+ """
420
+ if inplace:
421
+ raise NotImplementedError
422
+
423
+ alpha = 1.6732632423543772848170429916717
424
+ scale = 1.0507009873554804934193349852946
425
+
426
+ rhs = alpha * torch.expm1(a)
427
+
428
+ return scale * torch.where(a > 0, a, rhs)
429
+
430
+
431
+ # Forwarding alias: the functional variant doesn't support the out kwarg
432
+ # CompositeImplicitAutograd - don't register decomp
433
+ def softmax(
434
+ a: TensorLikeType,
435
+ dim: Optional[int] = None,
436
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
437
+ dtype: Optional[torch.dtype] = None,
438
+ ) -> TensorLikeType:
439
+ # The error is for compat with regular PyTorch, which has this behavior
440
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
441
+ # behavior because it requires explicit opt in. This error is to inform
442
+ # users how to update their calls.
443
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
444
+ return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
445
+
446
+
447
+ # CompositeImplicitAutograd - don't register decomp
448
+ def softmin(
449
+ a: TensorLikeType,
450
+ dim: Optional[int] = None,
451
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
452
+ dtype: Optional[torch.dtype] = None,
453
+ ) -> TensorLikeType:
454
+ # The error is for compat with regular PyTorch, which has this behavior
455
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
456
+ # behavior because it requires explicit opt in. This error is to inform
457
+ # users how to update their calls.
458
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
459
+ return torch.softmax(a=-a, dim=dim, dtype=dtype) # type: ignore[call-overload]
460
+
461
+
462
+ # softplus is implemented specially because it has beta and threshold arguments
463
+ @register_decomposition(aten.softplus)
464
+ @_inplace_wrapper
465
+ @out_wrapper()
466
+ @elementwise_type_promotion_wrapper(
467
+ type_promoting_args=("a",),
468
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
469
+ )
470
+ def softplus(
471
+ a: TensorLikeType,
472
+ beta: Optional[NumberType] = None,
473
+ threshold: NumberType = 20,
474
+ inplace: bool = False,
475
+ ) -> TensorLikeType:
476
+ """
477
+ Reference implementation of torch.nn.functional.softplus
478
+ """
479
+
480
+ if inplace:
481
+ raise NotImplementedError
482
+
483
+ rhs: TensorLikeType
484
+ if beta is not None:
485
+ python_type = utils.dtype_to_type(a.dtype)
486
+ if not utils.is_weakly_lesser_type(type(beta), python_type):
487
+ msg = f"beta argument of type {type(beta)} cannot be safely cast to type {python_type}!"
488
+ raise ValueError(msg)
489
+ scaled_input = a * beta
490
+ rhs = torch.true_divide(torch.log1p(torch.exp(scaled_input)), beta) # type: ignore[arg-type]
491
+
492
+ else:
493
+ scaled_input = a
494
+ rhs = torch.log1p(torch.exp(scaled_input))
495
+
496
+ return torch.where(scaled_input > threshold, a, rhs)
497
+
498
+
499
+ @aten.hardshrink.default.py_impl(DispatchKey.Autograd)
500
+ @register_decomposition(aten.hardshrink)
501
+ @out_wrapper()
502
+ def hardshrink(a: TensorLikeType, lambd: float = 0.5):
503
+ # Formula for reference,
504
+ # hardshrink(x) = x if x > lambd
505
+ # = x if x < -lambd
506
+ # = 0 otherwise
507
+ return torch.where(torch.abs(a) <= lambd, 0, a)
508
+
509
+
510
+ @aten.softshrink.default.py_impl(DispatchKey.Autograd)
511
+ @register_decomposition(aten.softshrink)
512
+ @out_wrapper()
513
+ def softshrink(a: TensorLikeType, lambd: float = 0.5):
514
+ # Formula for reference,
515
+ # softshrink(x) = x - lambd if x > lambd
516
+ # = x + lambd if x < -lambd
517
+ # = 0 otherwise
518
+ torch._check(
519
+ lambd >= 0,
520
+ lambda: f"lambda must be greater or equal to 0, but found to be {lambd}",
521
+ )
522
+ # We implement this in one torch.where to generate better code in the backward
523
+ # see https://github.com/pytorch/pytorch/pull/107052#discussion_r1293748211
524
+ # We multiply by 0 for dealing with nans
525
+ return torch.where(torch.abs(a) > lambd, a - torch.sign(a) * lambd, a * 0)
526
+
527
+
528
+ # Losses
529
+ def _reduction_int_to_str(reduction: int) -> str:
530
+ from torch._decomp.decompositions import Reduction
531
+
532
+ if reduction == Reduction.NONE.value:
533
+ return "none"
534
+ elif reduction == Reduction.MEAN.value:
535
+ return "mean"
536
+ elif reduction == Reduction.SUM.value:
537
+ return "sum"
538
+ else:
539
+ raise ValueError(f"{reduction} is not a valid value for reduction")
540
+
541
+
542
+ def _apply_loss_reduction(loss: TensorLikeType, reduction: str) -> TensorLikeType:
543
+ if reduction == "sum":
544
+ return torch.sum(loss)
545
+ elif reduction == "mean":
546
+ return torch.mean(loss)
547
+ else: # reduction == "none"
548
+ return loss
549
+
550
+
551
+ def _check_reduction_value(reduction: str):
552
+ if reduction not in ("mean", "sum", "none"):
553
+ raise ValueError(f"{reduction} is not a valid value for reduction")
554
+
555
+
556
+ # This helper function maps depreciated arguments, "size_average" and "reduce"
557
+ # to their corresponding "reduction" string argument
558
+ def _get_string_reduction_arg(
559
+ *, size_average: Optional[bool], reduce: Optional[bool]
560
+ ) -> str:
561
+ if size_average is None:
562
+ size_average = True
563
+ if reduce is None:
564
+ reduce = True
565
+ if size_average and reduce:
566
+ ret = "mean"
567
+ elif reduce:
568
+ ret = "sum"
569
+ else:
570
+ ret = "none"
571
+ return ret
572
+
573
+
574
+ # CompositeImplicitAutograd - don't register decomp
575
+ @elementwise_type_promotion_wrapper(
576
+ type_promoting_args=("input", "target"),
577
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
578
+ )
579
+ def l1_loss(
580
+ input: TensorLikeType,
581
+ target: TensorLikeType,
582
+ size_average: Optional[bool] = None,
583
+ reduce: Optional[bool] = None,
584
+ reduction: str = "mean",
585
+ ) -> TensorLikeType:
586
+ """
587
+ Reference implementation of torch.nn.functional.l1_loss
588
+ """
589
+ if size_average is not None or reduce is not None:
590
+ # TODO: Raise exception instead of converting value. This is only for
591
+ # primTorch since it can drop support for deprecated arguments.
592
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
593
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
594
+ _check_reduction_value(reduction)
595
+ loss = torch.abs(input - target)
596
+ return _apply_loss_reduction(loss, reduction)
597
+
598
+
599
+ @elementwise_type_promotion_wrapper(
600
+ type_promoting_args=("input", "target"),
601
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
602
+ )
603
+ def smooth_l1_loss(
604
+ input: TensorLikeType,
605
+ target: TensorLikeType,
606
+ size_average: Optional[bool] = None,
607
+ reduce: Optional[bool] = None,
608
+ reduction: str = "mean",
609
+ beta: float = 1.0,
610
+ ) -> TensorLikeType:
611
+ """
612
+ Reference implementation of torch.nn.functional.smooth_l1_loss
613
+ """
614
+ if size_average is not None or reduce is not None:
615
+ # TODO: Raise exception instead of converting value. This is only for
616
+ # primTorch since it can drop support for deprecated arguments.
617
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
618
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
619
+ _check_reduction_value(reduction)
620
+
621
+ if beta == 0.0:
622
+ return torch.nn.functional.l1_loss(
623
+ input, target, size_average=size_average, reduce=reduce, reduction=reduction
624
+ )
625
+ else:
626
+ loss = torch.abs(input - target)
627
+ loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta)
628
+ return _apply_loss_reduction(loss, reduction)
629
+
630
+
631
+ # Forwarding alias: the functional variant doesn't support the out kwarg
632
+ # CompositeImplicitAutograd - don't register decomp
633
+ def log_softmax(
634
+ a: TensorLikeType,
635
+ dim: Optional[int] = None,
636
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
637
+ dtype: Optional[torch.dtype] = None,
638
+ ) -> TensorLikeType:
639
+ # The error is for compat with regular PyTorch, which has this behavior
640
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
641
+ # behavior because it requires explicit opt in. This error is to inform
642
+ # users how to update their calls.
643
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
644
+ return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
645
+
646
+
647
+ @register_decomposition(aten.margin_ranking_loss)
648
+ def margin_ranking_loss(
649
+ input1: TensorLikeType,
650
+ input2: TensorLikeType,
651
+ target: TensorLikeType,
652
+ margin: float = 0.0,
653
+ reduction: str = "mean",
654
+ ) -> TensorLikeType:
655
+ # loss_without_reduction = max(0, -target * (input1 - input2) + margin)
656
+ if input1.ndim != input2.ndim or input1.ndim != target.ndim:
657
+ raise RuntimeError(
658
+ "margin_ranking_loss : All input tensors should have same dimension but got sizes: "
659
+ f"input1: {input1.shape}, input2: {input2.shape}, target: {target.shape} "
660
+ )
661
+ _check_reduction_value(reduction)
662
+ loss = torch.clamp_min(-target * (input1 - input2) + margin, 0)
663
+ return _apply_loss_reduction(loss, reduction)
664
+
665
+
666
+ @elementwise_type_promotion_wrapper(
667
+ type_promoting_args=("input", "target"),
668
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
669
+ )
670
+ def mse_loss(
671
+ input: TensorLikeType,
672
+ target: TensorLikeType,
673
+ size_average: Optional[bool] = None,
674
+ reduce: Optional[bool] = None,
675
+ reduction: str = "mean",
676
+ ) -> TensorLikeType:
677
+ if size_average is not None or reduce is not None:
678
+ # TODO: Raise exception instead of converting value. This is only for
679
+ # primTorch since it can drop support for deprecated arguments.
680
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
681
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
682
+ _check_reduction_value(reduction)
683
+ loss = torch.pow(input - target, 2)
684
+ return _apply_loss_reduction(loss, reduction)
685
+
686
+
687
+ @register_decomposition(aten.hinge_embedding_loss)
688
+ def hinge_embedding_loss(
689
+ input: TensorLikeType,
690
+ target: TensorLikeType,
691
+ margin: float = 1.0,
692
+ reduction: str = "mean",
693
+ ) -> TensorLikeType:
694
+ # loss_without_reduction = input if y == 1
695
+ # = max(0, margin - input) if y == -1
696
+ _check_reduction_value(reduction)
697
+ margin_clamp = torch.clamp_min(margin - input, 0)
698
+ output_margin = torch.where(target != 1, margin_clamp, 0)
699
+ output_self = torch.where(target != -1, input, 0)
700
+ loss = output_margin + output_self
701
+ return _apply_loss_reduction(loss, reduction)
702
+
703
+
704
+ def _nll_loss_nd(
705
+ input: TensorLikeType,
706
+ target: TensorLikeType,
707
+ weight: Optional[TensorLikeType],
708
+ reduction: str,
709
+ ignore_index: int,
710
+ ) -> TensorLikeType:
711
+ torch._check(
712
+ input.ndim > 0 and input.ndim <= 3,
713
+ lambda: f"Expected input dimension to be either [1, 2, 3] but received {input.ndim}.",
714
+ )
715
+
716
+ torch._check(
717
+ (input.ndim == 1) or (input.shape[0] == target.shape[0]),
718
+ lambda: f"Expected input batch size {input.shape[0]} to match target batch size {target.shape[0]}.",
719
+ )
720
+
721
+ _check_reduction_value(reduction)
722
+
723
+ flat_target = torch.flatten(target)
724
+ ignore_classes_mask = torch.eq(flat_target, ignore_index)
725
+
726
+ # TODO: Enable data-dependent checks with debug mode
727
+ # TODO: This check does not work with FakeTensor inputs; See Issue #85834
728
+ # Explicit cast for class_check to bool; See Issue #78071
729
+ """
730
+ from torch._subclasses.fake_tensor import FakeTensor
731
+ num_classes = input.shape[1] if input.ndim > 1 else input.shape[0]
732
+ valid_classes_mask = torch.logical_and(
733
+ (flat_target >= 0), (flat_target < num_classes)
734
+ )
735
+ class_check = torch.all(torch.logical_or(ignore_classes_mask, valid_classes_mask))
736
+ torch._check(
737
+ isinstance(target, FakeTensor) or bool(class_check.item()),
738
+ lambda: "A target class is out-of-bounds and not the ignore index.",
739
+ )
740
+ """
741
+
742
+ ignore_class_weight = torch.scalar_tensor(0, dtype=input.dtype, device=input.device)
743
+ class_weight = (
744
+ torch.scalar_tensor(1, dtype=input.dtype, device=input.device)
745
+ if weight is None
746
+ else weight[flat_target]
747
+ )
748
+ current_weight = torch.where(
749
+ ignore_classes_mask,
750
+ ignore_class_weight,
751
+ class_weight,
752
+ )
753
+
754
+ if input.ndim == 1:
755
+ # implicit batch size = 1
756
+ # input (1 batch size, C classes)
757
+ loss = -input[target] * current_weight
758
+ elif input.ndim == 2:
759
+ # input (N batch size, C classes)
760
+ batch_size = input.shape[0]
761
+ loss = -input[torch.arange(batch_size), target] * current_weight
762
+ else:
763
+ # 3D case (N batch size, C classes, K dimensions)
764
+ # input (N batch size, C classes, K)
765
+ batch_size = input.shape[0]
766
+ extent = input.shape[2]
767
+ numel = batch_size * extent
768
+ indices = torch.arange(numel)
769
+ bdx = indices // extent
770
+ kdx = indices % extent
771
+ loss = -input[bdx, flat_target, kdx] * current_weight
772
+ loss = torch.reshape(loss, target.shape)
773
+
774
+ if reduction == "none":
775
+ return loss
776
+ elif reduction == "sum":
777
+ return torch.sum(loss)
778
+ else:
779
+ # calculate weighted mean of the loss function
780
+ return torch.sum(loss) / torch.sum(current_weight)
781
+
782
+
783
+ @register_decomposition(aten.nll_loss)
784
+ @out_wrapper()
785
+ @elementwise_type_promotion_wrapper(
786
+ type_promoting_args=("input",),
787
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
788
+ )
789
+ def nll_loss(
790
+ input: TensorLikeType,
791
+ target: TensorLikeType,
792
+ weight: Optional[TensorLikeType] = None,
793
+ size_average: Optional[bool] = None,
794
+ ignore_index: int = -100,
795
+ reduce: Optional[bool] = None,
796
+ reduction: str = "mean",
797
+ ) -> TensorLikeType:
798
+ """
799
+ Reference implementation of torch.nn.functional.nll_loss
800
+ """
801
+ torch._check(
802
+ input.ndim > 0,
803
+ lambda: f"Expected input tensor to have 1 or more dimensions (got {input.ndim})",
804
+ )
805
+
806
+ # TODO: raise exception instead of converting value
807
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
808
+ # Convert these options for consistency with the eager mode
809
+ if size_average is not None or reduce is not None:
810
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
811
+
812
+ # The expected behavior when the target and input have zero elements:
813
+ # reduction = 'none' --- tensor([])
814
+ # reduction = 'sum' --- tensor(0.)
815
+ # reduction = 'mean' --- tensor(nan)
816
+ # Mean reduction on empty tensors produces NaN. See the discussion in
817
+ # https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162
818
+ if input.numel() == 0 and target.numel() == 0:
819
+ if reduction == "none":
820
+ return torch.zeros_like(target)
821
+ elif reduction == "sum":
822
+ return torch.empty_like(target)
823
+ else:
824
+ return torch.full_like(target, float("nan"))
825
+
826
+ # The _nll_loss_nd helper function handles the most common cases.
827
+ # ndim == 1 (Single Example)
828
+ # => Batch Size: 1, Input: (C), Target: ()
829
+ # ndim == 2 (k = 1)
830
+ # => Batch Size: N, Input: (N, C), Target: (N)
831
+ # ndim == 3 (k > 1)
832
+ # => Batch Size: N, Input: (N, C, K), Target: (N, K)
833
+ if input.ndim <= 3:
834
+ return _nll_loss_nd(input, target, weight, reduction, ignore_index)
835
+
836
+ # For ndim > 3, we reshape the input and target to 3-D case.
837
+ # Input (N batch-size, C classes, k-dimensions)
838
+ # Target (N batch-size, k-dimensions)
839
+ torch._check(
840
+ input.ndim > 0 and target.ndim > 0 and target.shape[1:] == input.shape[2:],
841
+ lambda: (
842
+ "Expected input and target to both have ndim > 0 and "
843
+ "target.shape[1:] == input.shape[2:], but got "
844
+ f"target.shape {target.shape} and input.shape {input.shape}"
845
+ ),
846
+ )
847
+
848
+ batch_size = input.shape[0]
849
+ num_classes = input.shape[1]
850
+ out_size = [batch_size] + list(target.shape[1:])
851
+
852
+ input = torch.reshape(input, [batch_size, num_classes, -1])
853
+ target = torch.reshape(target, [batch_size, -1])
854
+ if reduction != "none":
855
+ return _nll_loss_nd(input, target, weight, reduction, ignore_index)
856
+ else:
857
+ result = _nll_loss_nd(input, target, weight, reduction, ignore_index)
858
+ # reshape flattened inner-dim to original k-dimensions
859
+ return torch.reshape(result, out_size)
860
+
861
+
862
+ # TODO: This ref supports int reduction and out kwarg to be compatible with ATen:
863
+ # https://github.com/pytorch/pytorch/issues/83931
864
+ # TODO: Could be rewritten to support complex:
865
+ # https://github.com/pytorch/pytorch/pull/85041
866
+ @register_decomposition(aten.huber_loss)
867
+ @out_wrapper()
868
+ @elementwise_type_promotion_wrapper(
869
+ type_promoting_args=("input", "target"),
870
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
871
+ )
872
+ def huber_loss(
873
+ input: TensorLikeType,
874
+ target: TensorLikeType,
875
+ reduction: Union[str, int] = "mean",
876
+ delta: float = 1.0,
877
+ ) -> TensorLikeType:
878
+ """
879
+ Reference implementation of torch.nn.functional.huber_loss
880
+ """
881
+ if type(reduction) is int:
882
+ reduction = _reduction_int_to_str(reduction)
883
+ _check_reduction_value(reduction) # type: ignore[arg-type]
884
+ torch._check(
885
+ delta > 0,
886
+ lambda: "huber_loss does not support non-positive values for delta.",
887
+ )
888
+ z = (input - target).abs()
889
+ loss = torch.where(z < delta, 0.5 * z * z, delta * (z - 0.5 * delta))
890
+ return _apply_loss_reduction(loss, reduction) # type: ignore[arg-type]
891
+
892
+
893
+ # tanhshrink does not use _make_elementwise_unary_reference because it does not support out
894
+ @elementwise_unary_scalar_wrapper
895
+ @elementwise_type_promotion_wrapper(
896
+ type_promoting_args=("a",),
897
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
898
+ )
899
+ def tanhshrink(a: TensorLikeType) -> TensorLikeType:
900
+ """
901
+ Reference implementation of torch.nn.functional.tanhshrink
902
+ """
903
+ if not isinstance(a, TensorLike):
904
+ raise RuntimeError(
905
+ "Expected a tensor input for an elementwise unary operation!"
906
+ )
907
+ return a - torch.tanh(a)
908
+
909
+
910
+ @register_decomposition(aten.threshold)
911
+ @_inplace_wrapper
912
+ @out_wrapper()
913
+ @elementwise_type_promotion_wrapper(
914
+ type_promoting_args=("a",),
915
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
916
+ )
917
+ def threshold(
918
+ a: TensorLikeType,
919
+ threshold: NumberType,
920
+ value: Union[bool, int, float],
921
+ inplace: bool = False,
922
+ ) -> TensorLikeType:
923
+ """
924
+ Reference implementation of torch.nn.functional.threshold
925
+ """
926
+
927
+ if inplace:
928
+ raise NotImplementedError
929
+
930
+ return torch.where(a <= threshold, value, a)
931
+
932
+
933
+ # CompositeImplicitAutograd - don't register decomp
934
+ # No elementwise type promotion - core op doesn't explicitly type promote
935
+ def triplet_margin_loss(
936
+ anchor: TensorLikeType,
937
+ positive: TensorLikeType,
938
+ negative: TensorLikeType,
939
+ margin: float = 1.0,
940
+ p: float = 2,
941
+ eps: float = 1e-6,
942
+ swap: bool = False,
943
+ size_average: Optional[bool] = None,
944
+ reduce: Optional[bool] = None,
945
+ reduction: str = "mean",
946
+ ) -> TensorLikeType:
947
+ if size_average is not None or reduce is not None:
948
+ # TODO: Raise exception instead of converting value. This is only for
949
+ # primTorch since it can drop support for deprecated arguments.
950
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
951
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
952
+
953
+ if margin <= 0:
954
+ raise ValueError(f"margin must be greater than 0, got {margin}")
955
+
956
+ # torch.nn.functional.triplet_margin_with_distance_loss has no ref defined
957
+ # since it's a pure Python implementation. Use this helper instead.
958
+ return _triplet_margin_with_distance_loss(
959
+ anchor=anchor,
960
+ positive=positive,
961
+ negative=negative,
962
+ distance_function=lambda x, y: torch.pairwise_distance(x, y, p, eps),
963
+ margin=margin,
964
+ swap=swap,
965
+ reduction=reduction,
966
+ )
967
+
968
+
969
+ # Pure Python impl - don't register decomp and don't add a ref. Defined as a
970
+ # helper here since triplet_margin_loss can be nicely implemented with it.
971
+ def _triplet_margin_with_distance_loss(
972
+ anchor: TensorLikeType,
973
+ positive: TensorLikeType,
974
+ negative: TensorLikeType,
975
+ *,
976
+ distance_function: Optional[
977
+ Callable[[TensorLikeType, TensorLikeType], TensorLikeType]
978
+ ] = None,
979
+ margin: float = 1.0,
980
+ swap: bool = False,
981
+ reduction: str = "mean",
982
+ ) -> TensorLikeType:
983
+ _check_reduction_value(reduction)
984
+
985
+ a_dim = anchor.ndim
986
+ p_dim = positive.ndim
987
+ n_dim = negative.ndim
988
+ torch._check(
989
+ a_dim == p_dim and p_dim == n_dim,
990
+ lambda: (
991
+ f"The anchor, positive, and negative tensors are expected to have "
992
+ f"the same number of dimensions, but got: anchor {a_dim}D, "
993
+ f"positive {p_dim}D, and negative {n_dim}D inputs"
994
+ ),
995
+ )
996
+
997
+ if distance_function is None:
998
+ distance_function = torch.pairwise_distance
999
+
1000
+ dist_pos = distance_function(anchor, positive)
1001
+ dist_neg = distance_function(anchor, negative)
1002
+ # The distance swap is described in the paper "Learning shallow
1003
+ # convolutional feature descriptors with triplet losses" by V. Balntas, E.
1004
+ # Riba et al. If True, and if the positive example is closer to the
1005
+ # negative example than the anchor is, swaps the positive example and the
1006
+ # anchor in the loss computation.
1007
+ if swap:
1008
+ dist_swap = distance_function(positive, negative)
1009
+ dist_neg = torch.minimum(dist_neg, dist_swap)
1010
+ loss = torch.clamp_min(margin + dist_pos - dist_neg, 0)
1011
+ return _apply_loss_reduction(loss, reduction)
1012
+
1013
+
1014
+ @register_decomposition(aten.hardtanh)
1015
+ @_inplace_wrapper
1016
+ @out_wrapper()
1017
+ @elementwise_unary_scalar_wrapper
1018
+ @elementwise_type_promotion_wrapper(
1019
+ type_promoting_args=("a"),
1020
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1021
+ )
1022
+ def hardtanh(
1023
+ a: TensorLikeType,
1024
+ min_val: NumberType = -1,
1025
+ max_val: NumberType = 1,
1026
+ inplace: bool = False,
1027
+ ) -> TensorLikeType:
1028
+ """
1029
+ Reference implementation of torch.nn.functional.hardtanh
1030
+ """
1031
+ if inplace:
1032
+ raise NotImplementedError
1033
+ if utils.is_boolean_dtype(a.dtype):
1034
+ raise RuntimeError("Bool inputs not supported for hardtanh")
1035
+
1036
+ # preserve legacy behavior of boundaries not causing type promotion
1037
+ if utils.is_integer_dtype(a.dtype):
1038
+ min_val = int(min_val) # type: ignore[arg-type]
1039
+ max_val = int(max_val) # type: ignore[arg-type]
1040
+ if not (a.dtype != torch.uint8 or (min_val >= 0 and max_val >= 0)):
1041
+ raise RuntimeError(
1042
+ "Cannot do hardtanh on an unsigned type with negative limits"
1043
+ )
1044
+
1045
+ if min_val > max_val: # type: ignore[operator]
1046
+ raise ValueError("min_val cannot be greater than max_val")
1047
+
1048
+ return torch.clamp(a, min_val, max_val) # type: ignore[arg-type]
1049
+
1050
+
1051
+ @register_decomposition(aten.gelu)
1052
+ @out_wrapper()
1053
+ @elementwise_unary_scalar_wrapper
1054
+ @elementwise_type_promotion_wrapper(
1055
+ type_promoting_args=("a",),
1056
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1057
+ )
1058
+ def gelu(a: TensorLikeType, approximate: str = "none") -> TensorLikeType:
1059
+ """
1060
+ Reference implementation of torch.nn.functional.gelu
1061
+ """
1062
+ if not isinstance(a, TensorLike):
1063
+ raise RuntimeError(
1064
+ "Expected a tensor input for an elementwise unary operation!"
1065
+ )
1066
+ M_SQRT2 = 1.41421356237309504880
1067
+ M_SQRT1_2 = 0.70710678118654752440
1068
+ M_2_SQRTPI = 1.12837916709551257390
1069
+ if approximate == "tanh":
1070
+ kBeta = M_SQRT2 * M_2_SQRTPI * 0.5
1071
+ kKappa = 0.044715
1072
+ a_cube = a * a * a
1073
+ inner = kBeta * (a + kKappa * a_cube)
1074
+ return 0.5 * a * (1 + torch.tanh(inner))
1075
+ elif approximate == "none":
1076
+ kAlpha = M_SQRT1_2
1077
+ return a * 0.5 * (1 + torch.erf(a * kAlpha))
1078
+ else:
1079
+ raise RuntimeError("approximate argument must be either none or tanh.")
1080
+
1081
+
1082
+ # CompositeImplicitAutograd - don't register decomp
1083
+ @elementwise_type_promotion_wrapper(
1084
+ type_promoting_args=("input", "target"),
1085
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
1086
+ )
1087
+ def poisson_nll_loss(
1088
+ input: TensorLikeType,
1089
+ target: TensorLikeType,
1090
+ log_input: bool = True,
1091
+ full: bool = False,
1092
+ size_average: Optional[bool] = None,
1093
+ eps: float = 1e-8,
1094
+ reduce: Optional[bool] = None,
1095
+ reduction: str = "mean",
1096
+ ) -> TensorLikeType:
1097
+ """
1098
+ Reference implementation of torch.nn.functional.poisson_nll_loss
1099
+ """
1100
+ if size_average is not None or reduce is not None:
1101
+ # TODO: Raise exception instead of converting value. This is only for
1102
+ # primTorch since it can drop support for deprecated arguments.
1103
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
1104
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
1105
+ _check_reduction_value(reduction)
1106
+ if log_input:
1107
+ loss = torch.exp(input) - target * input
1108
+ else:
1109
+ loss = input - target * torch.log(input + eps)
1110
+
1111
+ if full:
1112
+ stirling_term = (
1113
+ target * torch.log(target) - target + 0.5 * torch.log(2 * torch.pi * target)
1114
+ )
1115
+ # avoid inplace add
1116
+ loss = loss + stirling_term.masked_fill(target <= 1, 0)
1117
+ return _apply_loss_reduction(loss, reduction)
1118
+
1119
+
1120
+ @register_decomposition(aten.prelu)
1121
+ @elementwise_type_promotion_wrapper(
1122
+ type_promoting_args=("a", "weight"),
1123
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1124
+ )
1125
+ def prelu(a: TensorLikeType, weight: TensorLikeType) -> TensorLikeType:
1126
+ """
1127
+ Reference implementation of torch.nn.functional.prelu
1128
+ """
1129
+ torch._check(
1130
+ isinstance(a, TensorLike),
1131
+ lambda: f"prelu: Expected `a` to be tensor, but got: {type(a)}",
1132
+ )
1133
+ torch._check(
1134
+ isinstance(weight, TensorLike),
1135
+ lambda: f"prelu: Expected `weight` to be tensor, but got: {type(weight)}",
1136
+ )
1137
+
1138
+ if weight.numel() != 1:
1139
+ torch._check(a.ndim > 0, lambda: "Not allow zero-dim input tensor.")
1140
+ channel_size = a.shape[1] if a.ndim >= 2 else 1
1141
+ torch._check(
1142
+ weight.numel() == channel_size,
1143
+ lambda: f"Mismatch of parameter numbers and input channel size. Found parameter numbers ="
1144
+ f" {weight.numel()} and channel size = {channel_size}.",
1145
+ )
1146
+
1147
+ torch._check(
1148
+ weight.ndim == 0 or weight.ndim == 1,
1149
+ lambda: f"prelu: Expected `weight` to be a scalar or 1D tensor, but got: "
1150
+ f"ndim = {weight.ndim}",
1151
+ )
1152
+ if a.ndim == 0:
1153
+ weight = weight[0] if weight.ndim == 1 else weight
1154
+ else:
1155
+ weight = prims.broadcast_in_dim(
1156
+ weight, a.shape, () if weight.ndim == 0 else (0 if a.ndim == 1 else 1,)
1157
+ )
1158
+
1159
+ return torch.where(a > 0, a, a * weight)
1160
+
1161
+
1162
+ @register_decomposition(aten.relu6)
1163
+ @_inplace_wrapper
1164
+ @out_wrapper()
1165
+ def relu6(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
1166
+ """
1167
+ Reference implementation of torch.nn.functional.relu6
1168
+ """
1169
+ if inplace:
1170
+ raise NotImplementedError
1171
+
1172
+ # See https://github.com/pytorch/pytorch/pull/81142#discussion_r918220126
1173
+ # It may be better to use clamp here, but we use hardtanh to replicate
1174
+ # the behavior of the existing implementation
1175
+ return torch.nn.functional.hardtanh(a, 0, 6)
1176
+
1177
+
1178
+ @register_decomposition(aten.glu)
1179
+ @out_wrapper()
1180
+ @elementwise_type_promotion_wrapper(
1181
+ type_promoting_args=("a",),
1182
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1183
+ )
1184
+ def glu(a: TensorLikeType, dim: int = -1) -> TensorLikeType:
1185
+ dim = utils.canonicalize_dims(a.ndim, dim)
1186
+ torch._check(
1187
+ a.shape[dim] % 2 == 0,
1188
+ lambda: f"Halving dimension must be even, but dimension {dim} is size {a.shape[dim]}",
1189
+ )
1190
+ b, c = torch.tensor_split(a, 2, dim)
1191
+
1192
+ return b * torch.sigmoid(c)
1193
+
1194
+
1195
+ @register_decomposition(aten.pairwise_distance)
1196
+ @out_wrapper()
1197
+ def pairwise_distance(
1198
+ x1: TensorLikeType,
1199
+ x2: TensorLikeType,
1200
+ p: NumberType = 2.0,
1201
+ eps: NumberType = 1e-6,
1202
+ keepdim=False,
1203
+ ) -> TensorLikeType:
1204
+ return torch.linalg.vector_norm(x1 - x2 + eps, ord=p, dim=-1, keepdim=keepdim)
1205
+
1206
+
1207
+ @register_decomposition(aten.pdist)
1208
+ @out_wrapper()
1209
+ @elementwise_type_promotion_wrapper(
1210
+ type_promoting_args=("a",),
1211
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1212
+ )
1213
+ def pdist(a: TensorLikeType, p: float = 2) -> TensorLikeType:
1214
+ torch._check(a.ndim == 2, lambda: f"pdist only supports 2D tensors, got: {a.ndim}D")
1215
+ torch._check(p >= 0, lambda: "pdist only supports non-negative p values")
1216
+ # For p == 2 we can use an efficient implementation, but other values of p
1217
+ # require creating a much bigger tensor for an intermediate step
1218
+ if p == 2:
1219
+ aTa = torch.mm(a, a.T)
1220
+ aTa_diag = torch.diag(aTa)
1221
+ t = torch.sqrt(torch.clamp(aTa_diag + aTa_diag.unsqueeze(-1) - 2 * aTa, min=0))
1222
+ else:
1223
+ t = torch.linalg.vector_norm(a.unsqueeze(1) - a, ord=p, dim=2)
1224
+ i = torch.triu_indices(t.shape[0], t.shape[1], offset=1, device=a.device)
1225
+ return t.flatten().index_select(0, i[0] * t.shape[0] + i[1])
1226
+
1227
+
1228
+ @register_decomposition(aten.pixel_shuffle)
1229
+ @out_wrapper()
1230
+ def pixel_shuffle(self: Tensor, upscale_factor: int):
1231
+ torch._check(
1232
+ self.dim() >= 3,
1233
+ lambda: f"pixel_shuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
1234
+ )
1235
+ batch = self.shape[:-3]
1236
+ C_out = self.shape[-3] // upscale_factor**2
1237
+ HW_out = (self.shape[-2] * upscale_factor, self.shape[-1] * upscale_factor)
1238
+ n = len(batch)
1239
+ B_dims = range(n)
1240
+ C_dim, r1_dim, r2_dim, H_dim, W_dim = range(n, n + 5)
1241
+ return (
1242
+ self.view(
1243
+ *batch,
1244
+ C_out,
1245
+ upscale_factor,
1246
+ upscale_factor,
1247
+ self.shape[-2],
1248
+ self.shape[-1],
1249
+ )
1250
+ .permute(*B_dims, C_dim, H_dim, r1_dim, W_dim, r2_dim)
1251
+ .reshape(*batch, C_out, *HW_out)
1252
+ .clone(memory_format=utils.suggest_memory_format(self))
1253
+ )
1254
+
1255
+
1256
+ @register_decomposition(aten.pixel_unshuffle)
1257
+ @out_wrapper()
1258
+ def pixel_unshuffle(self: Tensor, downscale_factor: int):
1259
+ torch._check(
1260
+ self.dim() >= 3,
1261
+ lambda: f"pixel_unshuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
1262
+ )
1263
+ batch = self.shape[:-3]
1264
+ C_out = self.shape[-3] * downscale_factor**2
1265
+ HW_out = (self.shape[-2] // downscale_factor, self.shape[-1] // downscale_factor)
1266
+ n = len(batch)
1267
+ B_dims = range(n)
1268
+ C_dim, H_dim, r1_dim, W_dim, r2_dim = range(n, n + 5)
1269
+ return (
1270
+ self.view(
1271
+ *batch,
1272
+ self.shape[-3],
1273
+ HW_out[0],
1274
+ downscale_factor,
1275
+ HW_out[1],
1276
+ downscale_factor,
1277
+ )
1278
+ .permute(*B_dims, C_dim, r1_dim, r2_dim, H_dim, W_dim)
1279
+ .reshape(*batch, C_out, *HW_out)
1280
+ .clone(memory_format=utils.suggest_memory_format(self))
1281
+ )
1282
+
1283
+
1284
+ # Needed as aten.{celu_,elu_...} exist (even if they don't have the in-place kwarg)
1285
+ celu_ = _make_inplace(celu)
1286
+ elu_ = _make_inplace(elu)
1287
+ mish_ = _make_inplace(mish)
1288
+ selu_ = _make_inplace(selu)
1289
+ threshold_ = _make_inplace(threshold)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (27.7 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/special/__init__.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch._prims as prims
7
+ import torch._prims_common as utils
8
+ import torch._refs as refs
9
+ from torch import Tensor
10
+ from torch._decomp import register_decomposition
11
+ from torch._prims_common import (
12
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
13
+ Number,
14
+ NumberType,
15
+ TensorLike,
16
+ TensorLikeType,
17
+ )
18
+ from torch._prims_common.wrappers import elementwise_type_promotion_wrapper, out_wrapper
19
+ from torch._refs import (
20
+ _make_alias,
21
+ _make_elementwise_binary_reference,
22
+ _make_elementwise_unary_reference,
23
+ )
24
+
25
+
26
+ __all__ = [
27
+ "bessel_j0",
28
+ "bessel_j1",
29
+ "entr",
30
+ "erfcx",
31
+ "expit",
32
+ "i0e",
33
+ "i1",
34
+ "i1e",
35
+ "log_ndtr",
36
+ "logit",
37
+ "log_softmax",
38
+ "multigammaln",
39
+ "ndtr",
40
+ "ndtri",
41
+ "softmax",
42
+ "spherical_bessel_j0",
43
+ "xlog1py",
44
+ "zeta",
45
+ ]
46
+ aten = torch._ops.ops.aten
47
+
48
+
49
+ @_make_elementwise_unary_reference(
50
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
51
+ )
52
+ def bessel_j0(a: TensorLikeType) -> TensorLikeType:
53
+ return prims.bessel_j0(a)
54
+
55
+
56
+ @_make_elementwise_unary_reference(
57
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
58
+ )
59
+ def bessel_j1(a: TensorLikeType) -> TensorLikeType:
60
+ return prims.bessel_j1(a)
61
+
62
+
63
+ @register_decomposition(aten.special_entr)
64
+ @out_wrapper()
65
+ @elementwise_type_promotion_wrapper(
66
+ type_promoting_args=("a",),
67
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
68
+ )
69
+ def entr(a: TensorLikeType) -> TensorLikeType:
70
+ return torch.where(
71
+ torch.isnan(a),
72
+ a,
73
+ torch.where(a > 0, -a * torch.log(a), torch.where(a == 0, 0, -torch.inf)),
74
+ )
75
+
76
+
77
+ @register_decomposition(aten.special_erfcx)
78
+ @out_wrapper()
79
+ @elementwise_type_promotion_wrapper(
80
+ type_promoting_args=("a",),
81
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
82
+ )
83
+ def erfcx(a: TensorLikeType) -> TensorLikeType:
84
+ return prims.erfcx(a)
85
+
86
+
87
+ # alias for sigmoid
88
+ expit = _make_alias(torch.sigmoid, "expit")
89
+
90
+
91
+ @_make_elementwise_unary_reference(
92
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
93
+ )
94
+ def i0e(a: TensorLikeType) -> TensorLikeType:
95
+ return prims.bessel_i0e(a)
96
+
97
+
98
+ @_make_elementwise_unary_reference(
99
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
100
+ )
101
+ def i1(a: TensorLikeType) -> TensorLikeType:
102
+ return prims.bessel_i1(a)
103
+
104
+
105
+ @_make_elementwise_unary_reference(
106
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
107
+ )
108
+ def i1e(a: TensorLikeType) -> TensorLikeType:
109
+ return prims.bessel_i1e(a)
110
+
111
+
112
+ @register_decomposition(aten.special_log_ndtr)
113
+ @out_wrapper()
114
+ @elementwise_type_promotion_wrapper(
115
+ type_promoting_args=("a",),
116
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
117
+ )
118
+ def log_ndtr(a: TensorLikeType) -> TensorLikeType:
119
+ # Note: M_SQRT1_2 is the value of 1 / sqrt(2)
120
+ M_SQRT1_2 = 0.707106781186547524400844362104849039
121
+ t = a * M_SQRT1_2
122
+ return torch.where(
123
+ a < 1.0,
124
+ torch.log(torch.special.erfcx(-t) / 2) - t * t,
125
+ torch.log1p(-torch.erfc(t) / 2),
126
+ )
127
+
128
+
129
+ @register_decomposition(aten.logit)
130
+ @out_wrapper()
131
+ @elementwise_type_promotion_wrapper(
132
+ type_promoting_args=("self",),
133
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
134
+ )
135
+ def logit(self: TensorLikeType, eps: Optional[float] = None) -> TensorLikeType:
136
+ if eps is None:
137
+ eps = -1.0
138
+ lo = eps
139
+ hi = 1 - eps
140
+ self = torch.where(self < lo, lo, torch.where(self > hi, hi, self))
141
+ return torch.log(torch.true_divide(self, torch.sub(1, self)))
142
+
143
+
144
+ @register_decomposition(aten.special_xlog1py)
145
+ @out_wrapper()
146
+ @elementwise_type_promotion_wrapper(
147
+ type_promoting_args=("a", "b"),
148
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
149
+ )
150
+ def xlog1py(a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]):
151
+ torch._check(
152
+ isinstance(a, TensorLike) or isinstance(b, TensorLike),
153
+ lambda: 'Expected either argument a or b to be a Tensor"',
154
+ )
155
+
156
+ # Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors.
157
+ if isinstance(a, TensorLike) and isinstance(b, Number):
158
+ b = refs.scalar_tensor(b, dtype=a.dtype, device=a.device)
159
+ elif isinstance(b, TensorLike) and isinstance(a, Number):
160
+ a = refs.scalar_tensor(a, dtype=b.dtype, device=b.device)
161
+
162
+ # mypy: expected "Tensor"
163
+ assert isinstance(a, TensorLike)
164
+ assert isinstance(b, TensorLike)
165
+ rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log1p(b)))
166
+ return torch.where(torch.isnan(b), float("nan"), rhs)
167
+
168
+
169
+ @register_decomposition(aten.mvlgamma)
170
+ @out_wrapper()
171
+ @elementwise_type_promotion_wrapper(
172
+ type_promoting_args=("a",),
173
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
174
+ )
175
+ def multigammaln(a: TensorLikeType, p: int) -> TensorLikeType:
176
+ c = 0.25 * p * (p - 1) * math.log(math.pi)
177
+ b = 0.5 * torch.arange(start=(1 - p), end=1, step=1, dtype=a.dtype, device=a.device)
178
+ return torch.sum(torch.lgamma(a.unsqueeze(-1) + b), dim=-1) + c
179
+
180
+
181
+ @register_decomposition(aten.special_ndtr)
182
+ @out_wrapper()
183
+ @elementwise_type_promotion_wrapper(
184
+ type_promoting_args=("a",),
185
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
186
+ )
187
+ def ndtr(a: TensorLikeType) -> TensorLikeType:
188
+ # Note: M_SQRT1_2 is the value of 1 / sqrt(2)
189
+ M_SQRT1_2 = 0.707106781186547524400844362104849039
190
+ a_sqrt_2 = a * M_SQRT1_2
191
+ return (1 + torch.erf(a_sqrt_2)) * 0.5
192
+
193
+
194
+ @register_decomposition(aten.special_ndtri)
195
+ @out_wrapper()
196
+ @elementwise_type_promotion_wrapper(
197
+ type_promoting_args=("a",),
198
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
199
+ )
200
+ def ndtri(a: TensorLikeType) -> TensorLikeType:
201
+ return prims.ndtri(a)
202
+
203
+
204
+ # Forwarding alias: the special variant doesn't support the out kwarg
205
+ # CompositeImplicitAutograd - don't register decomp
206
+ def log_softmax(
207
+ a: TensorLikeType,
208
+ dim: int,
209
+ dtype: Optional[torch.dtype] = None,
210
+ ) -> TensorLikeType:
211
+ return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
212
+
213
+
214
+ # Forwarding alias: the special variant doesn't support the out kwarg
215
+ # CompositeImplicitAutograd - don't register decomp
216
+ def softmax(
217
+ a: TensorLikeType,
218
+ dim: int,
219
+ dtype: Optional[torch.dtype] = None,
220
+ ) -> TensorLikeType:
221
+ return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
222
+
223
+
224
+ @_make_elementwise_unary_reference(
225
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
226
+ )
227
+ def spherical_bessel_j0(a: TensorLikeType) -> TensorLikeType:
228
+ return prims.spherical_bessel_j0(a)
229
+
230
+
231
+ # TODO: add docstring
232
+ @_make_elementwise_binary_reference(
233
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
234
+ )
235
+ def zeta(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
236
+ return prims.zeta(a, b)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_refs/special/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__init__.py ADDED
File without changes
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (232 Bytes). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__pycache__/cli_function_profiler.cpython-310.pyc ADDED
Binary file (9.33 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/__pycache__/compile_time_profiler.cpython-310.pyc ADDED
Binary file (6.48 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/cli_function_profiler.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disallow-untyped-defs
2
+
3
+ import functools
4
+ import logging
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import time
9
+ from collections.abc import Sequence
10
+ from threading import Lock
11
+ from timeit import default_timer as timer
12
+ from typing import Any, Callable, Optional, TypeVar
13
+ from typing_extensions import ParamSpec
14
+
15
+
16
+ logger = logging.getLogger("strobelight_function_profiler")
17
+
18
+ console_handler = logging.StreamHandler()
19
+ formatter = logging.Formatter(
20
+ "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s"
21
+ )
22
+ console_handler.setFormatter(formatter)
23
+
24
+ logger.addHandler(console_handler)
25
+ logger.setLevel(logging.INFO)
26
+ logger.propagate = False
27
+
28
+ _P = ParamSpec("_P")
29
+ _R = TypeVar("_R")
30
+
31
+
32
+ class StrobelightCLIProfilerError(Exception):
33
+ """
34
+ Raised when an error happens during strobelight profiling
35
+ """
36
+
37
+
38
+ def _pid_namespace_link(pid: Optional[int] = None) -> str:
39
+ """Returns the link to the process's namespace, example: pid:[4026531836]"""
40
+ PID_NAMESPACE_PATH = "/proc/{}/ns/pid"
41
+ pid = pid or os.getpid()
42
+ return os.readlink(PID_NAMESPACE_PATH.format(pid))
43
+
44
+
45
+ def _pid_namespace(pid: Optional[int] = None) -> int:
46
+ """Returns the process's namespace id"""
47
+ pid = pid or os.getpid()
48
+ link = _pid_namespace_link(pid)
49
+ return int(link[link.find("[") + 1 : -1])
50
+
51
+
52
+ def _command_to_string(command: Sequence[str]) -> str:
53
+ return " ".join(command)
54
+
55
+
56
+ class StrobelightCLIFunctionProfiler:
57
+ """
58
+ Note: this is a Meta only tool.
59
+
60
+ StrobelightCLIFunctionProfiler can be used to profile a python function and
61
+ generate a strobelight link with the results. It works on meta servers but
62
+ does not requires an fbcode target.
63
+ When stop_at_error is false(default), error during profiling does not prevent
64
+ the work function from running.
65
+
66
+ Check function_profiler_example.py for an example.
67
+ """
68
+
69
+ # This lock is used to make sure only one thread is running the profiler at any point.
70
+ _lock = Lock()
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ stop_at_error: bool = False,
76
+ max_profile_duration_sec: int = 60 * 10,
77
+ sample_each: float = 1e7, # sample each sample_each cycles.
78
+ run_user_name: str = "pytorch-strobelight-ondemand",
79
+ timeout_wait_for_running_sec: int = 60,
80
+ timeout_wait_for_finished_sec: int = 60,
81
+ recorded_env_variables: Optional[list[str]] = None,
82
+ sample_tags: Optional[list[str]] = None,
83
+ stack_max_len: int = 127,
84
+ async_stack_max_len: int = 127,
85
+ ):
86
+ self.stop_at_error = stop_at_error
87
+ self.max_profile_duration_sec = max_profile_duration_sec
88
+ self.sample_each = sample_each
89
+ self.run_user_name = run_user_name
90
+ self.timeout_wait_for_running_sec = timeout_wait_for_running_sec
91
+ self.timeout_wait_for_finished_sec = timeout_wait_for_finished_sec
92
+ # Results of the most recent run.
93
+ # Tracks the strobelight run id of the most recent run
94
+ self.current_run_id: Optional[int] = None
95
+ self.profile_result: Optional[list[str]] = None
96
+ self.sample_tags = sample_tags
97
+
98
+ def _run_async(self) -> None:
99
+ processId = os.getpid()
100
+ namespace = _pid_namespace(processId)
101
+ command = [
102
+ "strobeclient",
103
+ "run",
104
+ "--profiler",
105
+ "pyperf",
106
+ "--event",
107
+ "cycles",
108
+ "--async",
109
+ "--sample-interval",
110
+ f"{int(self.sample_each)}",
111
+ "--duration-ms",
112
+ f"{int(self.max_profile_duration_sec * 1000)}",
113
+ "--pid",
114
+ f"{namespace}:{processId}",
115
+ ]
116
+
117
+ if self.sample_tags:
118
+ command.append("--sample-tags")
119
+ command.append(",".join(self.sample_tags))
120
+
121
+ logger.debug("running command: %s", _command_to_string(command))
122
+ result = subprocess.run(command, capture_output=True)
123
+ output = result.stderr.decode("utf-8")
124
+ logger.debug("output:\n{%s}", output)
125
+
126
+ if result.returncode != 0:
127
+ raise StrobelightCLIProfilerError(
128
+ f"failed to start strobelight profiling, error in run_async:{output}"
129
+ )
130
+
131
+ if match := re.search(r"INFO Run Id: (-?\d+)", output):
132
+ self.current_run_id = int(match.group(1))
133
+ return
134
+
135
+ raise StrobelightCLIProfilerError(
136
+ f"failed to start strobelight profiling, unexpected result {output}"
137
+ )
138
+
139
+ def _wait_for_running(self, counter: int = 0) -> None:
140
+ if counter > 20:
141
+ raise StrobelightCLIProfilerError(
142
+ "wait_for_running called more than 20 times"
143
+ )
144
+
145
+ command = ["strobeclient", "getRunStatus", "--run-id", f"{self.current_run_id}"]
146
+ logger.debug("running command: %s", _command_to_string(command))
147
+ result = subprocess.run(command, capture_output=True)
148
+ output = result.stderr.decode("utf-8")
149
+ logger.debug("output:\n{%s}", output)
150
+
151
+ if result.returncode != 0:
152
+ raise StrobelightCLIProfilerError(
153
+ f"failed to start strobelight profiling, error in wait_for_running:{output}"
154
+ )
155
+
156
+ if match := re.search("Profile run status: (.*)", output):
157
+ current_status = match.group(1)
158
+ if current_status == "RUNNING":
159
+ return
160
+ elif current_status == "PREPARING":
161
+ time.sleep(10)
162
+ self._wait_for_running(counter + 1)
163
+ return
164
+ else:
165
+ raise StrobelightCLIProfilerError(f"unexpected {current_status} phase")
166
+
167
+ raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ")
168
+
169
+ def _stop_run(self) -> None:
170
+ command = ["strobeclient", "stopRun", "--run-id", str(self.current_run_id)]
171
+ logger.debug("running command: %s", _command_to_string(command))
172
+ result = subprocess.run(command, capture_output=True)
173
+ output = result.stderr.decode("utf-8")
174
+ logger.debug("output:\n{%s}", output)
175
+
176
+ if result.returncode != 0:
177
+ raise StrobelightCLIProfilerError(
178
+ f"failed to stop strobelight profiling, return code is not 0 :{output}"
179
+ )
180
+
181
+ if match := re.search("INFO ::1:(.*)", output):
182
+ current_status = match.group(1)
183
+ if current_status.__contains__("Success!"):
184
+ return
185
+ else:
186
+ raise StrobelightCLIProfilerError(
187
+ f"failed to stop strobelight profiling, got {current_status} result"
188
+ )
189
+
190
+ raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ")
191
+
192
+ def _get_results(self) -> None:
193
+ command = ["strobeclient", "getRunStatus", "--run-id", str(self.current_run_id)]
194
+ logger.debug("running command: %s", _command_to_string(command))
195
+ result = subprocess.run(command, capture_output=True)
196
+ output = result.stderr.decode("utf-8")
197
+ logger.debug("output:\n{%s}", output)
198
+
199
+ if result.returncode != 0:
200
+ raise StrobelightCLIProfilerError(
201
+ f"failed to extract profiling results, return code is not 0 : {output}"
202
+ )
203
+
204
+ if match := re.search("INFO ::1:(.*)", output):
205
+ current_status = match.group(1)
206
+ if current_status.__contains__("Profile run status: PROCESSING"):
207
+ time.sleep(10)
208
+ self._get_results()
209
+ return
210
+ elif not current_status.__contains__("Profile run finished with SUCCESS"):
211
+ raise StrobelightCLIProfilerError(
212
+ f"failed to extract profiling results, unexpected response {output}"
213
+ )
214
+
215
+ self.profile_result = []
216
+ for item in re.findall(
217
+ r"(Total samples(.*)|GraphProfiler(.*)|Icicle view \(python stack\)(.*))",
218
+ output,
219
+ ):
220
+ self.profile_result += item[0]
221
+ logger.info(item[0])
222
+
223
+ def _stop_strobelight_no_throw(
224
+ self,
225
+ collect_results: bool,
226
+ ) -> None:
227
+ try:
228
+ # call stop run
229
+ self._stop_run()
230
+ logger.info("strobelight profiling stopped")
231
+
232
+ logger.debug("collection stopped")
233
+
234
+ if not collect_results:
235
+ return
236
+
237
+ self._get_results()
238
+ except Exception:
239
+ logger.warning("error during stop_strobelight", exc_info=True)
240
+
241
+ # Return true if strobelight started and is running. Never throw.
242
+ def _start_strobelight(self) -> bool:
243
+ strobelight_started = False
244
+ try:
245
+ self._run_async()
246
+ strobelight_started = True
247
+ logger.info("strobelight run id is: %s", self.current_run_id)
248
+ self._wait_for_running()
249
+ logger.info("strobelight profiling running")
250
+ return True
251
+
252
+ except Exception:
253
+ logger.warning("error during start_strobelight:", exc_info=True)
254
+ if strobelight_started:
255
+ self._stop_strobelight_no_throw(collect_results=False)
256
+ return False
257
+
258
+ def profile(
259
+ self, work_function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs
260
+ ) -> Optional[_R]:
261
+ self.current_run_id = None
262
+ self.profile_result = None
263
+
264
+ if locked := StrobelightCLIFunctionProfiler._lock.acquire(False):
265
+ if not locked:
266
+ if self.stop_at_error:
267
+ raise StrobelightCLIProfilerError("concurrent runs not supported")
268
+
269
+ logger.warning("concurrent runs not supported")
270
+ return work_function(*args, **kwargs)
271
+
272
+ started = self._start_strobelight()
273
+ if not started:
274
+ if self.stop_at_error:
275
+ StrobelightCLIFunctionProfiler._lock.release()
276
+ raise StrobelightCLIProfilerError(
277
+ "failed to start strobelight profiling"
278
+ )
279
+ result = work_function(*args, **kwargs)
280
+ StrobelightCLIFunctionProfiler._lock.release()
281
+ return result
282
+
283
+ try:
284
+ logger.debug("collection started")
285
+ start = timer()
286
+ result = work_function(*args, **kwargs)
287
+ end = timer()
288
+ total_time = end - start # Time in seconds, e.g. 5.38091952400282
289
+ logger.info("work function took %s seconds", total_time)
290
+ self._stop_strobelight_no_throw(collect_results=True)
291
+ StrobelightCLIFunctionProfiler._lock.release()
292
+ return result
293
+ except Exception as error:
294
+ logger.warning("work function throw exception", exc_info=True)
295
+ self._stop_strobelight_no_throw(collect_results=False)
296
+ StrobelightCLIFunctionProfiler._lock.release()
297
+ raise error
298
+ return None
299
+
300
+
301
+ # A function decorator that wraps profile, if no profiler is provided one with
302
+ # default args is created. A function can be annotated as:
303
+ # @strobelight()
304
+ # @strobelight(profiler = StrobelightFunctionProfiler(stop_at_error=True,..))
305
+ # @strobelight(stop_at_error=True,...)
306
+ def strobelight(
307
+ profiler: Optional[StrobelightCLIFunctionProfiler] = None, **kwargs: Any
308
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, Optional[_R]]]:
309
+ if not profiler:
310
+ profiler = StrobelightCLIFunctionProfiler(**kwargs)
311
+
312
+ def strobelight_inner(
313
+ work_function: Callable[_P, _R],
314
+ ) -> Callable[_P, Optional[_R]]:
315
+ @functools.wraps(work_function)
316
+ def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> Optional[_R]:
317
+ return profiler.profile(work_function, *args, **kwargs)
318
+
319
+ return wrapper_function
320
+
321
+ return strobelight_inner
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_strobelight/compile_time_profiler.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disallow-untyped-defs
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from datetime import datetime
9
+ from socket import gethostname
10
+ from typing import Any, Optional
11
+
12
+ from torch._strobelight.cli_function_profiler import StrobelightCLIFunctionProfiler
13
+
14
+
15
+ logger = logging.getLogger("strobelight_compile_time_profiler")
16
+
17
+ console_handler = logging.StreamHandler()
18
+ formatter = logging.Formatter(
19
+ "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s"
20
+ )
21
+ console_handler.setFormatter(formatter)
22
+
23
+ logger.addHandler(console_handler)
24
+ logger.setLevel(logging.INFO)
25
+ logger.propagate = False
26
+
27
+
28
+ def get_fburl(url: str) -> str:
29
+ short_url = url
30
+ # Attempt to shorten the URL
31
+ try:
32
+ result = subprocess.run(
33
+ ["fburl", url], capture_output=True, stdin=subprocess.DEVNULL
34
+ )
35
+ if result.returncode == 0:
36
+ short_url = result.stdout.decode("utf-8")
37
+ except Exception as e:
38
+ logger.warning("URL shortening failed: %s, using long URL", repr(e))
39
+ return short_url
40
+
41
+
42
+ def get_strobelight_url(identifier: str) -> str:
43
+ scuba_json = {
44
+ "aggregateList": [],
45
+ "aggregation_field": "async_stack_complete",
46
+ "b_constraints": [[]],
47
+ "c_constraints": [[]],
48
+ "cols": ["namespace_id", "namespace_process_id"],
49
+ "compare": "none",
50
+ "constraints": [
51
+ [{"column": "sample_tags", "op": "all", "value": [f'["{identifier}"]']}]
52
+ ],
53
+ "derivedCols": [],
54
+ "end": "now",
55
+ "enumCols": [],
56
+ "filterMode": "DEFAULT",
57
+ "hideEmptyColumns": "false",
58
+ "ignoreGroupByInComparison": "false",
59
+ "is_timeseries": "false",
60
+ "mappedCols": [],
61
+ "metric": "count",
62
+ "modifiers": [],
63
+ "order": "weight",
64
+ "order_desc": "true",
65
+ "param_dimensions": [
66
+ {"dim": "py_async_stack", "op": "edge", "param": "0", "anchor": "0"}
67
+ ],
68
+ "purposes": [],
69
+ "return_remainder": "false",
70
+ "samplingRatio": "1",
71
+ "should_pivot": "false",
72
+ "start": "-30 days",
73
+ "timezone": "America/Los_Angeles",
74
+ "top": 10000,
75
+ }
76
+ scuba_url_prefix = "https://www.internalfb.com/intern/scuba/query/?dataset=pyperf_experimental/on_demand&drillstate="
77
+ scuba_url_suff = "&view=GraphProfilerView&&normalized=1726332703&pool=uber"
78
+ long_url = scuba_url_prefix + json.dumps(scuba_json) + scuba_url_suff
79
+ return get_fburl(long_url)
80
+
81
+
82
+ class StrobelightCompileTimeProfiler:
83
+ success_profile_count: int = 0
84
+ failed_profile_count: int = 0
85
+ ignored_profile_runs: int = 0
86
+ inside_profile_compile_time: bool = False
87
+ enabled: bool = False
88
+
89
+ # A regex that can be used to filter out what frames to profile. ex: "1/.*"
90
+ frame_id_filter: Optional[str] = os.environ.get("COMPILE_STROBELIGHT_FRAME_FILTER")
91
+
92
+ # A unique identifier that is used as the run_user_name in the strobelight profile to
93
+ # associate all compile time profiles together.
94
+ identifier: Optional[str] = None
95
+
96
+ current_phase: Optional[str] = None
97
+
98
+ profiler: Optional[Any] = None
99
+
100
+ max_stack_length: int = int(
101
+ os.environ.get("COMPILE_STROBELIGHT_MAX_STACK_LENGTH", 500)
102
+ )
103
+ max_profile_time: int = int(
104
+ os.environ.get("COMPILE_STROBELIGHT_MAX_PROFILE_TIME", 60 * 30)
105
+ )
106
+ # Collect sample each x cycles.
107
+ sample_each: int = int(
108
+ float(os.environ.get("COMPILE_STROBELIGHT_SAMPLE_RATE", 1e7))
109
+ )
110
+
111
+ @classmethod
112
+ def get_frame(cls) -> str:
113
+ from torch._guards import CompileContext
114
+
115
+ return (str)(CompileContext.current_trace_id())
116
+
117
+ @classmethod
118
+ def enable(cls, profiler_class: Any = StrobelightCLIFunctionProfiler) -> None:
119
+ if cls.enabled:
120
+ logger.info("compile time strobelight profiling already enabled")
121
+ return
122
+
123
+ logger.info("compile time strobelight profiling enabled")
124
+
125
+ if profiler_class is StrobelightCLIFunctionProfiler:
126
+ import shutil
127
+
128
+ if not shutil.which("strobeclient"):
129
+ logger.info(
130
+ "strobeclient not found, can't enable compile time strobelight profiling, seems"
131
+ "like you are not on a FB machine."
132
+ )
133
+ return
134
+
135
+ cls.enabled = True
136
+ cls._cls_init()
137
+ # profiler_class should have public API similar to that of StrobelightCLIFunctionProfiler.
138
+ # we have pass different functionProfilerClass for meta-internal fbcode targets.
139
+ # NB: the actual implementation in Meta is at
140
+ # fbcode/caffe2/fb/strobelight/function_profiler.py
141
+ cls.profiler = profiler_class(
142
+ sample_each=cls.sample_each,
143
+ max_profile_duration_sec=cls.max_profile_time,
144
+ stack_max_len=cls.max_stack_length,
145
+ async_stack_max_len=cls.max_stack_length,
146
+ run_user_name="pt2-profiler/"
147
+ + os.environ.get("USER", os.environ.get("USERNAME", "")),
148
+ sample_tags={cls.identifier},
149
+ )
150
+
151
+ @classmethod
152
+ def _cls_init(cls) -> None:
153
+ cls.identifier = "{date}{pid}{hostname}".format(
154
+ date=datetime.now().strftime("%Y-%m-%d-%H:%M:%S"),
155
+ pid=os.getpid(),
156
+ hostname=gethostname(),
157
+ )
158
+
159
+ logger.info("Unique sample tag for this run is: %s", cls.identifier)
160
+ logger.info(
161
+ "URL to access the strobelight profile at the end of the run: %s",
162
+ get_strobelight_url(cls.identifier),
163
+ )
164
+
165
+ @classmethod
166
+ def _log_stats(cls) -> None:
167
+ logger.info(
168
+ "%s strobelight success runs out of %s non-recursive compilation events.",
169
+ cls.success_profile_count,
170
+ cls.success_profile_count + cls.failed_profile_count,
171
+ )
172
+
173
+ # TODO use threadlevel meta data to tags to record phases.
174
+ @classmethod
175
+ def profile_compile_time(
176
+ cls, func: Any, phase_name: str, *args: Any, **kwargs: Any
177
+ ) -> Any:
178
+ def skip() -> Any:
179
+ return func(*args, **kwargs)
180
+
181
+ if not cls.enabled:
182
+ return skip()
183
+
184
+ if cls.profiler is None:
185
+ logger.error("profiler is not set")
186
+ return
187
+
188
+ frame_id = cls.get_frame()
189
+
190
+ if cls.inside_profile_compile_time:
191
+ cls.ignored_profile_runs += 1
192
+ logger.info(
193
+ "profile_compile_time is requested for phase: %s, frame %s, while already in running phase: %s,"
194
+ "frame %s, recursive call ignored",
195
+ phase_name,
196
+ frame_id,
197
+ cls.current_phase,
198
+ frame_id,
199
+ )
200
+ return skip()
201
+
202
+ if cls.frame_id_filter is not None:
203
+ should_run = re.match(cls.frame_id_filter, frame_id) is not None
204
+ if not should_run:
205
+ logger.info(
206
+ "profiling frame %s is skipped due to frame_id_filter %s",
207
+ frame_id,
208
+ cls.frame_id_filter,
209
+ )
210
+ return skip()
211
+
212
+ cls.inside_profile_compile_time = True
213
+ cls.current_phase = phase_name
214
+ logger.info("profiling frame %s", frame_id)
215
+ work_result = cls.profiler.profile(func, *args, **kwargs)
216
+
217
+ if cls.profiler.profile_result is not None:
218
+ cls.success_profile_count += 1
219
+ else:
220
+ cls.failed_profile_count += 1
221
+
222
+ cls._log_stats()
223
+ cls.inside_profile_compile_time = False
224
+ return work_result