hxrron commited on
Commit
4264cf1
·
verified ·
1 Parent(s): 33b9bd3

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. python_embeded/Lib/site-packages/_soundfile.py +11 -0
  2. python_embeded/Lib/site-packages/absl/__init__.py +15 -0
  3. python_embeded/Lib/site-packages/absl/app.py +488 -0
  4. python_embeded/Lib/site-packages/absl/app.pyi +88 -0
  5. python_embeded/Lib/site-packages/absl/py.typed +0 -0
  6. python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/INSTALLER +1 -0
  7. python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/METADATA +91 -0
  8. python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/RECORD +53 -0
  9. python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/WHEEL +4 -0
  10. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/INSTALLER +1 -0
  11. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/METADATA +396 -0
  12. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/RECORD +177 -0
  13. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/REQUESTED +0 -0
  14. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/WHEEL +5 -0
  15. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/entry_points.txt +6 -0
  16. python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/top_level.txt +1 -0
  17. python_embeded/Lib/site-packages/accelerate/__init__.py +50 -0
  18. python_embeded/Lib/site-packages/accelerate/accelerator.py +0 -0
  19. python_embeded/Lib/site-packages/accelerate/big_modeling.py +749 -0
  20. python_embeded/Lib/site-packages/accelerate/checkpointing.py +330 -0
  21. python_embeded/Lib/site-packages/accelerate/data_loader.py +1445 -0
  22. python_embeded/Lib/site-packages/accelerate/hooks.py +765 -0
  23. python_embeded/Lib/site-packages/accelerate/inference.py +184 -0
  24. python_embeded/Lib/site-packages/accelerate/launchers.py +302 -0
  25. python_embeded/Lib/site-packages/accelerate/local_sgd.py +106 -0
  26. python_embeded/Lib/site-packages/accelerate/logging.py +125 -0
  27. python_embeded/Lib/site-packages/accelerate/memory_utils.py +22 -0
  28. python_embeded/Lib/site-packages/accelerate/optimizer.py +213 -0
  29. python_embeded/Lib/site-packages/accelerate/scheduler.py +98 -0
  30. python_embeded/Lib/site-packages/accelerate/state.py +1344 -0
  31. python_embeded/Lib/site-packages/accelerate/tracking.py +1233 -0
  32. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/INSTALLER +1 -0
  33. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/LICENSE +22 -0
  34. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/METADATA +23 -0
  35. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/RECORD +11 -0
  36. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/REQUESTED +0 -0
  37. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/WHEEL +5 -0
  38. python_embeded/Lib/site-packages/addict-2.4.0.dist-info/top_level.txt +1 -0
  39. python_embeded/Lib/site-packages/addict/__init__.py +10 -0
  40. python_embeded/Lib/site-packages/addict/addict.py +159 -0
  41. python_embeded/Lib/site-packages/adodbapi/__init__.py +82 -0
  42. python_embeded/Lib/site-packages/adodbapi/ado_consts.py +283 -0
  43. python_embeded/Lib/site-packages/adodbapi/adodbapi.py +1153 -0
  44. python_embeded/Lib/site-packages/adodbapi/apibase.py +723 -0
  45. python_embeded/Lib/site-packages/adodbapi/is64bit.py +34 -0
  46. python_embeded/Lib/site-packages/adodbapi/license.txt +505 -0
  47. python_embeded/Lib/site-packages/adodbapi/process_connect_string.py +137 -0
  48. python_embeded/Lib/site-packages/adodbapi/readme.txt +88 -0
  49. python_embeded/Lib/site-packages/adodbapi/schema_table.py +16 -0
  50. python_embeded/Lib/site-packages/adodbapi/setup.py +68 -0
python_embeded/Lib/site-packages/_soundfile.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # auto-generated file
2
+ import _cffi_backend
3
+
4
+ ffi = _cffi_backend.FFI('_soundfile',
5
+ _version = 0x2601,
6
+ _types = b'\x00\x00\x17\x0D\x00\x00\x6D\x03\x00\x00\x07\x01\x00\x00\x6C\x03\x00\x00\x7A\x03\x00\x00\x00\x0F\x00\x00\x17\x0D\x00\x00\x6F\x03\x00\x00\x07\x01\x00\x00\x03\x11\x00\x00\x00\x0F\x00\x00\x17\x0D\x00\x00\x07\x01\x00\x00\x07\x01\x00\x00\x03\x11\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x17\x0D\x00\x00\x7B\x03\x00\x00\x07\x01\x00\x00\x03\x11\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x6E\x03\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x17\x11\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x6C\x03\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x6F\x03\x00\x00\x1C\x01\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x07\x01\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x07\x01\x00\x00\x04\x11\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x70\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x74\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x02\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x17\x01\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x79\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x04\x11\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x01\x00\x00\x07\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x04\x11\x00\x00\x17\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x7A\x03\x00\x00\x17\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x7A\x0D\x00\x00\x17\x11\x00\x00\x00\x0F\x00\x00\x00\x09\x00\x00\x01\x09\x00\x00\x02\x09\x00\x00\x03\x09\x00\x00\x02\x01\x00\x00\x0E\x01\x00\x00\x00\x0B\x00\x00\x01\x0B\x00\x00\x02\x0B\x00\x00\x0D\x01\x00\x00\x56\x03\x00\x00\x5B\x03\x00\x00\x5E\x03\x00\x00\x63\x03\x00\x00\x05\x01\x00\x00\x00\x01\x00\x00\x10\x01',
7
+ _globals = (b'\xFF\xFF\xFF\x0BSFC_FILE_TRUNCATE',4224,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_INFO',4136,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_MAJOR',4145,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_MAJOR_COUNT',4144,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_SUBTYPE',4147,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_SUBTYPE_COUNT',4146,b'\xFF\xFF\xFF\x0BSFC_GET_LIB_VERSION',4096,b'\xFF\xFF\xFF\x0BSFC_GET_LOG_INFO',4097,b'\xFF\xFF\xFF\x0BSFC_SET_BITRATE_MODE',4869,b'\xFF\xFF\xFF\x0BSFC_SET_CLIPPING',4288,b'\xFF\xFF\xFF\x0BSFC_SET_COMPRESSION_LEVEL',4865,b'\xFF\xFF\xFF\x0BSFC_SET_SCALE_FLOAT_INT_READ',4116,b'\xFF\xFF\xFF\x0BSFC_SET_SCALE_INT_FLOAT_WRITE',4117,b'\xFF\xFF\xFF\x0BSFM_RDWR',48,b'\xFF\xFF\xFF\x0BSFM_READ',16,b'\xFF\xFF\xFF\x0BSFM_WRITE',32,b'\xFF\xFF\xFF\x0BSF_BITRATE_MODE_AVERAGE',1,b'\xFF\xFF\xFF\x0BSF_BITRATE_MODE_CONSTANT',0,b'\xFF\xFF\xFF\x0BSF_BITRATE_MODE_VARIABLE',2,b'\xFF\xFF\xFF\x0BSF_FALSE',0,b'\xFF\xFF\xFF\x0BSF_FORMAT_ENDMASK',805306368,b'\xFF\xFF\xFF\x0BSF_FORMAT_SUBMASK',65535,b'\xFF\xFF\xFF\x0BSF_FORMAT_TYPEMASK',268369920,b'\xFF\xFF\xFF\x0BSF_TRUE',1,b'\x00\x00\x25\x23sf_close',0,b'\x00\x00\x32\x23sf_command',0,b'\x00\x00\x25\x23sf_error',0,b'\x00\x00\x1D\x23sf_error_number',0,b'\x00\x00\x28\x23sf_error_str',0,b'\x00\x00\x22\x23sf_format_check',0,b'\x00\x00\x19\x23sf_get_string',0,b'\x00\x00\x06\x23sf_open',0,b'\x00\x00\x0B\x23sf_open_fd',0,b'\x00\x00\x00\x23sf_open_virtual',0,b'\x00\x00\x25\x23sf_perror',0,b'\x00\x00\x38\x23sf_read_double',0,b'\x00\x00\x3D\x23sf_read_float',0,b'\x00\x00\x42\x23sf_read_int',0,b'\x00\x00\x51\x23sf_read_raw',0,b'\x00\x00\x4C\x23sf_read_short',0,b'\x00\x00\x51\x23sf_readf_double',0,b'\x00\x00\x51\x23sf_readf_float',0,b'\x00\x00\x51\x23sf_readf_int',0,b'\x00\x00\x51\x23sf_readf_short',0,b'\x00\x00\x47\x23sf_seek',0,b'\x00\x00\x2D\x23sf_set_string',0,b'\x00\x00\x16\x23sf_strerror',0,b'\x00\x00\x20\x23sf_version_string',0,b'\x00\x00\x11\x23sf_wchar_open',0,b'\x00\x00\x38\x23sf_write_double',0,b'\x00\x00\x3D\x23sf_write_float',0,b'\x00\x00\x42\x23sf_write_int',0,b'\x00\x00\x51\x23sf_write_raw',0,b'\x00\x00\x4C\x23sf_write_short',0,b'\x00\x00\x68\x23sf_write_sync',0,b'\x00\x00\x51\x23sf_writef_double',0,b'\x00\x00\x51\x23sf_writef_float',0,b'\x00\x00\x51\x23sf_writef_int',0,b'\x00\x00\x51\x23sf_writef_short',0),
8
+ _struct_unions = ((b'\x00\x00\x00\x6B\x00\x00\x00\x02SF_FORMAT_INFO',b'\x00\x00\x02\x11format',b'\x00\x00\x07\x11name',b'\x00\x00\x07\x11extension'),(b'\x00\x00\x00\x6C\x00\x00\x00\x02SF_INFO',b'\x00\x00\x3B\x11frames',b'\x00\x00\x02\x11samplerate',b'\x00\x00\x02\x11channels',b'\x00\x00\x02\x11format',b'\x00\x00\x02\x11sections',b'\x00\x00\x02\x11seekable'),(b'\x00\x00\x00\x6D\x00\x00\x00\x02SF_VIRTUAL_IO',b'\x00\x00\x76\x11get_filelen',b'\x00\x00\x75\x11seek',b'\x00\x00\x77\x11read',b'\x00\x00\x78\x11write',b'\x00\x00\x76\x11tell'),(b'\x00\x00\x00\x6E\x00\x00\x00\x10SNDFILE_tag',)),
9
+ _enums = (b'\x00\x00\x00\x71\x00\x00\x00\x16$1\x00SF_FORMAT_SUBMASK,SF_FORMAT_TYPEMASK,SF_FORMAT_ENDMASK',b'\x00\x00\x00\x72\x00\x00\x00\x16$2\x00SFC_GET_LIB_VERSION,SFC_GET_LOG_INFO,SFC_GET_FORMAT_INFO,SFC_GET_FORMAT_MAJOR_COUNT,SFC_GET_FORMAT_MAJOR,SFC_GET_FORMAT_SUBTYPE_COUNT,SFC_GET_FORMAT_SUBTYPE,SFC_FILE_TRUNCATE,SFC_SET_CLIPPING,SFC_SET_SCALE_FLOAT_INT_READ,SFC_SET_SCALE_INT_FLOAT_WRITE,SFC_SET_COMPRESSION_LEVEL,SFC_SET_BITRATE_MODE',b'\x00\x00\x00\x73\x00\x00\x00\x16$3\x00SF_FALSE,SF_TRUE,SFM_READ,SFM_WRITE,SFM_RDWR,SF_BITRATE_MODE_CONSTANT,SF_BITRATE_MODE_AVERAGE,SF_BITRATE_MODE_VARIABLE'),
10
+ _typenames = (b'\x00\x00\x00\x6BSF_FORMAT_INFO',b'\x00\x00\x00\x6CSF_INFO',b'\x00\x00\x00\x6DSF_VIRTUAL_IO',b'\x00\x00\x00\x6ESNDFILE',b'\x00\x00\x00\x3Bsf_count_t',b'\x00\x00\x00\x76sf_vio_get_filelen',b'\x00\x00\x00\x77sf_vio_read',b'\x00\x00\x00\x75sf_vio_seek',b'\x00\x00\x00\x76sf_vio_tell',b'\x00\x00\x00\x78sf_vio_write'),
11
+ )
python_embeded/Lib/site-packages/absl/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The Abseil Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = '2.3.0'
python_embeded/Lib/site-packages/absl/app.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The Abseil Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Generic entry point for Abseil Python applications.
16
+
17
+ To use this module, define a ``main`` function with a single ``argv`` argument
18
+ and call ``app.run(main)``. For example::
19
+
20
+ def main(argv):
21
+ if len(argv) > 1:
22
+ raise app.UsageError('Too many command-line arguments.')
23
+
24
+ if __name__ == '__main__':
25
+ app.run(main)
26
+ """
27
+
28
+ import collections
29
+ import errno
30
+ import os
31
+ import pdb
32
+ import sys
33
+ import textwrap
34
+ import traceback
35
+
36
+ from absl import command_name
37
+ from absl import flags
38
+ from absl import logging
39
+
40
+ try:
41
+ import faulthandler
42
+ except ImportError:
43
+ faulthandler = None
44
+
45
+ FLAGS = flags.FLAGS
46
+
47
+ flags.DEFINE_boolean('run_with_pdb', False, 'Set to true for PDB debug mode')
48
+ flags.DEFINE_boolean('pdb_post_mortem', False,
49
+ 'Set to true to handle uncaught exceptions with PDB '
50
+ 'post mortem.')
51
+ flags.DEFINE_alias('pdb', 'pdb_post_mortem')
52
+ flags.DEFINE_boolean('run_with_profiling', False,
53
+ 'Set to true for profiling the script. '
54
+ 'Execution will be slower, and the output format might '
55
+ 'change over time.')
56
+ flags.DEFINE_string('profile_file', None,
57
+ 'Dump profile information to a file (for python -m '
58
+ 'pstats). Implies --run_with_profiling.')
59
+ flags.DEFINE_boolean('use_cprofile_for_profiling', True,
60
+ 'Use cProfile instead of the profile module for '
61
+ 'profiling. This has no effect unless '
62
+ '--run_with_profiling is set.')
63
+ flags.DEFINE_boolean('only_check_args', False,
64
+ 'Set to true to validate args and exit.',
65
+ allow_hide_cpp=True)
66
+
67
+
68
+ # If main() exits via an abnormal exception, call into these
69
+ # handlers before exiting.
70
+ EXCEPTION_HANDLERS = []
71
+
72
+
73
+ class Error(Exception):
74
+ pass
75
+
76
+
77
+ class UsageError(Error):
78
+ """Exception raised when the arguments supplied by the user are invalid.
79
+
80
+ Raise this when the arguments supplied are invalid from the point of
81
+ view of the application. For example when two mutually exclusive
82
+ flags have been supplied or when there are not enough non-flag
83
+ arguments. It is distinct from flags.Error which covers the lower
84
+ level of parsing and validating individual flags.
85
+ """
86
+
87
+ def __init__(self, message, exitcode=1):
88
+ super().__init__(message)
89
+ self.exitcode = exitcode
90
+
91
+
92
+ class HelpFlag(flags.BooleanFlag):
93
+ """Special boolean flag that displays usage and raises SystemExit."""
94
+ NAME = 'help'
95
+ SHORT_NAME = '?'
96
+
97
+ def __init__(self):
98
+ super().__init__(
99
+ self.NAME,
100
+ False,
101
+ 'show this help',
102
+ short_name=self.SHORT_NAME,
103
+ allow_hide_cpp=True,
104
+ )
105
+
106
+ def parse(self, arg):
107
+ if self._parse(arg):
108
+ usage(shorthelp=True, writeto_stdout=True)
109
+ # Advertise --helpfull on stdout, since usage() was on stdout.
110
+ print()
111
+ print('Try --helpfull to get a list of all flags.')
112
+ sys.exit(1)
113
+
114
+
115
+ class HelpshortFlag(HelpFlag):
116
+ """--helpshort is an alias for --help."""
117
+ NAME = 'helpshort'
118
+ SHORT_NAME = None
119
+
120
+
121
+ class HelpfullFlag(flags.BooleanFlag):
122
+ """Display help for flags in the main module and all dependent modules."""
123
+
124
+ def __init__(self):
125
+ super().__init__('helpfull', False, 'show full help', allow_hide_cpp=True)
126
+
127
+ def parse(self, arg):
128
+ if self._parse(arg):
129
+ usage(writeto_stdout=True)
130
+ sys.exit(1)
131
+
132
+
133
+ class HelpXMLFlag(flags.BooleanFlag):
134
+ """Similar to HelpfullFlag, but generates output in XML format."""
135
+
136
+ def __init__(self):
137
+ super().__init__(
138
+ 'helpxml',
139
+ False,
140
+ 'like --helpfull, but generates XML output',
141
+ allow_hide_cpp=True,
142
+ )
143
+
144
+ def parse(self, arg):
145
+ if self._parse(arg):
146
+ flags.FLAGS.write_help_in_xml_format(sys.stdout)
147
+ sys.exit(1)
148
+
149
+
150
+ def parse_flags_with_usage(args):
151
+ """Tries to parse the flags, print usage, and exit if unparsable.
152
+
153
+ Args:
154
+ args: [str], a non-empty list of the command line arguments including
155
+ program name.
156
+
157
+ Returns:
158
+ [str], a non-empty list of remaining command line arguments after parsing
159
+ flags, including program name.
160
+ """
161
+ try:
162
+ return FLAGS(args)
163
+ except flags.Error as error:
164
+ message = str(error)
165
+ if '\n' in message:
166
+ final_message = 'FATAL Flags parsing error:\n%s\n' % textwrap.indent(
167
+ message, ' ')
168
+ else:
169
+ final_message = 'FATAL Flags parsing error: %s\n' % message
170
+ sys.stderr.write(final_message)
171
+ sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n')
172
+ sys.exit(1)
173
+
174
+
175
+ _define_help_flags_called = False
176
+
177
+
178
+ def define_help_flags():
179
+ """Registers help flags. Idempotent."""
180
+ # Use a global to ensure idempotence.
181
+ global _define_help_flags_called
182
+
183
+ if not _define_help_flags_called:
184
+ flags.DEFINE_flag(HelpFlag())
185
+ flags.DEFINE_flag(HelpshortFlag()) # alias for --help
186
+ flags.DEFINE_flag(HelpfullFlag())
187
+ flags.DEFINE_flag(HelpXMLFlag())
188
+ _define_help_flags_called = True
189
+
190
+
191
+ def _register_and_parse_flags_with_usage(
192
+ argv=None,
193
+ flags_parser=parse_flags_with_usage,
194
+ ):
195
+ """Registers help flags, parses arguments and shows usage if appropriate.
196
+
197
+ This also calls sys.exit(0) if flag --only_check_args is True.
198
+
199
+ Args:
200
+ argv: [str], a non-empty list of the command line arguments including
201
+ program name, sys.argv is used if None.
202
+ flags_parser: Callable[[List[str]], Any], the function used to parse flags.
203
+ The return value of this function is passed to `main` untouched. It must
204
+ guarantee FLAGS is parsed after this function is called.
205
+
206
+ Returns:
207
+ The return value of `flags_parser`. When using the default `flags_parser`,
208
+ it returns the following:
209
+ [str], a non-empty list of remaining command line arguments after parsing
210
+ flags, including program name.
211
+
212
+ Raises:
213
+ Error: Raised when flags_parser is called, but FLAGS is not parsed.
214
+ SystemError: Raised when it's called more than once.
215
+ """
216
+ # fmt: on
217
+ if _register_and_parse_flags_with_usage.done:
218
+ raise SystemError('Flag registration can be done only once.')
219
+
220
+ define_help_flags()
221
+
222
+ original_argv = sys.argv if argv is None else argv
223
+ args_to_main = flags_parser(original_argv)
224
+ if not FLAGS.is_parsed():
225
+ raise Error('FLAGS must be parsed after flags_parser is called.')
226
+
227
+ # Exit when told so.
228
+ if FLAGS.only_check_args:
229
+ sys.exit(0)
230
+ # Immediately after flags are parsed, bump verbosity to INFO if the flag has
231
+ # not been set.
232
+ if FLAGS['verbosity'].using_default_value:
233
+ FLAGS.verbosity = 0
234
+ _register_and_parse_flags_with_usage.done = True
235
+
236
+ return args_to_main
237
+
238
+ _register_and_parse_flags_with_usage.done = False
239
+
240
+
241
+ def _run_main(main, argv):
242
+ """Calls main, optionally with pdb or profiler."""
243
+ if FLAGS.run_with_pdb:
244
+ sys.exit(pdb.runcall(main, argv))
245
+ elif FLAGS.run_with_profiling or FLAGS.profile_file:
246
+ # Avoid import overhead since most apps (including performance-sensitive
247
+ # ones) won't be run with profiling.
248
+ # pylint: disable=g-import-not-at-top
249
+ import atexit
250
+ if FLAGS.use_cprofile_for_profiling:
251
+ import cProfile as profile
252
+ else:
253
+ import profile
254
+ profiler = profile.Profile()
255
+ if FLAGS.profile_file:
256
+ atexit.register(profiler.dump_stats, FLAGS.profile_file)
257
+ else:
258
+ atexit.register(profiler.print_stats)
259
+ sys.exit(profiler.runcall(main, argv))
260
+ else:
261
+ sys.exit(main(argv))
262
+
263
+
264
+ def _call_exception_handlers(exception):
265
+ """Calls any installed exception handlers."""
266
+ for handler in EXCEPTION_HANDLERS:
267
+ try:
268
+ if handler.wants(exception):
269
+ handler.handle(exception)
270
+ except: # pylint: disable=bare-except
271
+ try:
272
+ # We don't want to stop for exceptions in the exception handlers but
273
+ # we shouldn't hide them either.
274
+ logging.error(traceback.format_exc())
275
+ except: # pylint: disable=bare-except
276
+ # In case even the logging statement fails, ignore.
277
+ pass
278
+
279
+
280
+ def run(
281
+ main,
282
+ argv=None,
283
+ flags_parser=parse_flags_with_usage,
284
+ ):
285
+ """Begins executing the program.
286
+
287
+ Args:
288
+ main: The main function to execute. It takes an single argument "argv",
289
+ which is a list of command line arguments with parsed flags removed.
290
+ The return value is passed to `sys.exit`, and so for example
291
+ a return value of 0 or None results in a successful termination, whereas
292
+ a return value of 1 results in abnormal termination.
293
+ For more details, see https://docs.python.org/3/library/sys#sys.exit
294
+ argv: A non-empty list of the command line arguments including program name,
295
+ sys.argv is used if None.
296
+ flags_parser: Callable[[List[str]], Any], the function used to parse flags.
297
+ The return value of this function is passed to `main` untouched.
298
+ It must guarantee FLAGS is parsed after this function is called.
299
+ Should be passed as a keyword-only arg which will become mandatory in a
300
+ future release.
301
+ - Parses command line flags with the flag module.
302
+ - If there are any errors, prints usage().
303
+ - Calls main() with the remaining arguments.
304
+ - If main() raises a UsageError, prints usage and the error message.
305
+ """
306
+ # fmt: on
307
+ try:
308
+ args = _run_init(
309
+ sys.argv if argv is None else argv,
310
+ flags_parser,
311
+ )
312
+ while _init_callbacks:
313
+ callback = _init_callbacks.popleft()
314
+ callback()
315
+ try:
316
+ _run_main(main, args)
317
+ except UsageError as error:
318
+ usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode)
319
+ except:
320
+ exc = sys.exc_info()[1]
321
+ # Don't try to post-mortem debug successful SystemExits, since those
322
+ # mean there wasn't actually an error. In particular, the test framework
323
+ # raises SystemExit(False) even if all tests passed.
324
+ if isinstance(exc, SystemExit) and not exc.code:
325
+ raise
326
+
327
+ # Check the tty so that we don't hang waiting for input in an
328
+ # non-interactive scenario.
329
+ if FLAGS.pdb_post_mortem and sys.stdout.isatty():
330
+ traceback.print_exc()
331
+ print()
332
+ print(' *** Entering post-mortem debugging ***')
333
+ print()
334
+ pdb.post_mortem()
335
+ raise
336
+ except Exception as e:
337
+ _call_exception_handlers(e)
338
+ raise
339
+
340
+ # Callbacks which have been deferred until after _run_init has been called.
341
+ _init_callbacks = collections.deque()
342
+
343
+
344
+ def call_after_init(callback):
345
+ """Calls the given callback only once ABSL has finished initialization.
346
+
347
+ If ABSL has already finished initialization when ``call_after_init`` is
348
+ called then the callback is executed immediately, otherwise `callback` is
349
+ stored to be executed after ``app.run`` has finished initializing (aka. just
350
+ before the main function is called).
351
+
352
+ If called after ``app.run``, this is equivalent to calling ``callback()`` in
353
+ the caller thread. If called before ``app.run``, callbacks are run
354
+ sequentially (in an undefined order) in the same thread as ``app.run``.
355
+
356
+ Args:
357
+ callback: a callable to be called once ABSL has finished initialization.
358
+ This may be immediate if initialization has already finished. It
359
+ takes no arguments and returns nothing.
360
+ """
361
+ if _run_init.done:
362
+ callback()
363
+ else:
364
+ _init_callbacks.append(callback)
365
+
366
+
367
+ def _run_init(
368
+ argv,
369
+ flags_parser,
370
+ ):
371
+ """Does one-time initialization and re-parses flags on rerun."""
372
+ if _run_init.done:
373
+ return flags_parser(argv)
374
+ command_name.make_process_name_useful()
375
+ # Set up absl logging handler.
376
+ logging.use_absl_handler()
377
+ args = _register_and_parse_flags_with_usage(
378
+ argv=argv,
379
+ flags_parser=flags_parser,
380
+ )
381
+ if faulthandler:
382
+ try:
383
+ faulthandler.enable()
384
+ except Exception: # pylint: disable=broad-except
385
+ # Some tests verify stderr output very closely, so don't print anything.
386
+ # Disabled faulthandler is a low-impact error.
387
+ pass
388
+ _run_init.done = True
389
+ return args
390
+
391
+
392
+ _run_init.done = False
393
+
394
+
395
+ def usage(shorthelp=False, writeto_stdout=False, detailed_error=None,
396
+ exitcode=None):
397
+ """Writes __main__'s docstring to stderr with some help text.
398
+
399
+ Args:
400
+ shorthelp: bool, if True, prints only flags from the main module,
401
+ rather than all flags.
402
+ writeto_stdout: bool, if True, writes help message to stdout,
403
+ rather than to stderr.
404
+ detailed_error: str, additional detail about why usage info was presented.
405
+ exitcode: optional integer, if set, exits with this status code after
406
+ writing help.
407
+ """
408
+ if writeto_stdout:
409
+ stdfile = sys.stdout
410
+ else:
411
+ stdfile = sys.stderr
412
+
413
+ doc = sys.modules['__main__'].__doc__
414
+ if not doc:
415
+ doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
416
+ doc = flags.text_wrap(doc, indent=' ', firstline_indent='')
417
+ else:
418
+ # Replace all '%s' with sys.argv[0], and all '%%' with '%'.
419
+ num_specifiers = doc.count('%') - 2 * doc.count('%%')
420
+ try:
421
+ doc %= (sys.argv[0],) * num_specifiers
422
+ except (OverflowError, TypeError, ValueError):
423
+ # Just display the docstring as-is.
424
+ pass
425
+ if shorthelp:
426
+ flag_str = FLAGS.main_module_help()
427
+ else:
428
+ flag_str = FLAGS.get_help()
429
+ try:
430
+ stdfile.write(doc)
431
+ if flag_str:
432
+ stdfile.write('\nflags:\n')
433
+ stdfile.write(flag_str)
434
+ stdfile.write('\n')
435
+ if detailed_error is not None:
436
+ stdfile.write('\n%s\n' % detailed_error)
437
+ except OSError as e:
438
+ # We avoid printing a huge backtrace if we get EPIPE, because
439
+ # "foo.par --help | less" is a frequent use case.
440
+ if e.errno != errno.EPIPE:
441
+ raise
442
+ if exitcode is not None:
443
+ sys.exit(exitcode)
444
+
445
+
446
+ class ExceptionHandler:
447
+ """Base exception handler from which other may inherit."""
448
+
449
+ def wants(self, exc):
450
+ """Returns whether this handler wants to handle the exception or not.
451
+
452
+ This base class returns True for all exceptions by default. Override in
453
+ subclass if it wants to be more selective.
454
+
455
+ Args:
456
+ exc: Exception, the current exception.
457
+ """
458
+ del exc # Unused.
459
+ return True
460
+
461
+ def handle(self, exc):
462
+ """Do something with the current exception.
463
+
464
+ Args:
465
+ exc: Exception, the current exception
466
+
467
+ This method must be overridden.
468
+ """
469
+ raise NotImplementedError()
470
+
471
+
472
+ def install_exception_handler(handler):
473
+ """Installs an exception handler.
474
+
475
+ Args:
476
+ handler: ExceptionHandler, the exception handler to install.
477
+
478
+ Raises:
479
+ TypeError: Raised when the handler was not of the correct type.
480
+
481
+ All installed exception handlers will be called if main() exits via
482
+ an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt,
483
+ FlagsError or UsageError.
484
+ """
485
+ if not isinstance(handler, ExceptionHandler):
486
+ raise TypeError('handler of type %s does not inherit from ExceptionHandler'
487
+ % type(handler))
488
+ EXCEPTION_HANDLERS.append(handler)
python_embeded/Lib/site-packages/absl/app.pyi ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Collection, Iterable, List, NoReturn, Optional, TypeVar, Union, overload
2
+
3
+ from absl.flags import _flag
4
+
5
+ _MainArgs = TypeVar('_MainArgs')
6
+ _Exc = TypeVar('_Exc', bound=Exception)
7
+
8
+ class ExceptionHandler():
9
+
10
+ def wants(self, exc: _Exc) -> bool:
11
+ ...
12
+
13
+ def handle(self, exc: _Exc):
14
+ ...
15
+
16
+ EXCEPTION_HANDLERS: List[ExceptionHandler] = ...
17
+
18
+ class HelpFlag(_flag.BooleanFlag):
19
+ def __init__(self):
20
+ ...
21
+
22
+ class HelpshortFlag(HelpFlag):
23
+ ...
24
+
25
+ class HelpfullFlag(_flag.BooleanFlag):
26
+ def __init__(self):
27
+ ...
28
+
29
+ class HelpXMLFlag(_flag.BooleanFlag):
30
+ def __init__(self):
31
+ ...
32
+
33
+ def define_help_flags() -> None:
34
+ ...
35
+
36
+ @overload
37
+ def usage(shorthelp: Union[bool, int] = ...,
38
+ writeto_stdout: Union[bool, int] = ...,
39
+ detailed_error: Optional[Any] = ...,
40
+ exitcode: None = ...) -> None:
41
+ ...
42
+
43
+ @overload
44
+ def usage(shorthelp: Union[bool, int],
45
+ writeto_stdout: Union[bool, int],
46
+ detailed_error: Optional[Any],
47
+ exitcode: int) -> NoReturn:
48
+ ...
49
+
50
+ @overload
51
+ def usage(shorthelp: Union[bool, int] = ...,
52
+ writeto_stdout: Union[bool, int] = ...,
53
+ detailed_error: Optional[Any] = ...,
54
+ *,
55
+ exitcode: int) -> NoReturn:
56
+ ...
57
+
58
+ def install_exception_handler(handler: ExceptionHandler) -> None:
59
+ ...
60
+
61
+ class Error(Exception):
62
+ ...
63
+
64
+ class UsageError(Error):
65
+ exitcode: int
66
+
67
+ def parse_flags_with_usage(args: List[str]) -> List[str]:
68
+ ...
69
+
70
+ def call_after_init(callback: Callable[[], Any]) -> None:
71
+ ...
72
+
73
+ # Without the flag_parser argument, `main` should require a List[str].
74
+ @overload
75
+ def run(
76
+ main: Callable[[List[str]], Any],
77
+ argv: Optional[List[str]] = ...,
78
+ ) -> NoReturn:
79
+ ...
80
+
81
+ @overload
82
+ def run(
83
+ main: Callable[[_MainArgs], Any],
84
+ argv: Optional[List[str]] = ...,
85
+ *,
86
+ flags_parser: Callable[[List[str]], _MainArgs],
87
+ ) -> NoReturn:
88
+ ...
python_embeded/Lib/site-packages/absl/py.typed ADDED
File without changes
python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/METADATA ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: absl-py
3
+ Version: 2.3.0
4
+ Summary: Abseil Python Common Libraries, see https://github.com/abseil/abseil-py.
5
+ Project-URL: Homepage, https://github.com/abseil/abseil-py
6
+ Author: The Abseil Authors
7
+ License-Expression: Apache-2.0
8
+ License-File: AUTHORS
9
+ License-File: LICENSE
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Abseil Python Common Libraries
26
+
27
+ This repository is a collection of Python library code for building Python
28
+ applications. The code is collected from Google's own Python code base, and has
29
+ been extensively tested and used in production.
30
+
31
+ ## Features
32
+
33
+ * Simple application startup
34
+ * Distributed commandline flags system
35
+ * Custom logging module with additional features
36
+ * Testing utilities
37
+
38
+ ## Getting Started
39
+
40
+ ### Installation
41
+
42
+ To install the package, simply run:
43
+
44
+ ```bash
45
+ pip install absl-py
46
+ ```
47
+
48
+ Or install from source:
49
+
50
+ ```bash
51
+ pip install .
52
+ ```
53
+
54
+ ### Running Tests
55
+
56
+ To run Abseil tests, you can clone the git repo and run
57
+ [bazel](https://bazel.build/):
58
+
59
+ ```bash
60
+ git clone https://github.com/abseil/abseil-py.git
61
+ cd abseil-py
62
+ bazel test absl/...
63
+ ```
64
+
65
+ Please also validate the type annotations against the latest mypy:
66
+
67
+ ```bash
68
+ pip install mypy
69
+ mypy absl
70
+ ```
71
+
72
+ ### Example Code
73
+
74
+ Please refer to
75
+ [smoke_tests/sample_app.py](https://github.com/abseil/abseil-py/blob/main/smoke_tests/sample_app.py)
76
+ as an example to get started.
77
+
78
+ ## Documentation
79
+
80
+ See the [Abseil Python Developer Guide](https://abseil.io/docs/python/).
81
+
82
+ ## Future Releases
83
+
84
+ The current repository includes an initial set of libraries for early adoption.
85
+ More components and interoperability with Abseil C++ Common Libraries
86
+ will come in future releases.
87
+
88
+ ## License
89
+
90
+ The Abseil Python library is licensed under the terms of the Apache
91
+ license. See [LICENSE](LICENSE) for more information.
python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/RECORD ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl/__init__.py,sha256=SHpa5c7ayI8Qh7DokzatR_WrOjrLuuMpyjM9jcIzqTs,607
2
+ absl/__pycache__/__init__.cpython-312.pyc,,
3
+ absl/__pycache__/app.cpython-312.pyc,,
4
+ absl/__pycache__/command_name.cpython-312.pyc,,
5
+ absl/app.py,sha256=0WJpjLaYcgcXtl9NTn-i5jSEfAoweMg4SXAel2XLF0Y,15360
6
+ absl/app.pyi,sha256=NdRh0OBqWHKnc3hEjdLaspLdu6aDHn3XP360ZPZeQE8,1885
7
+ absl/command_name.py,sha256=FgWUMHmlX0yQxEuMPXxFxn5ayWWZSLB0cq8Vx361TpU,2283
8
+ absl/flags/__init__.py,sha256=n_uLeSK-15_1DKLb0wXivmt6A8xvADDC87D1yoJdqVU,7665
9
+ absl/flags/__pycache__/__init__.cpython-312.pyc,,
10
+ absl/flags/__pycache__/_argument_parser.cpython-312.pyc,,
11
+ absl/flags/__pycache__/_defines.cpython-312.pyc,,
12
+ absl/flags/__pycache__/_exceptions.cpython-312.pyc,,
13
+ absl/flags/__pycache__/_flag.cpython-312.pyc,,
14
+ absl/flags/__pycache__/_flagvalues.cpython-312.pyc,,
15
+ absl/flags/__pycache__/_helpers.cpython-312.pyc,,
16
+ absl/flags/__pycache__/_validators.cpython-312.pyc,,
17
+ absl/flags/__pycache__/_validators_classes.cpython-312.pyc,,
18
+ absl/flags/__pycache__/argparse_flags.cpython-312.pyc,,
19
+ absl/flags/_argument_parser.py,sha256=arzkHA3CbPJdJ7diqUyskdoaLtKt8Aij1EZCVH_qJHU,20629
20
+ absl/flags/_defines.py,sha256=NMQ6bxt2pYeJcJtyw9HTLCnqkSRRujisWDnIqFfZKzY,52864
21
+ absl/flags/_exceptions.py,sha256=FZzlzhvkjqPImTxXqbS1pSPYKr_TvtOd5ellvoiVLDI,3619
22
+ absl/flags/_flag.py,sha256=mdMJFklKQdCi9WsWPvUlmBRoQ2IAPW0Z0lDIKj0Lsx8,20079
23
+ absl/flags/_flagvalues.py,sha256=cGzMsWxthqGYfpESReRSJCXjpRujosSmTT-efJW3CbQ,54364
24
+ absl/flags/_helpers.py,sha256=TZW-gHwQIJae1D9ZX7RJZ9uSxp_rswH7r8bei3c07EI,14181
25
+ absl/flags/_validators.py,sha256=VcsJtZzohliNxsI974NECYpeozD8rswHNHXggrQ4BLo,14140
26
+ absl/flags/_validators_classes.py,sha256=PGUWzO7v3wPOHb9leIKKzry3q-pPeKCoMB_O7prLdnY,6093
27
+ absl/flags/argparse_flags.py,sha256=usJudgMpy3P6Vvq7-LmJNa2Rj3ygHM3hwDTGd1mbAzc,14386
28
+ absl/logging/__init__.py,sha256=Sr4yZRudS-65keej89EuTrXSz_WU7-NFy6HB6ejBwuk,43773
29
+ absl/logging/__init__.pyi,sha256=8CtWTjE6rgjozuYPevqsdz9oH357kG2H2y6ClZZWijY,5962
30
+ absl/logging/__pycache__/__init__.cpython-312.pyc,,
31
+ absl/logging/__pycache__/converter.cpython-312.pyc,,
32
+ absl/logging/converter.py,sha256=6eBymfv9UNkog0BGat4HPWlxC_oSqvHcQ46jnSdtaMg,6323
33
+ absl/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
+ absl/testing/__init__.py,sha256=7cM57swk2T1Hc5wxmt-JpcaR6xfdPJyL_lyRqgODvuM,584
35
+ absl/testing/__pycache__/__init__.cpython-312.pyc,,
36
+ absl/testing/__pycache__/_bazelize_command.cpython-312.pyc,,
37
+ absl/testing/__pycache__/_pretty_print_reporter.cpython-312.pyc,,
38
+ absl/testing/__pycache__/absltest.cpython-312.pyc,,
39
+ absl/testing/__pycache__/flagsaver.cpython-312.pyc,,
40
+ absl/testing/__pycache__/parameterized.cpython-312.pyc,,
41
+ absl/testing/__pycache__/xml_reporter.cpython-312.pyc,,
42
+ absl/testing/_bazelize_command.py,sha256=qpioV02ln2sBBJ9kdlHgNpKk8_wxdz2hJGKbG6EWZMI,2287
43
+ absl/testing/_pretty_print_reporter.py,sha256=PZh9NXSXBbXDi0FOk-BOmpse8LXa92Er16tgyBRogMs,3065
44
+ absl/testing/absltest.py,sha256=lEgFNDiG7NHlOJs6tubFZlcbFYcsjomJaPighXBtb7Q,105889
45
+ absl/testing/flagsaver.py,sha256=HIWzFyayy-Pa8TqTAXF7BtHQ7s9Uk68KE8AVVAM0o0w,13346
46
+ absl/testing/parameterized.py,sha256=TpTlWTUXjikGeUDE45AgubvnmHsPbFNj-wUtAwT-e6E,27817
47
+ absl/testing/xml_reporter.py,sha256=YFkM7SROW8aeoCCn8IsGZ4cqXu4x8MwL1oN42-OtPKI,21430
48
+ absl_py-2.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
49
+ absl_py-2.3.0.dist-info/METADATA,sha256=NL4blIf7trzaL9oRKFkp6J4OXU3IxqliiKm9I1YgSGk,2433
50
+ absl_py-2.3.0.dist-info/RECORD,,
51
+ absl_py-2.3.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
52
+ absl_py-2.3.0.dist-info/licenses/AUTHORS,sha256=YoLudsylaQg7W5mLn4FroQMuEnuNx8RpQrhkd_xvv6U,296
53
+ absl_py-2.3.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
python_embeded/Lib/site-packages/absl_py-2.3.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/METADATA ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: accelerate
3
+ Version: 1.8.1
4
+ Summary: Accelerate
5
+ Home-page: https://github.com/huggingface/accelerate
6
+ Author: The HuggingFace team
7
+ Author-email: zach.mueller@huggingface.co
8
+ License: Apache
9
+ Keywords: deep learning
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.9.0
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy<3.0.0,>=1.17
23
+ Requires-Dist: packaging>=20.0
24
+ Requires-Dist: psutil
25
+ Requires-Dist: pyyaml
26
+ Requires-Dist: torch>=2.0.0
27
+ Requires-Dist: huggingface_hub>=0.21.0
28
+ Requires-Dist: safetensors>=0.4.3
29
+ Provides-Extra: quality
30
+ Requires-Dist: black~=23.1; extra == "quality"
31
+ Requires-Dist: hf-doc-builder>=0.3.0; extra == "quality"
32
+ Requires-Dist: ruff~=0.11.2; extra == "quality"
33
+ Provides-Extra: docs
34
+ Provides-Extra: test-prod
35
+ Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "test-prod"
36
+ Requires-Dist: pytest-xdist; extra == "test-prod"
37
+ Requires-Dist: pytest-subtests; extra == "test-prod"
38
+ Requires-Dist: parameterized; extra == "test-prod"
39
+ Requires-Dist: pytest-order; extra == "test-prod"
40
+ Provides-Extra: test-dev
41
+ Requires-Dist: datasets; extra == "test-dev"
42
+ Requires-Dist: diffusers; extra == "test-dev"
43
+ Requires-Dist: evaluate; extra == "test-dev"
44
+ Requires-Dist: torchdata>=0.8.0; extra == "test-dev"
45
+ Requires-Dist: torchpippy>=0.2.0; extra == "test-dev"
46
+ Requires-Dist: transformers; extra == "test-dev"
47
+ Requires-Dist: scipy; extra == "test-dev"
48
+ Requires-Dist: scikit-learn; extra == "test-dev"
49
+ Requires-Dist: tqdm; extra == "test-dev"
50
+ Requires-Dist: bitsandbytes; extra == "test-dev"
51
+ Requires-Dist: timm; extra == "test-dev"
52
+ Provides-Extra: testing
53
+ Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "testing"
54
+ Requires-Dist: pytest-xdist; extra == "testing"
55
+ Requires-Dist: pytest-subtests; extra == "testing"
56
+ Requires-Dist: parameterized; extra == "testing"
57
+ Requires-Dist: pytest-order; extra == "testing"
58
+ Requires-Dist: datasets; extra == "testing"
59
+ Requires-Dist: diffusers; extra == "testing"
60
+ Requires-Dist: evaluate; extra == "testing"
61
+ Requires-Dist: torchdata>=0.8.0; extra == "testing"
62
+ Requires-Dist: torchpippy>=0.2.0; extra == "testing"
63
+ Requires-Dist: transformers; extra == "testing"
64
+ Requires-Dist: scipy; extra == "testing"
65
+ Requires-Dist: scikit-learn; extra == "testing"
66
+ Requires-Dist: tqdm; extra == "testing"
67
+ Requires-Dist: bitsandbytes; extra == "testing"
68
+ Requires-Dist: timm; extra == "testing"
69
+ Provides-Extra: deepspeed
70
+ Requires-Dist: deepspeed; extra == "deepspeed"
71
+ Provides-Extra: rich
72
+ Requires-Dist: rich; extra == "rich"
73
+ Provides-Extra: test-fp8
74
+ Requires-Dist: torchao; extra == "test-fp8"
75
+ Provides-Extra: test-trackers
76
+ Requires-Dist: wandb; extra == "test-trackers"
77
+ Requires-Dist: comet-ml; extra == "test-trackers"
78
+ Requires-Dist: tensorboard; extra == "test-trackers"
79
+ Requires-Dist: dvclive; extra == "test-trackers"
80
+ Requires-Dist: mlflow; extra == "test-trackers"
81
+ Requires-Dist: matplotlib; extra == "test-trackers"
82
+ Requires-Dist: swanlab; extra == "test-trackers"
83
+ Provides-Extra: dev
84
+ Requires-Dist: black~=23.1; extra == "dev"
85
+ Requires-Dist: hf-doc-builder>=0.3.0; extra == "dev"
86
+ Requires-Dist: ruff~=0.11.2; extra == "dev"
87
+ Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "dev"
88
+ Requires-Dist: pytest-xdist; extra == "dev"
89
+ Requires-Dist: pytest-subtests; extra == "dev"
90
+ Requires-Dist: parameterized; extra == "dev"
91
+ Requires-Dist: pytest-order; extra == "dev"
92
+ Requires-Dist: datasets; extra == "dev"
93
+ Requires-Dist: diffusers; extra == "dev"
94
+ Requires-Dist: evaluate; extra == "dev"
95
+ Requires-Dist: torchdata>=0.8.0; extra == "dev"
96
+ Requires-Dist: torchpippy>=0.2.0; extra == "dev"
97
+ Requires-Dist: transformers; extra == "dev"
98
+ Requires-Dist: scipy; extra == "dev"
99
+ Requires-Dist: scikit-learn; extra == "dev"
100
+ Requires-Dist: tqdm; extra == "dev"
101
+ Requires-Dist: bitsandbytes; extra == "dev"
102
+ Requires-Dist: timm; extra == "dev"
103
+ Requires-Dist: rich; extra == "dev"
104
+ Provides-Extra: sagemaker
105
+ Requires-Dist: sagemaker; extra == "sagemaker"
106
+ Dynamic: author
107
+ Dynamic: author-email
108
+ Dynamic: classifier
109
+ Dynamic: description
110
+ Dynamic: description-content-type
111
+ Dynamic: home-page
112
+ Dynamic: keywords
113
+ Dynamic: license
114
+ Dynamic: license-file
115
+ Dynamic: provides-extra
116
+ Dynamic: requires-dist
117
+ Dynamic: requires-python
118
+ Dynamic: summary
119
+
120
+ <!---
121
+ Copyright 2021 The HuggingFace Team. All rights reserved.
122
+
123
+ Licensed under the Apache License, Version 2.0 (the "License");
124
+ you may not use this file except in compliance with the License.
125
+ You may obtain a copy of the License at
126
+
127
+ http://www.apache.org/licenses/LICENSE-2.0
128
+
129
+ Unless required by applicable law or agreed to in writing, software
130
+ distributed under the License is distributed on an "AS IS" BASIS,
131
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
132
+ See the License for the specific language governing permissions and
133
+ limitations under the License.
134
+ -->
135
+
136
+ <p align="center">
137
+ <br>
138
+ <img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png" width="400"/>
139
+ <br>
140
+ <p>
141
+
142
+ <p align="center">
143
+ <!-- Uncomment when CircleCI is set up
144
+ <a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a>
145
+ -->
146
+ <a href="https://github.com/huggingface/accelerate/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue"></a>
147
+ <a href="https://huggingface.co/docs/accelerate/index.html"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/accelerate/index.html.svg?down_color=red&down_message=offline&up_message=online"></a>
148
+ <a href="https://github.com/huggingface/accelerate/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg"></a>
149
+ <a href="https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
150
+ </p>
151
+
152
+ <h3 align="center">
153
+ <p>Run your *raw* PyTorch training script on any kind of device
154
+ </h3>
155
+
156
+ <h3 align="center">
157
+ <a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a>
158
+ </h3>
159
+
160
+ ## Easy to integrate
161
+
162
+ 🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16.
163
+
164
+ 🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.
165
+
166
+ Here is an example:
167
+
168
+ ```diff
169
+ import torch
170
+ import torch.nn.functional as F
171
+ from datasets import load_dataset
172
+ + from accelerate import Accelerator
173
+
174
+ + accelerator = Accelerator()
175
+ - device = 'cpu'
176
+ + device = accelerator.device
177
+
178
+ model = torch.nn.Transformer().to(device)
179
+ optimizer = torch.optim.Adam(model.parameters())
180
+
181
+ dataset = load_dataset('my_dataset')
182
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
183
+
184
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
185
+
186
+ model.train()
187
+ for epoch in range(10):
188
+ for source, targets in data:
189
+ source = source.to(device)
190
+ targets = targets.to(device)
191
+
192
+ optimizer.zero_grad()
193
+
194
+ output = model(source)
195
+ loss = F.cross_entropy(output, targets)
196
+
197
+ - loss.backward()
198
+ + accelerator.backward(loss)
199
+
200
+ optimizer.step()
201
+ ```
202
+
203
+ As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16).
204
+
205
+ In particular, the same code can then be run without modification on your local machine for debugging or your training environment.
206
+
207
+ 🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further:
208
+
209
+ ```diff
210
+ import torch
211
+ import torch.nn.functional as F
212
+ from datasets import load_dataset
213
+ + from accelerate import Accelerator
214
+
215
+ - device = 'cpu'
216
+ + accelerator = Accelerator()
217
+
218
+ - model = torch.nn.Transformer().to(device)
219
+ + model = torch.nn.Transformer()
220
+ optimizer = torch.optim.Adam(model.parameters())
221
+
222
+ dataset = load_dataset('my_dataset')
223
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
224
+
225
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
226
+
227
+ model.train()
228
+ for epoch in range(10):
229
+ for source, targets in data:
230
+ - source = source.to(device)
231
+ - targets = targets.to(device)
232
+
233
+ optimizer.zero_grad()
234
+
235
+ output = model(source)
236
+ loss = F.cross_entropy(output, targets)
237
+
238
+ - loss.backward()
239
+ + accelerator.backward(loss)
240
+
241
+ optimizer.step()
242
+ ```
243
+
244
+ Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
245
+
246
+ ## Launching script
247
+
248
+ 🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training!
249
+ On your machine(s) just run:
250
+
251
+ ```bash
252
+ accelerate config
253
+ ```
254
+
255
+ and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
256
+
257
+ ```bash
258
+ accelerate launch my_script.py --args_to_my_script
259
+ ```
260
+
261
+ For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
262
+
263
+ ```bash
264
+ accelerate launch examples/nlp_example.py
265
+ ```
266
+
267
+ This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.
268
+
269
+ You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`.
270
+
271
+ For example, here is how to launch on two GPUs:
272
+
273
+ ```bash
274
+ accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py
275
+ ```
276
+
277
+ To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).
278
+
279
+ Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)
280
+
281
+ ## Launching multi-CPU run using MPI
282
+
283
+ 🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well.
284
+ Once you have MPI setup on your cluster, just run:
285
+ ```bash
286
+ accelerate config
287
+ ```
288
+ Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun.
289
+ Then, use `accelerate launch` with your script like:
290
+ ```bash
291
+ accelerate launch examples/nlp_example.py
292
+ ```
293
+ Alternatively, you can use mpirun directly, without using the CLI like:
294
+ ```bash
295
+ mpirun -np 2 python examples/nlp_example.py
296
+ ```
297
+
298
+ ## Launching training using DeepSpeed
299
+
300
+ 🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`.
301
+
302
+ ```python
303
+ from accelerate import Accelerator, DeepSpeedPlugin
304
+
305
+ # deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it
306
+ # Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed
307
+ deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
308
+ accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin)
309
+
310
+ # How to save your 🤗 Transformer?
311
+ accelerator.wait_for_everyone()
312
+ unwrapped_model = accelerator.unwrap_model(model)
313
+ unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))
314
+ ```
315
+
316
+ Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.
317
+
318
+ ## Launching your training from a notebook
319
+
320
+ 🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add:
321
+
322
+ ```python
323
+ from accelerate import notebook_launcher
324
+
325
+ notebook_launcher(training_function)
326
+ ```
327
+
328
+ An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
329
+
330
+ ## Why should I use 🤗 Accelerate?
331
+
332
+ You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object.
333
+
334
+ ## Why shouldn't I use 🤗 Accelerate?
335
+
336
+ You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them.
337
+
338
+ ## Frameworks using 🤗 Accelerate
339
+
340
+ If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below:
341
+
342
+ * [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development.
343
+ * [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76).
344
+ * [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic.
345
+ * [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms.
346
+ * [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses.
347
+ * [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products.
348
+ * [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library.
349
+ * [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so.
350
+ * [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves!
351
+ * [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion.
352
+ * [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric.
353
+ * [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side).
354
+
355
+
356
+ ## Installation
357
+
358
+ This repository is tested on Python 3.8+ and PyTorch 1.10.0+
359
+
360
+ You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
361
+
362
+ First, create a virtual environment with the version of Python you're going to use and activate it.
363
+
364
+ Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows:
365
+
366
+ ```bash
367
+ pip install accelerate
368
+ ```
369
+
370
+ ## Supported integrations
371
+
372
+ - CPU only
373
+ - multi-CPU on one node (machine)
374
+ - multi-CPU on several nodes (machines)
375
+ - single GPU
376
+ - multi-GPU on one node (machine)
377
+ - multi-GPU on several nodes (machines)
378
+ - TPU
379
+ - FP16/BFloat16 mixed precision
380
+ - FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)
381
+ - DeepSpeed support (Experimental)
382
+ - PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)
383
+ - Megatron-LM support (Experimental)
384
+
385
+ ## Citing 🤗 Accelerate
386
+
387
+ If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
388
+
389
+ ```bibtex
390
+ @Misc{accelerate,
391
+ title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.},
392
+ author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},
393
+ howpublished = {\url{https://github.com/huggingface/accelerate}},
394
+ year = {2022}
395
+ }
396
+ ```
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/RECORD ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../Scripts/accelerate-config.exe,sha256=vDJVBj82VElT8MZ3Dr0wbwna04mitROjqdGbfEFEduk,108427
2
+ ../../Scripts/accelerate-estimate-memory.exe,sha256=SRB7ylFz4ZBHB1-70C1B1Xy2WmraThUpjdoc3Y__mRQ,108429
3
+ ../../Scripts/accelerate-launch.exe,sha256=HfAg0r0WG3puCpnOrADrz4yGJe_kCLkoitpXKdWUV9s,108427
4
+ ../../Scripts/accelerate-merge-weights.exe,sha256=ve1Tc-HBDFmmaySRzwnoWobBt6I2xXJQmsBBHK8KkrY,108426
5
+ ../../Scripts/accelerate.exe,sha256=tjsAPQ823ovQLAzwNslJslWWYspfLJlGKo3lDZTKIak,108435
6
+ accelerate-1.8.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
7
+ accelerate-1.8.1.dist-info/METADATA,sha256=VUDv08VTjcXDNtu0bFGUz11j_VBolsghyrYwaBrDUyM,19817
8
+ accelerate-1.8.1.dist-info/RECORD,,
9
+ accelerate-1.8.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ accelerate-1.8.1.dist-info/WHEEL,sha256=lTU6B6eIfYoiQJTZNc-fyaR6BpL6ehTzU3xGYxn2n8k,91
11
+ accelerate-1.8.1.dist-info/entry_points.txt,sha256=Vpy8gUGfZ-1VnM2229fb8CpJNLBdMH_wtJ9PQ7b_2tQ,296
12
+ accelerate-1.8.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
13
+ accelerate-1.8.1.dist-info/top_level.txt,sha256=esVfdxTidsjQ90zsN_rPpjLFJ4ijRlx4mnLrG09hlt4,11
14
+ accelerate/__init__.py,sha256=x-IpfrXM6_IliRXhu0SgO4DkU_r7EMSnScbEswWPbBU,1504
15
+ accelerate/__pycache__/__init__.cpython-312.pyc,,
16
+ accelerate/__pycache__/accelerator.cpython-312.pyc,,
17
+ accelerate/__pycache__/big_modeling.cpython-312.pyc,,
18
+ accelerate/__pycache__/checkpointing.cpython-312.pyc,,
19
+ accelerate/__pycache__/data_loader.cpython-312.pyc,,
20
+ accelerate/__pycache__/hooks.cpython-312.pyc,,
21
+ accelerate/__pycache__/inference.cpython-312.pyc,,
22
+ accelerate/__pycache__/launchers.cpython-312.pyc,,
23
+ accelerate/__pycache__/local_sgd.cpython-312.pyc,,
24
+ accelerate/__pycache__/logging.cpython-312.pyc,,
25
+ accelerate/__pycache__/memory_utils.cpython-312.pyc,,
26
+ accelerate/__pycache__/optimizer.cpython-312.pyc,,
27
+ accelerate/__pycache__/scheduler.cpython-312.pyc,,
28
+ accelerate/__pycache__/state.cpython-312.pyc,,
29
+ accelerate/__pycache__/tracking.cpython-312.pyc,,
30
+ accelerate/accelerator.py,sha256=Rq60sftkvjpiBlBLfhvWlvXuGFfSXwBLEIqeHECrAQg,179209
31
+ accelerate/big_modeling.py,sha256=bqqO4Lw00YErTup7MUM6saOVHRFvMNOdNqAwg96fBG0,34765
32
+ accelerate/checkpointing.py,sha256=ARi8ZNFlLQW2uz9hd2D5-5rRUNoY2zL7BSe8HQKBFjs,13957
33
+ accelerate/commands/__init__.py,sha256=m1PPTDT4ziIAvM0-FDSgIMIZ69Konn126s6LwuzH6v8,606
34
+ accelerate/commands/__pycache__/__init__.cpython-312.pyc,,
35
+ accelerate/commands/__pycache__/accelerate_cli.cpython-312.pyc,,
36
+ accelerate/commands/__pycache__/env.cpython-312.pyc,,
37
+ accelerate/commands/__pycache__/estimate.cpython-312.pyc,,
38
+ accelerate/commands/__pycache__/launch.cpython-312.pyc,,
39
+ accelerate/commands/__pycache__/merge.cpython-312.pyc,,
40
+ accelerate/commands/__pycache__/test.cpython-312.pyc,,
41
+ accelerate/commands/__pycache__/to_fsdp2.cpython-312.pyc,,
42
+ accelerate/commands/__pycache__/tpu.cpython-312.pyc,,
43
+ accelerate/commands/__pycache__/utils.cpython-312.pyc,,
44
+ accelerate/commands/accelerate_cli.py,sha256=SkwFad6Z1ZsGjtm7TiXFq8je-akshp_0WxX_6rGSBw8,1972
45
+ accelerate/commands/config/__init__.py,sha256=iJK8dgj3pc5Vdr1E7UuGoFu-BlybyXLxYDoTg9gXngE,1645
46
+ accelerate/commands/config/__pycache__/__init__.cpython-312.pyc,,
47
+ accelerate/commands/config/__pycache__/cluster.cpython-312.pyc,,
48
+ accelerate/commands/config/__pycache__/config.cpython-312.pyc,,
49
+ accelerate/commands/config/__pycache__/config_args.cpython-312.pyc,,
50
+ accelerate/commands/config/__pycache__/config_utils.cpython-312.pyc,,
51
+ accelerate/commands/config/__pycache__/default.cpython-312.pyc,,
52
+ accelerate/commands/config/__pycache__/sagemaker.cpython-312.pyc,,
53
+ accelerate/commands/config/__pycache__/update.cpython-312.pyc,,
54
+ accelerate/commands/config/cluster.py,sha256=Ln8AbiHX0fDLYV8Gxk3WjC2JL94CEAjuhhn6BKdQ1zE,37544
55
+ accelerate/commands/config/config.py,sha256=FuRlQvOjgATEtyqOSsGD-KEtOCvACOHjs2C-krrtldk,3035
56
+ accelerate/commands/config/config_args.py,sha256=hJo7E3J_T7MPNkgtyNjPilJuH-wJK09mGWF6CvGFYIQ,9970
57
+ accelerate/commands/config/config_utils.py,sha256=lbV9iKAVSF5bUyQDGpzFduhH5JENYgAilPpRLLlCEq8,3299
58
+ accelerate/commands/config/default.py,sha256=UY0dQ7w1peBkQe8QDCm3XJrTnsRcm_G-_hf44NzNAbU,6213
59
+ accelerate/commands/config/sagemaker.py,sha256=SRLup9XrV_Z-23A3d8gZbkqbonDcscMDDmbpmytCzbY,10636
60
+ accelerate/commands/config/update.py,sha256=NXW1J7GkUHpg71QlIXsmMB_0z8S8IZo2FWax5POwrhc,2395
61
+ accelerate/commands/env.py,sha256=gRGwtPhMMWmZ5NTMaMrgHXaOzBV6SvAtP78TuuJvC6g,4336
62
+ accelerate/commands/estimate.py,sha256=Qduq4xudVyIede37BMEe1rNhXf-rfW-MHV2KtwxdfEA,12585
63
+ accelerate/commands/launch.py,sha256=h-d1W1y6NEwciGdzeLY-aTQG2N6dx3iBgcwSZZ_Yjn0,46889
64
+ accelerate/commands/menu/__init__.py,sha256=uqSlBM0TFHBwzdv3p3SXfpAk1lZFp4h1a7mbBdscPHs,645
65
+ accelerate/commands/menu/__pycache__/__init__.cpython-312.pyc,,
66
+ accelerate/commands/menu/__pycache__/cursor.cpython-312.pyc,,
67
+ accelerate/commands/menu/__pycache__/helpers.cpython-312.pyc,,
68
+ accelerate/commands/menu/__pycache__/input.cpython-312.pyc,,
69
+ accelerate/commands/menu/__pycache__/keymap.cpython-312.pyc,,
70
+ accelerate/commands/menu/__pycache__/selection_menu.cpython-312.pyc,,
71
+ accelerate/commands/menu/cursor.py,sha256=-lmpJVAzvNc0c3EOtSuLoKB59zqylVCbYyWLPnrOmvQ,2028
72
+ accelerate/commands/menu/helpers.py,sha256=KrSB5fJjH4MUEUAQJ6bYaN16AYcnl9UalDrPD3DYeeg,1483
73
+ accelerate/commands/menu/input.py,sha256=T8Mdd-Y_OURgqfDV9qZh4Wf6hmT22AneNtJzj4JA1Rk,2512
74
+ accelerate/commands/menu/keymap.py,sha256=eXj-suyYs1m5dEHoUKN4mKAMLc8DWHnwhP6G6JSU0jQ,4086
75
+ accelerate/commands/menu/selection_menu.py,sha256=bxy-DHaKKC6SCToOlMBv5_z0MdUzylEg6Sio9OuV3GM,4921
76
+ accelerate/commands/merge.py,sha256=3Uo14LADvk8RJwZ_i6kIsGwWB3Ul5y8Uq47oHkDYqKU,2387
77
+ accelerate/commands/test.py,sha256=YrPYEaAACOGZ6btn2MV6NbMSEdBUcMWADLbQWaZSHtk,2149
78
+ accelerate/commands/to_fsdp2.py,sha256=gfbhoUT4qFB3LVDMNmckElgLG0yWm8aj_aofszeiJmM,5991
79
+ accelerate/commands/tpu.py,sha256=KyxDP7IuveidZrbW4rx2s8Ku3o_ptI6tzwr_R7ck0os,5548
80
+ accelerate/commands/utils.py,sha256=aT8xUCe2pCkFII7yZxcfaohEjgBAzMUM7WiD4UuWSOY,4150
81
+ accelerate/data_loader.py,sha256=PUvNjsxrgYXxvPOqArRpYATFrbeC7rXzBpQOuDJuZ_U,65294
82
+ accelerate/hooks.py,sha256=y4eN7blCjOkXY9_mVBmkgiTKqJfasAKrHOddEHj91Vg,33293
83
+ accelerate/inference.py,sha256=NLANdzXm5PwmDWbPYkFmoRoQSLLvuhfvIG33xfpapT0,7668
84
+ accelerate/launchers.py,sha256=GCj7y4qgK34k-VWi6EeM0DvXfsHBeGOZBfgTv9wi1zE,13724
85
+ accelerate/local_sgd.py,sha256=aCj_yqXK_FhhZRWEpzXIkgXBERH6fC3HyrC3nsOj1uA,4160
86
+ accelerate/logging.py,sha256=4XcgY_BV7Qn_enh2tZ-8fNtuaE_3n-LsYJbgwhRx_PI,5042
87
+ accelerate/memory_utils.py,sha256=3R5LoeHl6GgTZ-IMPrDZMdaEehWarGdPqODushb-6pg,862
88
+ accelerate/optimizer.py,sha256=p5qfCOMi8DAjvx6eECypo4ej3pvmQ_U_bgmrEAKc4hY,8158
89
+ accelerate/scheduler.py,sha256=des_4M_Tt1W8gCYZZbLla0GHBEgJY3Wx2EGBQPTzeiY,4238
90
+ accelerate/state.py,sha256=NpBKZQAn1FsrVVC0j_s_JocrVa-XWPQAxwog6cwNvw4,56351
91
+ accelerate/test_utils/__init__.py,sha256=ROl3bvBqmuI6ueRlPRNkNC-83yb6u6z_FFzrHJtq8rM,1809
92
+ accelerate/test_utils/__pycache__/__init__.cpython-312.pyc,,
93
+ accelerate/test_utils/__pycache__/examples.cpython-312.pyc,,
94
+ accelerate/test_utils/__pycache__/testing.cpython-312.pyc,,
95
+ accelerate/test_utils/__pycache__/training.cpython-312.pyc,,
96
+ accelerate/test_utils/examples.py,sha256=CO3SlkkrORUjroreoPfBPwfcNCDlHSgNWIt81iz2oQ8,7257
97
+ accelerate/test_utils/scripts/__init__.py,sha256=m1PPTDT4ziIAvM0-FDSgIMIZ69Konn126s6LwuzH6v8,606
98
+ accelerate/test_utils/scripts/__pycache__/__init__.cpython-312.pyc,,
99
+ accelerate/test_utils/scripts/__pycache__/test_cli.cpython-312.pyc,,
100
+ accelerate/test_utils/scripts/__pycache__/test_ddp_comm_hook.cpython-312.pyc,,
101
+ accelerate/test_utils/scripts/__pycache__/test_distributed_data_loop.cpython-312.pyc,,
102
+ accelerate/test_utils/scripts/__pycache__/test_merge_weights.cpython-312.pyc,,
103
+ accelerate/test_utils/scripts/__pycache__/test_notebook.cpython-312.pyc,,
104
+ accelerate/test_utils/scripts/__pycache__/test_ops.cpython-312.pyc,,
105
+ accelerate/test_utils/scripts/__pycache__/test_script.cpython-312.pyc,,
106
+ accelerate/test_utils/scripts/__pycache__/test_sync.cpython-312.pyc,,
107
+ accelerate/test_utils/scripts/external_deps/__init__.py,sha256=m1PPTDT4ziIAvM0-FDSgIMIZ69Konn126s6LwuzH6v8,606
108
+ accelerate/test_utils/scripts/external_deps/__pycache__/__init__.cpython-312.pyc,,
109
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_checkpointing.cpython-312.pyc,,
110
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_ds_multiple_model.cpython-312.pyc,,
111
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_metrics.cpython-312.pyc,,
112
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_peak_memory_usage.cpython-312.pyc,,
113
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_performance.cpython-312.pyc,,
114
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_pippy.cpython-312.pyc,,
115
+ accelerate/test_utils/scripts/external_deps/__pycache__/test_zero3_integration.cpython-312.pyc,,
116
+ accelerate/test_utils/scripts/external_deps/test_checkpointing.py,sha256=XHaNRmnrARd1izXFjWGi5UjYGas-4vqayW51jAHBPCA,10699
117
+ accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py,sha256=Cg4-h0B4UcOQ5CxXjIdrsPVR5fFsWCv24DqZGjXEwW8,13790
118
+ accelerate/test_utils/scripts/external_deps/test_metrics.py,sha256=Ev2XKaiwmznoxKujskAAuISGChW646MOiyf0CXEPb9Y,12168
119
+ accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py,sha256=9Yn9Rc7d-yWr1fU0RagASPG5l8vrKeHVYbuYABbA-fU,12498
120
+ accelerate/test_utils/scripts/external_deps/test_performance.py,sha256=4SW108BHEdpzDA_VY4B0GKKAdms4QxVlVywhZ-CZwRI,11721
121
+ accelerate/test_utils/scripts/external_deps/test_pippy.py,sha256=rYF5bqSCe_pfylxDv2_2Q7S2mHIb9_6fGns-IcLgE_E,4789
122
+ accelerate/test_utils/scripts/external_deps/test_zero3_integration.py,sha256=P9alBOHZ9Lfqs5LoRP7bCbXl-tnsNrBkvJZGseibBeA,1665
123
+ accelerate/test_utils/scripts/test_cli.py,sha256=-p78NTJgKdeTNDqyrQuGEZZqMpnzdUHPyWZ05FMl5EI,1081
124
+ accelerate/test_utils/scripts/test_ddp_comm_hook.py,sha256=k_-2MBjLKNdMGIcneTbuGd84K05Wp1GEQX6DUVF9UBw,3566
125
+ accelerate/test_utils/scripts/test_distributed_data_loop.py,sha256=RUWTwd7DIpr2fl7JtKOsvTjMiJioTxO8FdSr2Lw_5uI,15137
126
+ accelerate/test_utils/scripts/test_merge_weights.py,sha256=UQa5cR_gZK94fNuopsQ4FEAfTNEsTnlepCxXhboGEOg,6144
127
+ accelerate/test_utils/scripts/test_notebook.py,sha256=qfIy3IvH74-kGn8nadBn_k7qrviqvsxy5ijsnUhuY6o,3894
128
+ accelerate/test_utils/scripts/test_ops.py,sha256=Bcs-h8EMJwULTfbizlFN5qkv3JraWEpoSZWMn-HswiI,6265
129
+ accelerate/test_utils/scripts/test_script.py,sha256=zns5-YNj5h3YHBk79XisiqDQfX2nl9UL8K_NS5IoqFg,36446
130
+ accelerate/test_utils/scripts/test_sync.py,sha256=PDe8sYZLCL2LKjj_L9b-Bh2BjAjeii9EZ8sZNfuYx5s,18817
131
+ accelerate/test_utils/testing.py,sha256=Q3kzLnpna3YhAyM6fUDQ7477LtJN9Qb0bNgj6b6V6ik,29241
132
+ accelerate/test_utils/training.py,sha256=jO5YEIr34jAcnJ_9WNp_x3zuHzSam_I6IgMvmcGm7yI,6456
133
+ accelerate/tracking.py,sha256=Bc5DPSIlexbiV4SryKl-UxwH1CeEnOZkbGwYvvwLfmw,48032
134
+ accelerate/utils/__init__.py,sha256=xl6E87k9XJH4imIBQ61Qaip0_1JWx9Or2_tCmSHrTJI,7980
135
+ accelerate/utils/__pycache__/__init__.cpython-312.pyc,,
136
+ accelerate/utils/__pycache__/ao.cpython-312.pyc,,
137
+ accelerate/utils/__pycache__/bnb.cpython-312.pyc,,
138
+ accelerate/utils/__pycache__/constants.cpython-312.pyc,,
139
+ accelerate/utils/__pycache__/dataclasses.cpython-312.pyc,,
140
+ accelerate/utils/__pycache__/deepspeed.cpython-312.pyc,,
141
+ accelerate/utils/__pycache__/environment.cpython-312.pyc,,
142
+ accelerate/utils/__pycache__/fsdp_utils.cpython-312.pyc,,
143
+ accelerate/utils/__pycache__/imports.cpython-312.pyc,,
144
+ accelerate/utils/__pycache__/launch.cpython-312.pyc,,
145
+ accelerate/utils/__pycache__/megatron_lm.cpython-312.pyc,,
146
+ accelerate/utils/__pycache__/memory.cpython-312.pyc,,
147
+ accelerate/utils/__pycache__/modeling.cpython-312.pyc,,
148
+ accelerate/utils/__pycache__/offload.cpython-312.pyc,,
149
+ accelerate/utils/__pycache__/operations.cpython-312.pyc,,
150
+ accelerate/utils/__pycache__/other.cpython-312.pyc,,
151
+ accelerate/utils/__pycache__/random.cpython-312.pyc,,
152
+ accelerate/utils/__pycache__/rich.cpython-312.pyc,,
153
+ accelerate/utils/__pycache__/torch_xla.cpython-312.pyc,,
154
+ accelerate/utils/__pycache__/tqdm.cpython-312.pyc,,
155
+ accelerate/utils/__pycache__/transformer_engine.cpython-312.pyc,,
156
+ accelerate/utils/__pycache__/versions.cpython-312.pyc,,
157
+ accelerate/utils/ao.py,sha256=yfi84ywNpXsKZ6di4jbmtd6bIvRi9bmygr3giN92_Pg,4777
158
+ accelerate/utils/bnb.py,sha256=PdgdXwjhQ4Sg9orj4hlUiMQlPxSsdsiNfFVq4yBtl-g,20651
159
+ accelerate/utils/constants.py,sha256=A5KmcIry76B9p4Fa8CuI5ugv7bVcyTc5g4IBU1cvky0,3516
160
+ accelerate/utils/dataclasses.py,sha256=ByhYIuIRt92un7Uj9Lr3gbClBzsOaGBnNvgpaBlF2-k,134173
161
+ accelerate/utils/deepspeed.py,sha256=gt-jwOpOtRs6N4sohuSO2I3x1qLoO6uYYjnPrKp6Zk4,14796
162
+ accelerate/utils/environment.py,sha256=h0zacbBkAp9szltTf5-aTr5NcbVsQp7wl6DFWp8XNuI,15257
163
+ accelerate/utils/fsdp_utils.py,sha256=uBd3bovBPxa2gt5Q-L-7isvsZdi2b7_2H8jzm8dfHsw,36206
164
+ accelerate/utils/imports.py,sha256=w4DqTh21D_rsCBdifSm27vrilk_VZtMPWvf1U439qhs,16598
165
+ accelerate/utils/launch.py,sha256=-QfklFN8U0U37dQZiz70GGTFSQ0vzadBW7ZFShJykrc,33406
166
+ accelerate/utils/megatron_lm.py,sha256=ZMxcYAdGnMWla2PtB04ctb9mhMfKUP8qLYusGNjyScU,58054
167
+ accelerate/utils/memory.py,sha256=CDG80xzDQfQOqhP56jZ5xVN5bLIgNDqj0TtcoiidvhY,7201
168
+ accelerate/utils/modeling.py,sha256=m3ZSeTZjI83MpdtGK9hdtp3jyGAIKn3tPymHAAM-mJU,94721
169
+ accelerate/utils/offload.py,sha256=VFaL8oSJzqZ_47VuUQ69xZi9bF2heRSFoOSnnOxbGXc,7825
170
+ accelerate/utils/operations.py,sha256=84SpXwKsbNHHePboL9gUqK6bA5vo0kyH_gLAdwnzE_s,31266
171
+ accelerate/utils/other.py,sha256=LQTH_iRAGyTeGZS19y-1hyJTboFN2n-2sqd8fc_Bats,19676
172
+ accelerate/utils/random.py,sha256=Xv_ZJm9eaC2Q7rgZy9OpOunKuTingMiDQCH00qhNVxE,6220
173
+ accelerate/utils/rich.py,sha256=8JZX_uGMQX-BufdXxJpdne7BWd1KyLHSgbiGxrDMYr8,847
174
+ accelerate/utils/torch_xla.py,sha256=Pq1tuqN0X_pWDVza6YgjfO45uoJdoRVRForLeLQzFus,1908
175
+ accelerate/utils/tqdm.py,sha256=k8e9JnieTEQHCCNBaiBys7hPxWlEbyRASdIma-qy_X8,1657
176
+ accelerate/utils/transformer_engine.py,sha256=PENq1zhDzENnFFfV4hLzhZiiLo28tQFvmuhpQPlc3S0,6594
177
+ accelerate/utils/versions.py,sha256=UgmcbjBm--6CIx1ZamSAMjAK_B_2l48LbeaNygqej8M,2149
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/REQUESTED ADDED
File without changes
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [console_scripts]
2
+ accelerate = accelerate.commands.accelerate_cli:main
3
+ accelerate-config = accelerate.commands.config:main
4
+ accelerate-estimate-memory = accelerate.commands.estimate:main
5
+ accelerate-launch = accelerate.commands.launch:main
6
+ accelerate-merge-weights = accelerate.commands.merge:main
python_embeded/Lib/site-packages/accelerate-1.8.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ accelerate
python_embeded/Lib/site-packages/accelerate/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ __version__ = "1.8.1"
15
+
16
+ from .accelerator import Accelerator
17
+ from .big_modeling import (
18
+ cpu_offload,
19
+ cpu_offload_with_hook,
20
+ disk_offload,
21
+ dispatch_model,
22
+ init_empty_weights,
23
+ init_on_device,
24
+ load_checkpoint_and_dispatch,
25
+ )
26
+ from .data_loader import skip_first_batches
27
+ from .inference import prepare_pippy
28
+ from .launchers import debug_launcher, notebook_launcher
29
+ from .state import PartialState
30
+ from .utils import (
31
+ AutocastKwargs,
32
+ DataLoaderConfiguration,
33
+ DDPCommunicationHookType,
34
+ DeepSpeedPlugin,
35
+ DistributedDataParallelKwargs,
36
+ DistributedType,
37
+ FullyShardedDataParallelPlugin,
38
+ GradScalerKwargs,
39
+ InitProcessGroupKwargs,
40
+ ProfileKwargs,
41
+ find_executable_batch_size,
42
+ infer_auto_device_map,
43
+ is_rich_available,
44
+ load_checkpoint_in_model,
45
+ synchronize_rng_states,
46
+ )
47
+
48
+
49
+ if is_rich_available():
50
+ from .utils import rich
python_embeded/Lib/site-packages/accelerate/accelerator.py ADDED
The diff for this file is too large to render. See raw diff
 
python_embeded/Lib/site-packages/accelerate/big_modeling.py ADDED
@@ -0,0 +1,749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import os
17
+ import re
18
+ from contextlib import contextmanager
19
+ from functools import wraps
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from .hooks import (
26
+ AlignDevicesHook,
27
+ CpuOffload,
28
+ LayerwiseCastingHook,
29
+ UserCpuOffloadHook,
30
+ add_hook_to_module,
31
+ attach_align_device_hook,
32
+ attach_align_device_hook_on_blocks,
33
+ )
34
+ from .utils import (
35
+ OffloadedWeightsLoader,
36
+ check_cuda_p2p_ib_support,
37
+ check_device_map,
38
+ extract_submodules_state_dict,
39
+ find_tied_parameters,
40
+ get_balanced_memory,
41
+ infer_auto_device_map,
42
+ is_bnb_available,
43
+ is_mlu_available,
44
+ is_musa_available,
45
+ is_npu_available,
46
+ is_sdaa_available,
47
+ is_xpu_available,
48
+ load_checkpoint_in_model,
49
+ offload_state_dict,
50
+ parse_flag_from_env,
51
+ retie_parameters,
52
+ )
53
+ from .utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING
54
+ from .utils.other import recursive_getattr
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ @contextmanager
61
+ def init_empty_weights(include_buffers: bool = None):
62
+ """
63
+ A context manager under which models are initialized with all parameters on the meta device, therefore creating an
64
+ empty model. Useful when just initializing the model would blow the available RAM.
65
+
66
+ Args:
67
+ include_buffers (`bool`, *optional*):
68
+ Whether or not to also put all buffers on the meta device while initializing.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ import torch.nn as nn
74
+ from accelerate import init_empty_weights
75
+
76
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
77
+ with init_empty_weights():
78
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
79
+ ```
80
+
81
+ <Tip warning={true}>
82
+
83
+ Any model created under this context manager has no weights. As such you can't do something like
84
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
85
+ Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not
86
+ called.
87
+
88
+ </Tip>
89
+ """
90
+ if include_buffers is None:
91
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
92
+ with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
93
+ yield f
94
+
95
+
96
+ @contextmanager
97
+ def init_on_device(device: torch.device, include_buffers: bool = None):
98
+ """
99
+ A context manager under which models are initialized with all parameters on the specified device.
100
+
101
+ Args:
102
+ device (`torch.device`):
103
+ Device to initialize all parameters on.
104
+ include_buffers (`bool`, *optional*):
105
+ Whether or not to also put all buffers on the meta device while initializing.
106
+
107
+ Example:
108
+
109
+ ```python
110
+ import torch.nn as nn
111
+ from accelerate import init_on_device
112
+
113
+ with init_on_device(device=torch.device("cuda")):
114
+ tst = nn.Linear(100, 100) # on `cuda` device
115
+ ```
116
+ """
117
+ if include_buffers is None:
118
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
119
+
120
+ if include_buffers:
121
+ with device:
122
+ yield
123
+ return
124
+
125
+ old_register_parameter = nn.Module.register_parameter
126
+ if include_buffers:
127
+ old_register_buffer = nn.Module.register_buffer
128
+
129
+ def register_empty_parameter(module, name, param):
130
+ old_register_parameter(module, name, param)
131
+ if param is not None:
132
+ param_cls = type(module._parameters[name])
133
+ kwargs = module._parameters[name].__dict__
134
+ kwargs["requires_grad"] = param.requires_grad
135
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
136
+
137
+ def register_empty_buffer(module, name, buffer, persistent=True):
138
+ old_register_buffer(module, name, buffer, persistent=persistent)
139
+ if buffer is not None:
140
+ module._buffers[name] = module._buffers[name].to(device)
141
+
142
+ # Patch tensor creation
143
+ if include_buffers:
144
+ tensor_constructors_to_patch = {
145
+ torch_function_name: getattr(torch, torch_function_name)
146
+ for torch_function_name in ["empty", "zeros", "ones", "full"]
147
+ }
148
+ else:
149
+ tensor_constructors_to_patch = {}
150
+
151
+ def patch_tensor_constructor(fn):
152
+ def wrapper(*args, **kwargs):
153
+ kwargs["device"] = device
154
+ return fn(*args, **kwargs)
155
+
156
+ return wrapper
157
+
158
+ try:
159
+ nn.Module.register_parameter = register_empty_parameter
160
+ if include_buffers:
161
+ nn.Module.register_buffer = register_empty_buffer
162
+ for torch_function_name in tensor_constructors_to_patch.keys():
163
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
164
+ yield
165
+ finally:
166
+ nn.Module.register_parameter = old_register_parameter
167
+ if include_buffers:
168
+ nn.Module.register_buffer = old_register_buffer
169
+ for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
170
+ setattr(torch, torch_function_name, old_torch_function)
171
+
172
+
173
+ def cpu_offload(
174
+ model: nn.Module,
175
+ execution_device: Optional[torch.device] = None,
176
+ offload_buffers: bool = False,
177
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
178
+ preload_module_classes: Optional[list[str]] = None,
179
+ ):
180
+ """
181
+ Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one
182
+ copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that
183
+ state dict and put on the execution device passed as they are needed, then offloaded again.
184
+
185
+ Args:
186
+ model (`torch.nn.Module`):
187
+ The model to offload.
188
+ execution_device (`torch.device`, *optional*):
189
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
190
+ model first parameter device.
191
+ offload_buffers (`bool`, *optional*, defaults to `False`):
192
+ Whether or not to offload the buffers with the model parameters.
193
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
194
+ The state dict of the model that will be kept on CPU.
195
+ preload_module_classes (`List[str]`, *optional*):
196
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
197
+ of the forward. This should only be used for classes that have submodules which are registered but not
198
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
199
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
200
+ """
201
+ if execution_device is None:
202
+ execution_device = next(iter(model.parameters())).device
203
+ if state_dict is None:
204
+ state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()}
205
+
206
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
207
+ attach_align_device_hook(
208
+ model,
209
+ execution_device=execution_device,
210
+ offload=True,
211
+ offload_buffers=offload_buffers,
212
+ weights_map=state_dict,
213
+ preload_module_classes=preload_module_classes,
214
+ )
215
+
216
+ return model
217
+
218
+
219
+ def cpu_offload_with_hook(
220
+ model: torch.nn.Module,
221
+ execution_device: Optional[Union[int, str, torch.device]] = None,
222
+ prev_module_hook: Optional[UserCpuOffloadHook] = None,
223
+ ):
224
+ """
225
+ Offloads a model on the CPU and puts it back to an execution device when executed. The difference with
226
+ [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when
227
+ the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop.
228
+
229
+ Args:
230
+ model (`torch.nn.Module`):
231
+ The model to offload.
232
+ execution_device(`str`, `int` or `torch.device`, *optional*):
233
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
234
+ GPU 0 if there is a GPU, and finally to the CPU.
235
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
236
+ The hook sent back by this function for a previous model in the pipeline you are running. If passed, its
237
+ offload method will be called just before the forward of the model to which this hook is attached.
238
+
239
+ Example:
240
+
241
+ ```py
242
+ model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device)
243
+ model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1)
244
+ model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2)
245
+
246
+ hid_1 = model_1(input)
247
+ for i in range(50):
248
+ # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop.
249
+ hid_2 = model_2(hid_1)
250
+ # model2 is offloaded to the CPU just before this forward.
251
+ hid_3 = model_3(hid_3)
252
+
253
+ # For model3, you need to manually call the hook offload method.
254
+ hook_3.offload()
255
+ ```
256
+ """
257
+ hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook)
258
+ add_hook_to_module(model, hook, append=True)
259
+ user_hook = UserCpuOffloadHook(model, hook)
260
+ return model, user_hook
261
+
262
+
263
+ def disk_offload(
264
+ model: nn.Module,
265
+ offload_dir: Union[str, os.PathLike],
266
+ execution_device: Optional[torch.device] = None,
267
+ offload_buffers: bool = False,
268
+ preload_module_classes: Optional[list[str]] = None,
269
+ ):
270
+ """
271
+ Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as
272
+ memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and
273
+ put on the execution device passed as they are needed, then offloaded again.
274
+
275
+ Args:
276
+ model (`torch.nn.Module`): The model to offload.
277
+ offload_dir (`str` or `os.PathLike`):
278
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
279
+ execution_device (`torch.device`, *optional*):
280
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
281
+ model's first parameter device.
282
+ offload_buffers (`bool`, *optional*, defaults to `False`):
283
+ Whether or not to offload the buffers with the model parameters.
284
+ preload_module_classes (`List[str]`, *optional*):
285
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
286
+ of the forward. This should only be used for classes that have submodules which are registered but not
287
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
288
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
289
+ """
290
+ if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")):
291
+ offload_state_dict(offload_dir, model.state_dict())
292
+ if execution_device is None:
293
+ execution_device = next(iter(model.parameters())).device
294
+ weights_map = OffloadedWeightsLoader(save_folder=offload_dir)
295
+
296
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
297
+ attach_align_device_hook(
298
+ model,
299
+ execution_device=execution_device,
300
+ offload=True,
301
+ offload_buffers=offload_buffers,
302
+ weights_map=weights_map,
303
+ preload_module_classes=preload_module_classes,
304
+ )
305
+
306
+ return model
307
+
308
+
309
+ def dispatch_model(
310
+ model: nn.Module,
311
+ device_map: dict[str, Union[str, int, torch.device]],
312
+ main_device: Optional[torch.device] = None,
313
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
314
+ offload_dir: Optional[Union[str, os.PathLike]] = None,
315
+ offload_index: Optional[dict[str, str]] = None,
316
+ offload_buffers: bool = False,
317
+ skip_keys: Optional[Union[str, list[str]]] = None,
318
+ preload_module_classes: Optional[list[str]] = None,
319
+ force_hooks: bool = False,
320
+ ):
321
+ """
322
+ Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on
323
+ the CPU or even the disk.
324
+
325
+ Args:
326
+ model (`torch.nn.Module`):
327
+ The model to dispatch.
328
+ device_map (`Dict[str, Union[str, int, torch.device]]`):
329
+ A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that
330
+ `"disk"` is accepted even if it's not a proper value for `torch.device`.
331
+ main_device (`str`, `int` or `torch.device`, *optional*):
332
+ The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or
333
+ `"disk"`.
334
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
335
+ The state dict of the part of the model that will be kept on CPU.
336
+ offload_dir (`str` or `os.PathLike`):
337
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
338
+ offload_index (`Dict`, *optional*):
339
+ A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default
340
+ to the index saved in `save_folder`.
341
+ offload_buffers (`bool`, *optional*, defaults to `False`):
342
+ Whether or not to offload the buffers with the model parameters.
343
+ skip_keys (`str` or `List[str]`, *optional*):
344
+ A list of keys to ignore when moving inputs or outputs between devices.
345
+ preload_module_classes (`List[str]`, *optional*):
346
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
347
+ of the forward. This should only be used for classes that have submodules which are registered but not
348
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
349
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
350
+ force_hooks (`bool`, *optional*, defaults to `False`):
351
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
352
+ single device.
353
+ """
354
+ # Error early if the device map is incomplete.
355
+ check_device_map(model, device_map)
356
+
357
+ # We need to force hook for quantized model that can't be moved with to()
358
+ if getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes":
359
+ # since bnb 0.43.2, we can move 4-bit model
360
+ if getattr(model, "is_loaded_in_8bit", False) or (
361
+ getattr(model, "is_loaded_in_4bit", False) and not is_bnb_available(min_version="0.43.2")
362
+ ):
363
+ force_hooks = True
364
+
365
+ # We attach hooks if the device_map has at least 2 different devices or if
366
+ # force_hooks is set to `True`. Otherwise, the model in already loaded
367
+ # in the unique device and the user can decide where to dispatch the model.
368
+ # If the model is quantized, we always force-dispatch the model
369
+ if (len(set(device_map.values())) > 1) or force_hooks:
370
+ if main_device is None:
371
+ if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}:
372
+ main_device = "cpu"
373
+ else:
374
+ main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0]
375
+
376
+ if main_device != "cpu":
377
+ cpu_modules = [name for name, device in device_map.items() if device == "cpu"]
378
+ if state_dict is None and len(cpu_modules) > 0:
379
+ state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules)
380
+
381
+ disk_modules = [name for name, device in device_map.items() if device == "disk"]
382
+ if offload_dir is None and offload_index is None and len(disk_modules) > 0:
383
+ raise ValueError(
384
+ "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules "
385
+ f"need to be offloaded: {', '.join(disk_modules)}."
386
+ )
387
+ if (
388
+ len(disk_modules) > 0
389
+ and offload_index is None
390
+ and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")))
391
+ ):
392
+ disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules)
393
+ offload_state_dict(offload_dir, disk_state_dict)
394
+
395
+ execution_device = {
396
+ name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items()
397
+ }
398
+ execution_device[""] = main_device
399
+ offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"]
400
+ offload = {name: device in offloaded_devices for name, device in device_map.items()}
401
+ save_folder = offload_dir if len(disk_modules) > 0 else None
402
+ if state_dict is not None or save_folder is not None or offload_index is not None:
403
+ device = main_device if offload_index is not None else None
404
+ weights_map = OffloadedWeightsLoader(
405
+ state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device
406
+ )
407
+ else:
408
+ weights_map = None
409
+
410
+ # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the
411
+ # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its
412
+ # original pointer) on each devices.
413
+ tied_params = find_tied_parameters(model)
414
+
415
+ tied_params_map = {}
416
+ for group in tied_params:
417
+ for param_name in group:
418
+ # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need
419
+ # to care about views of tensors through storage_offset.
420
+ data_ptr = recursive_getattr(model, param_name).data_ptr()
421
+ tied_params_map[data_ptr] = {}
422
+
423
+ # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer,
424
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
425
+
426
+ attach_align_device_hook_on_blocks(
427
+ model,
428
+ execution_device=execution_device,
429
+ offload=offload,
430
+ offload_buffers=offload_buffers,
431
+ weights_map=weights_map,
432
+ skip_keys=skip_keys,
433
+ preload_module_classes=preload_module_classes,
434
+ tied_params_map=tied_params_map,
435
+ )
436
+
437
+ # warn if there is any params on the meta device
438
+ offloaded_devices_str = " and ".join(
439
+ [device for device in set(device_map.values()) if device in ("cpu", "disk")]
440
+ )
441
+ if len(offloaded_devices_str) > 0:
442
+ logger.warning(
443
+ f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}."
444
+ )
445
+
446
+ # Attaching the hook may break tied weights, so we retie them
447
+ retie_parameters(model, tied_params)
448
+
449
+ # add warning to cuda and to method
450
+ def add_warning(fn, model):
451
+ @wraps(fn)
452
+ def wrapper(*args, **kwargs):
453
+ warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks."
454
+ if str(fn.__name__) == "to":
455
+ to_device = torch._C._nn._parse_to(*args, **kwargs)[0]
456
+ if to_device is not None:
457
+ logger.warning(warning_msg)
458
+ else:
459
+ logger.warning(warning_msg)
460
+ for param in model.parameters():
461
+ if param.device == torch.device("meta"):
462
+ raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.")
463
+ return fn(*args, **kwargs)
464
+
465
+ return wrapper
466
+
467
+ # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook
468
+ model.to = add_warning(model.to, model)
469
+ if is_npu_available():
470
+ model.npu = add_warning(model.npu, model)
471
+ elif is_mlu_available():
472
+ model.mlu = add_warning(model.mlu, model)
473
+ elif is_sdaa_available():
474
+ model.sdaa = add_warning(model.sdaa, model)
475
+ elif is_musa_available():
476
+ model.musa = add_warning(model.musa, model)
477
+ elif is_xpu_available():
478
+ model.xpu = add_warning(model.xpu, model)
479
+ else:
480
+ model.cuda = add_warning(model.cuda, model)
481
+
482
+ # Check if we are using multi-gpus with RTX 4000 series
483
+ use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1
484
+ if use_multi_gpu and not check_cuda_p2p_ib_support():
485
+ logger.warning(
486
+ "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. "
487
+ "This can affect the multi-gpu inference when using accelerate device_map."
488
+ "Please make sure to update your driver to the latest version which resolves this."
489
+ )
490
+ else:
491
+ device = list(device_map.values())[0]
492
+ # `torch.Tensor.to(<int num>)` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
493
+ if is_npu_available() and isinstance(device, int):
494
+ device = f"npu:{device}"
495
+ elif is_mlu_available() and isinstance(device, int):
496
+ device = f"mlu:{device}"
497
+ elif is_sdaa_available() and isinstance(device, int):
498
+ device = f"sdaa:{device}"
499
+ elif is_musa_available() and isinstance(device, int):
500
+ device = f"musa:{device}"
501
+ if device != "disk":
502
+ model.to(device)
503
+ else:
504
+ raise ValueError(
505
+ "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead."
506
+ )
507
+ # Convert OrderedDict back to dict for easier usage
508
+ model.hf_device_map = dict(device_map)
509
+ return model
510
+
511
+
512
+ def load_checkpoint_and_dispatch(
513
+ model: nn.Module,
514
+ checkpoint: Union[str, os.PathLike],
515
+ device_map: Optional[Union[str, dict[str, Union[int, str, torch.device]]]] = None,
516
+ max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None,
517
+ no_split_module_classes: Optional[list[str]] = None,
518
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
519
+ offload_buffers: bool = False,
520
+ dtype: Optional[Union[str, torch.dtype]] = None,
521
+ offload_state_dict: Optional[bool] = None,
522
+ skip_keys: Optional[Union[str, list[str]]] = None,
523
+ preload_module_classes: Optional[list[str]] = None,
524
+ force_hooks: bool = False,
525
+ strict: bool = False,
526
+ full_state_dict: bool = True,
527
+ broadcast_from_rank0: bool = False,
528
+ ):
529
+ """
530
+ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are
531
+ loaded and adds the various hooks that will make this model run properly (even if split across devices).
532
+
533
+ Args:
534
+ model (`torch.nn.Module`): The model in which we want to load a checkpoint.
535
+ checkpoint (`str` or `os.PathLike`):
536
+ The folder checkpoint to load. It can be:
537
+ - a path to a file containing a whole model state dict
538
+ - a path to a `.json` file containing the index to a sharded checkpoint
539
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
540
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
541
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
542
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
543
+
544
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more
545
+ information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map).
546
+ Defaults to None, which means [`dispatch_model`] will not be called.
547
+ max_memory (`Dict`, *optional*):
548
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU
549
+ and the available CPU RAM if unset.
550
+ no_split_module_classes (`List[str]`, *optional*):
551
+ A list of layer class names that should never be split across device (for instance any layer that has a
552
+ residual connection).
553
+ offload_folder (`str` or `os.PathLike`, *optional*):
554
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
555
+ offload_buffers (`bool`, *optional*, defaults to `False`):
556
+ In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as
557
+ well as the parameters.
558
+ dtype (`str` or `torch.dtype`, *optional*):
559
+ If provided, the weights will be converted to that type when loaded.
560
+ offload_state_dict (`bool`, *optional*):
561
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
562
+ the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map
563
+ picked contains `"disk"` values.
564
+ skip_keys (`str` or `List[str]`, *optional*):
565
+ A list of keys to ignore when moving inputs or outputs between devices.
566
+ preload_module_classes (`List[str]`, *optional*):
567
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
568
+ of the forward. This should only be used for classes that have submodules which are registered but not
569
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
570
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
571
+ force_hooks (`bool`, *optional*, defaults to `False`):
572
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
573
+ single device.
574
+ strict (`bool`, *optional*, defaults to `False`):
575
+ Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's
576
+ state_dict.
577
+ full_state_dict (`bool`, *optional*, defaults to `True`): if this is set to `True`, all the tensors in the
578
+ loaded state_dict will be gathered. No ShardedTensor and DTensor will be in the loaded state_dict.
579
+ broadcast_from_rank0 (`False`, *optional*, defaults to `False`): when the option is `True`, a distributed
580
+ `ProcessGroup` must be initialized. rank0 should receive a full state_dict and will broadcast the tensors
581
+ in the state_dict one by one to other ranks. Other ranks will receive the tensors and shard (if applicable)
582
+ according to the local shards in the model.
583
+
584
+ Example:
585
+
586
+ ```python
587
+ >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch
588
+ >>> from huggingface_hub import hf_hub_download
589
+ >>> from transformers import AutoConfig, AutoModelForCausalLM
590
+
591
+ >>> # Download the Weights
592
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
593
+ >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin")
594
+
595
+ >>> # Create a model and initialize it with empty weights
596
+ >>> config = AutoConfig.from_pretrained(checkpoint)
597
+ >>> with init_empty_weights():
598
+ ... model = AutoModelForCausalLM.from_config(config)
599
+
600
+ >>> # Load the checkpoint and dispatch it to the right devices
601
+ >>> model = load_checkpoint_and_dispatch(
602
+ ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"]
603
+ ... )
604
+ ```
605
+ """
606
+ if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
607
+ raise ValueError(
608
+ "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or 'sequential'."
609
+ )
610
+ if isinstance(device_map, str):
611
+ if device_map != "sequential":
612
+ max_memory = get_balanced_memory(
613
+ model,
614
+ max_memory=max_memory,
615
+ no_split_module_classes=no_split_module_classes,
616
+ dtype=dtype,
617
+ low_zero=(device_map == "balanced_low_0"),
618
+ )
619
+ device_map = infer_auto_device_map(
620
+ model,
621
+ max_memory=max_memory,
622
+ no_split_module_classes=no_split_module_classes,
623
+ dtype=dtype,
624
+ offload_buffers=offload_buffers,
625
+ )
626
+ if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
627
+ offload_state_dict = True
628
+ load_checkpoint_in_model(
629
+ model,
630
+ checkpoint,
631
+ device_map=device_map,
632
+ offload_folder=offload_folder,
633
+ dtype=dtype,
634
+ offload_state_dict=offload_state_dict,
635
+ offload_buffers=offload_buffers,
636
+ strict=strict,
637
+ full_state_dict=full_state_dict,
638
+ broadcast_from_rank0=broadcast_from_rank0,
639
+ )
640
+ if device_map is None:
641
+ return model
642
+ return dispatch_model(
643
+ model,
644
+ device_map=device_map,
645
+ offload_dir=offload_folder,
646
+ offload_buffers=offload_buffers,
647
+ skip_keys=skip_keys,
648
+ preload_module_classes=preload_module_classes,
649
+ force_hooks=force_hooks,
650
+ )
651
+
652
+
653
+ def attach_layerwise_casting_hooks(
654
+ module: torch.nn.Module,
655
+ storage_dtype: torch.dtype,
656
+ compute_dtype: torch.dtype,
657
+ skip_modules_pattern: Union[str, tuple[str, ...]] = None,
658
+ skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None,
659
+ non_blocking: bool = False,
660
+ ) -> None:
661
+ r"""
662
+ Applies layerwise casting to a given module. The module expected here is a PyTorch `nn.Module`. This is helpful for
663
+ reducing memory requirements when one doesn't want to fully quantize a model. Model params can be kept in say,
664
+ `torch.float8_e4m3fn` and upcasted to a higher precision like `torch.bfloat16` during forward pass and downcasted
665
+ back to `torch.float8_e4m3fn` to realize memory savings.
666
+
667
+ Args:
668
+ module (`torch.nn.Module`):
669
+ The module whose leaf modules will be cast to a high precision dtype for computation, and to a low
670
+ precision dtype for storage.
671
+ storage_dtype (`torch.dtype`):
672
+ The dtype to cast the module to before/after the forward pass for storage.
673
+ compute_dtype (`torch.dtype`):
674
+ The dtype to cast the module to during the forward pass for computation.
675
+ skip_modules_pattern (`tuple[str, ...]`, defaults to `None`):
676
+ A list of patterns to match the names of the modules to skip during the layerwise casting process. If set
677
+ to `None` alongside `skip_modules_classes` being `None`, the layerwise casting is applied directly to the
678
+ module instead of its internal submodules.
679
+ skip_modules_classes (`tuple[type[torch.nn.Module], ...]`, defaults to `None`):
680
+ A list of module classes to skip during the layerwise casting process.
681
+ non_blocking (`bool`, defaults to `False`):
682
+ If `True`, the weight casting operations are non-blocking.
683
+
684
+ Example:
685
+
686
+ ```python
687
+ >>> from accelerate.hooks import attach_layerwise_casting_hooks
688
+ >>> from transformers import AutoModelForCausalLM
689
+ >>> import torch
690
+
691
+ >>> # Model
692
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
693
+ >>> model = AutoModelForCausalLM.from_pretrained(checkpoint)
694
+
695
+ >>> # Attach hooks and perform inference
696
+ >>> attach_layerwise_casting_hooks(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
697
+ >>> with torch.no_grad():
698
+ ... model(...)
699
+ ```
700
+
701
+ Users can also pass modules they want to avoid from getting downcasted.
702
+
703
+ ```py
704
+ >>> attach_layerwise_casting_hooks(
705
+ ... model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16, skip_modules_pattern=["norm"]
706
+ ... )
707
+ ```
708
+ """
709
+ _attach_layerwise_casting_hooks(
710
+ module, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking
711
+ )
712
+
713
+
714
+ def _attach_layerwise_casting_hooks(
715
+ module: torch.nn.Module,
716
+ storage_dtype: torch.dtype,
717
+ compute_dtype: torch.dtype,
718
+ skip_modules_pattern: Union[str, tuple[str, ...]] = None,
719
+ skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None,
720
+ non_blocking: bool = False,
721
+ _prefix: str = "",
722
+ ):
723
+ should_skip = (skip_modules_classes is not None and isinstance(module, skip_modules_classes)) or (
724
+ skip_modules_pattern is not None and any(re.search(pattern, _prefix) for pattern in skip_modules_pattern)
725
+ )
726
+ if should_skip:
727
+ logger.debug(f'Skipping layerwise casting for layer "{_prefix}"')
728
+ return
729
+
730
+ if isinstance(module, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING):
731
+ logger.debug(f'Applying layerwise casting to layer "{_prefix}"')
732
+ add_hook_to_module(
733
+ module,
734
+ LayerwiseCastingHook(storage_dtype=storage_dtype, compute_dtype=compute_dtype, non_blocking=non_blocking),
735
+ append=True,
736
+ )
737
+ return
738
+
739
+ for name, submodule in module.named_children():
740
+ layer_name = f"{_prefix}.{name}" if _prefix else name
741
+ _attach_layerwise_casting_hooks(
742
+ submodule,
743
+ storage_dtype,
744
+ compute_dtype,
745
+ skip_modules_pattern,
746
+ skip_modules_classes,
747
+ non_blocking,
748
+ _prefix=layer_name,
749
+ )
python_embeded/Lib/site-packages/accelerate/checkpointing.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import random
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from safetensors.torch import load_model
21
+
22
+ from .utils import (
23
+ MODEL_NAME,
24
+ OPTIMIZER_NAME,
25
+ RNG_STATE_NAME,
26
+ SAFE_MODEL_NAME,
27
+ SAFE_WEIGHTS_NAME,
28
+ SAMPLER_NAME,
29
+ SCALER_NAME,
30
+ SCHEDULER_NAME,
31
+ WEIGHTS_NAME,
32
+ get_pretty_name,
33
+ is_cuda_available,
34
+ is_hpu_available,
35
+ is_mlu_available,
36
+ is_musa_available,
37
+ is_sdaa_available,
38
+ is_torch_version,
39
+ is_torch_xla_available,
40
+ is_xpu_available,
41
+ load,
42
+ save,
43
+ )
44
+
45
+
46
+ if is_torch_version(">=", "2.4.0"):
47
+ from torch.amp import GradScaler
48
+ else:
49
+ from torch.cuda.amp import GradScaler
50
+
51
+ if is_torch_xla_available():
52
+ import torch_xla.core.xla_model as xm
53
+
54
+ from .logging import get_logger
55
+ from .state import PartialState
56
+
57
+
58
+ logger = get_logger(__name__)
59
+
60
+
61
+ def save_accelerator_state(
62
+ output_dir: str,
63
+ model_states: list[dict],
64
+ optimizers: list,
65
+ schedulers: list,
66
+ dataloaders: list,
67
+ process_index: int,
68
+ step: int,
69
+ scaler: GradScaler = None,
70
+ save_on_each_node: bool = False,
71
+ safe_serialization: bool = True,
72
+ ):
73
+ """
74
+ Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.
75
+
76
+ <Tip>
77
+
78
+ If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native
79
+ `pickle`.
80
+
81
+ </Tip>
82
+
83
+ Args:
84
+ output_dir (`str` or `os.PathLike`):
85
+ The name of the folder to save all relevant weights and states.
86
+ model_states (`List[torch.nn.Module]`):
87
+ A list of model states
88
+ optimizers (`List[torch.optim.Optimizer]`):
89
+ A list of optimizer instances
90
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
91
+ A list of learning rate schedulers
92
+ dataloaders (`List[torch.utils.data.DataLoader]`):
93
+ A list of dataloader instances to save their sampler states
94
+ process_index (`int`):
95
+ The current process index in the Accelerator state
96
+ step (`int`):
97
+ The current step in the internal step tracker
98
+ scaler (`torch.amp.GradScaler`, *optional*):
99
+ An optional gradient scaler instance to save;
100
+ save_on_each_node (`bool`, *optional*):
101
+ Whether to save on every node, or only the main node.
102
+ safe_serialization (`bool`, *optional*, defaults to `True`):
103
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
104
+ """
105
+ output_dir = Path(output_dir)
106
+ # Model states
107
+ for i, state in enumerate(model_states):
108
+ weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
109
+ if i > 0:
110
+ weights_name = weights_name.replace(".", f"_{i}.")
111
+ output_model_file = output_dir.joinpath(weights_name)
112
+ save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization)
113
+ logger.info(f"Model weights saved in {output_model_file}")
114
+ # Optimizer states
115
+ for i, opt in enumerate(optimizers):
116
+ state = opt.state_dict()
117
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
118
+ output_optimizer_file = output_dir.joinpath(optimizer_name)
119
+ save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False)
120
+ logger.info(f"Optimizer state saved in {output_optimizer_file}")
121
+ # Scheduler states
122
+ for i, scheduler in enumerate(schedulers):
123
+ state = scheduler.state_dict()
124
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
125
+ output_scheduler_file = output_dir.joinpath(scheduler_name)
126
+ save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
127
+ logger.info(f"Scheduler state saved in {output_scheduler_file}")
128
+ # DataLoader states
129
+ for i, dataloader in enumerate(dataloaders):
130
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
131
+ output_sampler_file = output_dir.joinpath(sampler_name)
132
+ # Only save if we have our custom sampler
133
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
134
+
135
+ if isinstance(dataloader.dataset, IterableDatasetShard):
136
+ sampler = dataloader.get_sampler()
137
+ if isinstance(sampler, SeedableRandomSampler):
138
+ save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
139
+ if getattr(dataloader, "use_stateful_dataloader", False):
140
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
141
+ output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name)
142
+ state_dict = dataloader.state_dict()
143
+ torch.save(state_dict, output_dataloader_state_dict_file)
144
+ logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}")
145
+
146
+ # GradScaler state
147
+ if scaler is not None:
148
+ state = scaler.state_dict()
149
+ output_scaler_file = output_dir.joinpath(SCALER_NAME)
150
+ torch.save(state, output_scaler_file)
151
+ logger.info(f"Gradient scaler state saved in {output_scaler_file}")
152
+ # Random number generator states
153
+ states = {}
154
+ states_name = f"{RNG_STATE_NAME}_{process_index}.pkl"
155
+ states["step"] = step
156
+ states["random_state"] = random.getstate()
157
+ states["numpy_random_seed"] = np.random.get_state()
158
+ states["torch_manual_seed"] = torch.get_rng_state()
159
+ if is_xpu_available():
160
+ states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all()
161
+ if is_mlu_available():
162
+ states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all()
163
+ elif is_sdaa_available():
164
+ states["torch_sdaa_manual_seed"] = torch.sdaa.get_rng_state_all()
165
+ elif is_musa_available():
166
+ states["torch_musa_manual_seed"] = torch.musa.get_rng_state_all()
167
+ if is_hpu_available():
168
+ states["torch_hpu_manual_seed"] = torch.hpu.get_rng_state_all()
169
+ if is_cuda_available():
170
+ states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all()
171
+ if is_torch_xla_available():
172
+ states["xm_seed"] = xm.get_rng_state()
173
+ output_states_file = output_dir.joinpath(states_name)
174
+ torch.save(states, output_states_file)
175
+ logger.info(f"Random states saved in {output_states_file}")
176
+ return output_dir
177
+
178
+
179
+ def load_accelerator_state(
180
+ input_dir,
181
+ models,
182
+ optimizers,
183
+ schedulers,
184
+ dataloaders,
185
+ process_index,
186
+ scaler=None,
187
+ map_location=None,
188
+ load_kwargs=None,
189
+ **load_model_func_kwargs,
190
+ ):
191
+ """
192
+ Loads states of the models, optimizers, scaler, and RNG generators from a given directory.
193
+
194
+ Args:
195
+ input_dir (`str` or `os.PathLike`):
196
+ The name of the folder to load all relevant weights and states.
197
+ models (`List[torch.nn.Module]`):
198
+ A list of model instances
199
+ optimizers (`List[torch.optim.Optimizer]`):
200
+ A list of optimizer instances
201
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
202
+ A list of learning rate schedulers
203
+ process_index (`int`):
204
+ The current process index in the Accelerator state
205
+ scaler (`torch.amp.GradScaler`, *optional*):
206
+ An optional *GradScaler* instance to load
207
+ map_location (`str`, *optional*):
208
+ What device to load the optimizer state onto. Should be one of either "cpu" or "on_device".
209
+ load_kwargs (`dict`, *optional*):
210
+ Additional arguments that can be passed to the `load` function.
211
+ load_model_func_kwargs (`dict`, *optional*):
212
+ Additional arguments that can be passed to the model's `load_state_dict` method.
213
+
214
+ Returns:
215
+ `dict`: Contains the `Accelerator` attributes to override while loading the state.
216
+ """
217
+ # stores the `Accelerator` attributes to override
218
+ override_attributes = dict()
219
+ if map_location not in [None, "cpu", "on_device"]:
220
+ raise TypeError(
221
+ "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"
222
+ )
223
+ if map_location is None:
224
+ map_location = "cpu"
225
+ elif map_location == "on_device":
226
+ map_location = PartialState().device
227
+
228
+ if load_kwargs is None:
229
+ load_kwargs = {}
230
+
231
+ input_dir = Path(input_dir)
232
+ # Model states
233
+ for i, model in enumerate(models):
234
+ ending = f"_{i}" if i > 0 else ""
235
+ input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors")
236
+ if input_model_file.exists():
237
+ load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs)
238
+ else:
239
+ # Load with torch
240
+ input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin")
241
+ state_dict = load(input_model_file, map_location=map_location)
242
+ model.load_state_dict(state_dict, **load_model_func_kwargs)
243
+ logger.info("All model weights loaded successfully")
244
+
245
+ # Optimizer states
246
+ for i, opt in enumerate(optimizers):
247
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
248
+ input_optimizer_file = input_dir.joinpath(optimizer_name)
249
+ optimizer_state = load(input_optimizer_file, map_location=map_location, **load_kwargs)
250
+ optimizers[i].load_state_dict(optimizer_state)
251
+ logger.info("All optimizer states loaded successfully")
252
+
253
+ # Scheduler states
254
+ for i, scheduler in enumerate(schedulers):
255
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
256
+ input_scheduler_file = input_dir.joinpath(scheduler_name)
257
+ scheduler_state = load(input_scheduler_file, **load_kwargs)
258
+ scheduler.load_state_dict(scheduler_state)
259
+ logger.info("All scheduler states loaded successfully")
260
+
261
+ for i, dataloader in enumerate(dataloaders):
262
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
263
+ input_sampler_file = input_dir.joinpath(sampler_name)
264
+ # Only load if we have our custom sampler
265
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
266
+
267
+ if isinstance(dataloader.dataset, IterableDatasetShard):
268
+ sampler = dataloader.get_sampler()
269
+ if isinstance(sampler, SeedableRandomSampler):
270
+ sampler = dataloader.set_sampler(load(input_sampler_file))
271
+ if getattr(dataloader, "use_stateful_dataloader", False):
272
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
273
+ input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name)
274
+ if input_dataloader_state_dict_file.exists():
275
+ state_dict = load(input_dataloader_state_dict_file, **load_kwargs)
276
+ dataloader.load_state_dict(state_dict)
277
+ logger.info("All dataloader sampler states loaded successfully")
278
+
279
+ # GradScaler state
280
+ if scaler is not None:
281
+ input_scaler_file = input_dir.joinpath(SCALER_NAME)
282
+ scaler_state = load(input_scaler_file)
283
+ scaler.load_state_dict(scaler_state)
284
+ logger.info("GradScaler state loaded successfully")
285
+
286
+ # Random states
287
+ try:
288
+ states = load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl"))
289
+ if "step" in states:
290
+ override_attributes["step"] = states["step"]
291
+ random.setstate(states["random_state"])
292
+ np.random.set_state(states["numpy_random_seed"])
293
+ torch.set_rng_state(states["torch_manual_seed"])
294
+ if is_xpu_available():
295
+ torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"])
296
+ if is_mlu_available():
297
+ torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"])
298
+ elif is_sdaa_available():
299
+ torch.sdaa.set_rng_state_all(states["torch_sdaa_manual_seed"])
300
+ elif is_musa_available():
301
+ torch.musa.set_rng_state_all(states["torch_musa_manual_seed"])
302
+ else:
303
+ torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"])
304
+ if is_torch_xla_available():
305
+ xm.set_rng_state(states["xm_seed"])
306
+ logger.info("All random states loaded successfully")
307
+ except Exception:
308
+ logger.info("Could not load random states")
309
+
310
+ return override_attributes
311
+
312
+
313
+ def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False):
314
+ """
315
+ Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl`
316
+ """
317
+ # Should this be the right way to get a qual_name type value from `obj`?
318
+ save_location = Path(path) / f"custom_checkpoint_{index}.pkl"
319
+ logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}")
320
+ save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node)
321
+
322
+
323
+ def load_custom_state(obj, path, index: int = 0):
324
+ """
325
+ Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`. Will always set `weights_only=False` when
326
+ loading the state.
327
+ """
328
+ load_location = f"{path}/custom_checkpoint_{index}.pkl"
329
+ logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}")
330
+ obj.load_state_dict(load(load_location, map_location="cpu", weights_only=False))
python_embeded/Lib/site-packages/accelerate/data_loader.py ADDED
@@ -0,0 +1,1445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib
16
+ import math
17
+ from contextlib import suppress
18
+ from typing import Callable, Optional, Union
19
+
20
+ import torch
21
+ from packaging import version
22
+ from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler
23
+
24
+ from .logging import get_logger
25
+ from .state import DistributedType, GradientState, PartialState, is_torch_xla_available
26
+ from .utils import (
27
+ RNGType,
28
+ broadcast,
29
+ broadcast_object_list,
30
+ compare_versions,
31
+ concatenate,
32
+ find_batch_size,
33
+ get_data_structure,
34
+ initialize_tensors,
35
+ is_datasets_available,
36
+ is_torch_version,
37
+ is_torchdata_stateful_dataloader_available,
38
+ send_to_device,
39
+ slice_tensors,
40
+ synchronize_rng_states,
41
+ )
42
+
43
+
44
+ logger = get_logger(__name__)
45
+
46
+ # kwargs of the DataLoader in min version 2.0
47
+ _PYTORCH_DATALOADER_KWARGS = {
48
+ "batch_size": 1,
49
+ "shuffle": False,
50
+ "sampler": None,
51
+ "batch_sampler": None,
52
+ "num_workers": 0,
53
+ "collate_fn": None,
54
+ "pin_memory": False,
55
+ "drop_last": False,
56
+ "timeout": 0,
57
+ "worker_init_fn": None,
58
+ "multiprocessing_context": None,
59
+ "generator": None,
60
+ "prefetch_factor": 2,
61
+ "persistent_workers": False,
62
+ "pin_memory_device": "",
63
+ }
64
+
65
+ # kwargs added after by version
66
+ _PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {"2.6.0": {"in_order": True}}
67
+
68
+ for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items():
69
+ if is_torch_version(">=", v):
70
+ _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs)
71
+
72
+
73
+ class SeedableRandomSampler(RandomSampler):
74
+ """
75
+ Same as a random sampler, except that in `__iter__` a seed can be used.
76
+
77
+ Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed
78
+ and be fully reproducable on multiple iterations.
79
+
80
+ If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on
81
+ (stored in `self.epoch`).
82
+ """
83
+
84
+ def __init__(self, *args, **kwargs):
85
+ data_seed = kwargs.pop("data_seed", None)
86
+ super().__init__(*args, **kwargs)
87
+
88
+ self.initial_seed = data_seed if data_seed is not None else torch.random.initial_seed()
89
+ self.epoch = 0
90
+
91
+ def __iter__(self):
92
+ if self.generator is None:
93
+ self.generator = torch.Generator(
94
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
95
+ )
96
+ self.generator.manual_seed(self.initial_seed)
97
+
98
+ # Allow `self.epoch` to modify the seed of the generator
99
+ seed = self.epoch + self.initial_seed
100
+ # print("Setting seed at epoch", self.epoch, seed)
101
+ self.generator.manual_seed(seed)
102
+ yield from super().__iter__()
103
+ self.set_epoch(self.epoch + 1)
104
+
105
+ def set_epoch(self, epoch: int):
106
+ "Sets the current iteration of the sampler."
107
+ self.epoch = epoch
108
+
109
+
110
+ class BatchSamplerShard(BatchSampler):
111
+ """
112
+ Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will
113
+ always yield a number of batches that is a round multiple of `num_processes` and that all have the same size.
114
+ Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration
115
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
116
+
117
+ Args:
118
+ batch_sampler (`torch.utils.data.sampler.BatchSampler`):
119
+ The batch sampler to split in several shards.
120
+ num_processes (`int`, *optional*, defaults to 1):
121
+ The number of processes running concurrently.
122
+ process_index (`int`, *optional*, defaults to 0):
123
+ The index of the current process.
124
+ split_batches (`bool`, *optional*, defaults to `False`):
125
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
126
+ yielding different full batches on each process.
127
+
128
+ On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in:
129
+
130
+ - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if
131
+ this argument is set to `False`.
132
+ - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]`
133
+ then `[6, 7]` if this argument is set to `True`.
134
+ even_batches (`bool`, *optional*, defaults to `True`):
135
+ Whether or not to loop back at the beginning of the sampler when the number of samples is not a round
136
+ multiple of (original batch size / number of processes).
137
+
138
+ <Tip warning={true}>
139
+
140
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
141
+ equal to `False`
142
+
143
+ </Tip>"""
144
+
145
+ def __init__(
146
+ self,
147
+ batch_sampler: BatchSampler,
148
+ num_processes: int = 1,
149
+ process_index: int = 0,
150
+ split_batches: bool = False,
151
+ even_batches: bool = True,
152
+ ):
153
+ if split_batches and batch_sampler.batch_size % num_processes != 0:
154
+ raise ValueError(
155
+ f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) "
156
+ f"needs to be a round multiple of the number of processes ({num_processes})."
157
+ )
158
+ self.batch_sampler = batch_sampler
159
+ self.num_processes = num_processes
160
+ self.process_index = process_index
161
+ self.split_batches = split_batches
162
+ self.even_batches = even_batches
163
+ self.batch_size = getattr(batch_sampler, "batch_size", None)
164
+ self.drop_last = getattr(batch_sampler, "drop_last", False)
165
+ if self.batch_size is None and self.even_batches:
166
+ raise ValueError(
167
+ "You need to use `even_batches=False` when the batch sampler has no batch size. If you "
168
+ "are not calling this method directly, set `accelerator.even_batches=False` instead."
169
+ )
170
+
171
+ @property
172
+ def total_length(self):
173
+ return len(self.batch_sampler)
174
+
175
+ def __len__(self):
176
+ if self.split_batches:
177
+ # Split batches does not change the length of the batch sampler
178
+ return len(self.batch_sampler)
179
+ if len(self.batch_sampler) % self.num_processes == 0:
180
+ # If the length is a round multiple of the number of processes, it's easy.
181
+ return len(self.batch_sampler) // self.num_processes
182
+ length = len(self.batch_sampler) // self.num_processes
183
+ if self.drop_last:
184
+ # Same if we drop the remainder.
185
+ return length
186
+ elif self.even_batches:
187
+ # When we even batches we always get +1
188
+ return length + 1
189
+ else:
190
+ # Otherwise it depends on the process index.
191
+ return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length
192
+
193
+ def __iter__(self):
194
+ return self._iter_with_split() if self.split_batches else self._iter_with_no_split()
195
+
196
+ def _iter_with_split(self):
197
+ initial_data = []
198
+ batch_length = self.batch_sampler.batch_size // self.num_processes
199
+ for idx, batch in enumerate(self.batch_sampler):
200
+ if idx == 0:
201
+ initial_data = batch
202
+ if len(batch) == self.batch_size:
203
+ # If the batch is full, we yield the part of it this process is responsible of.
204
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
205
+
206
+ # If drop_last is True of the last batch was full, iteration is over, otherwise...
207
+ if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:
208
+ if not self.even_batches:
209
+ if len(batch) > batch_length * self.process_index:
210
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
211
+ else:
212
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
213
+ while len(initial_data) < self.batch_size:
214
+ initial_data += initial_data
215
+ batch = batch + initial_data
216
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
217
+
218
+ def _iter_with_no_split(self):
219
+ initial_data = []
220
+ batch_to_yield = []
221
+ for idx, batch in enumerate(self.batch_sampler):
222
+ # We gather the initial indices in case we need to circle back at the end.
223
+ if not self.drop_last and idx < self.num_processes:
224
+ initial_data += batch
225
+ # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually
226
+ # yielding it.
227
+ if idx % self.num_processes == self.process_index:
228
+ batch_to_yield = batch
229
+ if idx % self.num_processes == self.num_processes - 1 and (
230
+ self.batch_size is None or len(batch) == self.batch_size
231
+ ):
232
+ yield batch_to_yield
233
+ batch_to_yield = []
234
+
235
+ # If drop_last is True, iteration is over, otherwise...
236
+ if not self.drop_last and len(initial_data) > 0:
237
+ if not self.even_batches:
238
+ if len(batch_to_yield) > 0:
239
+ yield batch_to_yield
240
+ else:
241
+ # ... we yield the complete batch we had saved before if it has the proper length
242
+ if len(batch_to_yield) == self.batch_size:
243
+ yield batch_to_yield
244
+
245
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
246
+ while len(initial_data) < self.num_processes * self.batch_size:
247
+ initial_data += initial_data
248
+
249
+ # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next
250
+ if len(batch) == self.batch_size:
251
+ batch = []
252
+ idx += 1
253
+
254
+ # Make sure we yield a multiple of self.num_processes batches
255
+ cycle_index = 0
256
+ while idx % self.num_processes != 0 or len(batch) > 0:
257
+ end_index = cycle_index + self.batch_size - len(batch)
258
+ batch += initial_data[cycle_index:end_index]
259
+ if idx % self.num_processes == self.process_index:
260
+ yield batch
261
+ cycle_index = end_index
262
+ batch = []
263
+ idx += 1
264
+
265
+
266
+ class IterableDatasetShard(IterableDataset):
267
+ """
268
+ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
269
+ always yield a number of samples that is a round multiple of the actual batch size (depending of the value of
270
+ `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the
271
+ `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would
272
+ be too small or loop with indices from the beginning.
273
+
274
+ Args:
275
+ dataset (`torch.utils.data.dataset.IterableDataset`):
276
+ The batch sampler to split in several shards.
277
+ batch_size (`int`, *optional*, defaults to 1):
278
+ The size of the batches per shard (if `split_batches=False`) or the size of the batches (if
279
+ `split_batches=True`).
280
+ drop_last (`bool`, *optional*, defaults to `False`):
281
+ Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
282
+ beginning.
283
+ num_processes (`int`, *optional*, defaults to 1):
284
+ The number of processes running concurrently.
285
+ process_index (`int`, *optional*, defaults to 0):
286
+ The index of the current process.
287
+ split_batches (`bool`, *optional*, defaults to `False`):
288
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
289
+ yielding different full batches on each process.
290
+
291
+ On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in:
292
+
293
+ - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this
294
+ argument is set to `False`.
295
+ - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if
296
+ this argument is set to `True`.
297
+ """
298
+
299
+ def __init__(
300
+ self,
301
+ dataset: IterableDataset,
302
+ batch_size: int = 1,
303
+ drop_last: bool = False,
304
+ num_processes: int = 1,
305
+ process_index: int = 0,
306
+ split_batches: bool = False,
307
+ ):
308
+ if split_batches and batch_size > 1 and batch_size % num_processes != 0:
309
+ raise ValueError(
310
+ f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) "
311
+ f"needs to be a round multiple of the number of processes ({num_processes})."
312
+ )
313
+ self.dataset = dataset
314
+ self.batch_size = batch_size
315
+ self.drop_last = drop_last
316
+ self.num_processes = num_processes
317
+ self.process_index = process_index
318
+ self.split_batches = split_batches
319
+
320
+ def set_epoch(self, epoch):
321
+ self.epoch = epoch
322
+ if hasattr(self.dataset, "set_epoch"):
323
+ self.dataset.set_epoch(epoch)
324
+
325
+ def __len__(self):
326
+ # We will just raise the downstream error if the underlying dataset is not sized
327
+ if self.drop_last:
328
+ return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
329
+ else:
330
+ return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
331
+
332
+ def __iter__(self):
333
+ if (
334
+ not hasattr(self.dataset, "set_epoch")
335
+ and hasattr(self.dataset, "generator")
336
+ and isinstance(self.dataset.generator, torch.Generator)
337
+ ):
338
+ self.dataset.generator.manual_seed(self.epoch)
339
+ real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes)
340
+ process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size
341
+ process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size)
342
+
343
+ first_batch = None
344
+ current_batch = []
345
+ for element in self.dataset:
346
+ current_batch.append(element)
347
+ # Wait to have a full batch before yielding elements.
348
+ if len(current_batch) == real_batch_size:
349
+ for i in process_slice:
350
+ yield current_batch[i]
351
+ if first_batch is None:
352
+ first_batch = current_batch.copy()
353
+ current_batch = []
354
+
355
+ # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.
356
+ if not self.drop_last and len(current_batch) > 0:
357
+ if first_batch is None:
358
+ first_batch = current_batch.copy()
359
+ while len(current_batch) < real_batch_size:
360
+ current_batch += first_batch
361
+ for i in process_slice:
362
+ yield current_batch[i]
363
+
364
+
365
+ class DataLoaderStateMixin:
366
+ """
367
+ Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the
368
+ end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other
369
+ useful information that might be needed.
370
+
371
+ **Available attributes:**
372
+
373
+ - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch
374
+ - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total
375
+ batch size
376
+
377
+ <Tip warning={true}>
378
+
379
+ Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in
380
+ `self.gradient_state`.
381
+
382
+ </Tip>
383
+
384
+ """
385
+
386
+ def __init_subclass__(cls, **kwargs):
387
+ cls.end_of_dataloader = False
388
+ cls.remainder = -1
389
+
390
+ def reset(self):
391
+ self.end_of_dataloader = False
392
+ self.remainder = -1
393
+
394
+ def begin(self):
395
+ "Prepares the gradient state for the current dataloader"
396
+ self.reset()
397
+ with suppress(Exception):
398
+ if not self._drop_last:
399
+ length = getattr(self.dataset, "total_dataset_length", len(self.dataset))
400
+ self.remainder = length % self.total_batch_size
401
+ self.gradient_state._add_dataloader(self)
402
+
403
+ def end(self):
404
+ "Cleans up the gradient state after exiting the dataloader"
405
+ self.gradient_state._remove_dataloader(self)
406
+
407
+
408
+ class DataLoaderAdapter:
409
+ """
410
+ A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For
411
+ compatability reasons, this class inherits from the class it wraps around, so it can be used as a drop-in.
412
+ """
413
+
414
+ def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs):
415
+ self.use_stateful_dataloader = use_stateful_dataloader
416
+ if is_torchdata_stateful_dataloader_available():
417
+ from torchdata.stateful_dataloader import StatefulDataLoader
418
+
419
+ if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available():
420
+ raise ImportError(
421
+ "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it."
422
+ )
423
+ if use_stateful_dataloader:
424
+ torchdata_version = version.parse(importlib.metadata.version("torchdata"))
425
+ if (
426
+ "in_order" in kwargs
427
+ and compare_versions(torchdata_version, "<", "0.11")
428
+ and is_torch_version(">=", "2.6.0")
429
+ ):
430
+ kwargs.pop("in_order")
431
+ self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
432
+ else:
433
+ self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
434
+
435
+ if hasattr(self.base_dataloader, "state_dict"):
436
+ self.dl_state_dict = self.base_dataloader.state_dict()
437
+
438
+ def __getattr__(self, name):
439
+ # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute.
440
+ if name == "base_dataloader":
441
+ raise AttributeError()
442
+ # Delegate attribute access to the internal dataloader
443
+ return getattr(self.base_dataloader, name)
444
+
445
+ def state_dict(self):
446
+ return self.dl_state_dict
447
+
448
+ def load_state_dict(self, state_dict):
449
+ self.base_dataloader.load_state_dict(state_dict)
450
+
451
+ @property
452
+ def __class__(self):
453
+ """
454
+ In order to maintain backwards compatability with other code, we need to ensure `isinstance(obj, DataLoader)`
455
+ returs true. This is because some downstream code assumes that the `DataLoader` is the base class of the
456
+ object.
457
+ """
458
+ return self.base_dataloader.__class__
459
+
460
+ def __len__(self):
461
+ return len(self.base_dataloader)
462
+
463
+ def adjust_state_dict_for_prefetch(self):
464
+ """
465
+ Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in
466
+ `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be
467
+ overridden.
468
+
469
+ This should modify `self.dl_state_dict` directly
470
+ """
471
+ # The state dict will be off by a factor of `n-1` batch too many during DDP,
472
+ # so we need to adjust it here
473
+ if PartialState().distributed_type != DistributedType.NO:
474
+ factor = PartialState().num_processes - 1
475
+ if self.dl_state_dict["_sampler_iter_yielded"] > 0:
476
+ self.dl_state_dict["_sampler_iter_yielded"] -= factor
477
+ if self.dl_state_dict["_num_yielded"] > 0:
478
+ self.dl_state_dict["_num_yielded"] -= factor
479
+ if self.dl_state_dict["_index_sampler_state"] is not None:
480
+ if (
481
+ "samples_yielded" in self.dl_state_dict["_index_sampler_state"]
482
+ and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0
483
+ ):
484
+ self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor
485
+
486
+ def _update_state_dict(self):
487
+ # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded.
488
+ # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of
489
+ # what it wants to yield.
490
+ #
491
+ # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter.
492
+ if hasattr(self.base_dataloader, "state_dict"):
493
+ self.dl_state_dict = self.base_dataloader.state_dict()
494
+ # Potentially modify the state_dict to adjust for prefetching
495
+ self.adjust_state_dict_for_prefetch()
496
+ # Then tag if we are at the end of the dataloader
497
+ self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader
498
+
499
+
500
+ class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin):
501
+ """
502
+ Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup.
503
+
504
+ Args:
505
+ dataset (`torch.utils.data.dataset.Dataset`):
506
+ The dataset to use to build this dataloader.
507
+ device (`torch.device`, *optional*):
508
+ If passed, the device to put all batches on.
509
+ rng_types (list of `str` or [`~utils.RNGType`]):
510
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
511
+ several of:
512
+
513
+ - `"torch"`: the base torch random number generator
514
+ - `"cuda"`: the CUDA random number generator (GPU only)
515
+ - `"xla"`: the XLA random number generator (TPU only)
516
+ - `"generator"`: an optional `torch.Generator`
517
+ synchronized_generator (`torch.Generator`, *optional*):
518
+ A random number generator to keep synchronized across processes.
519
+ skip_batches (`int`, *optional*, defaults to 0):
520
+ The number of batches to skip at the beginning.
521
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
522
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
523
+ **kwargs (additional keyword arguments, *optional*):
524
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
525
+
526
+ **Available attributes:**
527
+
528
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
529
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
530
+ number of processes
531
+
532
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
533
+ """
534
+
535
+ def __init__(
536
+ self,
537
+ dataset,
538
+ device=None,
539
+ rng_types=None,
540
+ synchronized_generator=None,
541
+ skip_batches=0,
542
+ use_stateful_dataloader=False,
543
+ _drop_last: bool = False,
544
+ _non_blocking: bool = False,
545
+ torch_device_mesh=None,
546
+ **kwargs,
547
+ ):
548
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
549
+ self.device = device
550
+ self.rng_types = rng_types
551
+ self.synchronized_generator = synchronized_generator
552
+ self.skip_batches = skip_batches
553
+ self.gradient_state = GradientState()
554
+ self._drop_last = _drop_last
555
+ self._non_blocking = _non_blocking
556
+ self.iteration = 0
557
+
558
+ def __iter__(self):
559
+ if self.rng_types is not None:
560
+ synchronize_rng_states(self.rng_types, self.synchronized_generator)
561
+ self.begin()
562
+
563
+ self.set_epoch(self.iteration)
564
+ dataloader_iter = self.base_dataloader.__iter__()
565
+ # We iterate one batch ahead to check when we are at the end
566
+ try:
567
+ current_batch = next(dataloader_iter)
568
+ except StopIteration:
569
+ yield
570
+
571
+ batch_index = 0
572
+ while True:
573
+ try:
574
+ # But we still move it to the device so it is done before `StopIteration` is reached
575
+ if self.device is not None:
576
+ current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking)
577
+ self._update_state_dict()
578
+ next_batch = next(dataloader_iter)
579
+ if batch_index >= self.skip_batches:
580
+ yield current_batch
581
+ batch_index += 1
582
+ current_batch = next_batch
583
+ except StopIteration:
584
+ self.end_of_dataloader = True
585
+ self._update_state_dict()
586
+ if batch_index >= self.skip_batches:
587
+ yield current_batch
588
+ break
589
+
590
+ self.iteration += 1
591
+ self.end()
592
+
593
+ def __reduce__(self):
594
+ """
595
+ Define the `__reduce__` method to ensure a `DataLoaderShard` can be pickled and unpickled. This needs to be
596
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
597
+ `__class__` member.
598
+ """
599
+ args = super().__reduce__()
600
+ return (DataLoaderShard, *args[1:])
601
+
602
+ def set_epoch(self, epoch: int):
603
+ # In case it is manually passed in, the user can set it to what they like
604
+ if self.iteration != epoch:
605
+ self.iteration = epoch
606
+ if hasattr(self.batch_sampler, "set_epoch"):
607
+ self.batch_sampler.set_epoch(epoch)
608
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
609
+ self.batch_sampler.sampler.set_epoch(epoch)
610
+ if (
611
+ hasattr(self.batch_sampler, "batch_sampler")
612
+ and hasattr(self.batch_sampler.batch_sampler, "sampler")
613
+ and hasattr(self.batch_sampler.batch_sampler.sampler, "set_epoch")
614
+ ):
615
+ self.batch_sampler.batch_sampler.sampler.set_epoch(epoch)
616
+ # We support if a custom `Dataset` implementation has `set_epoch`
617
+ # or in general HF datasets `Datasets`
618
+ elif hasattr(self.dataset, "set_epoch"):
619
+ self.dataset.set_epoch(epoch)
620
+
621
+ @property
622
+ def total_batch_size(self):
623
+ batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler
624
+ return (
625
+ batch_sampler.batch_size
626
+ if getattr(batch_sampler, "split_batches", False)
627
+ else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1))
628
+ )
629
+
630
+ @property
631
+ def total_dataset_length(self):
632
+ if hasattr(self.dataset, "total_length"):
633
+ return self.dataset.total_length
634
+ else:
635
+ return len(self.dataset)
636
+
637
+ def get_sampler(self):
638
+ return get_sampler(self)
639
+
640
+ def set_sampler(self, sampler):
641
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
642
+ if sampler_is_batch_sampler:
643
+ self.sampler.sampler = sampler
644
+ else:
645
+ self.batch_sampler.sampler = sampler
646
+ if hasattr(self.batch_sampler, "batch_sampler"):
647
+ self.batch_sampler.batch_sampler.sampler = sampler
648
+
649
+
650
+ if is_torch_xla_available():
651
+ import torch_xla.distributed.parallel_loader as xpl
652
+
653
+ class MpDeviceLoaderWrapper(xpl.MpDeviceLoader):
654
+ """
655
+ Wrapper for the xpl.MpDeviceLoader class that knows the total batch size.
656
+
657
+ XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to
658
+ prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main
659
+ thread only.
660
+
661
+ **Available attributes:**
662
+
663
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
664
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
665
+ number of processes
666
+
667
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
668
+ """
669
+
670
+ def __init__(self, dataloader: DataLoaderShard, device: torch.device):
671
+ super().__init__(dataloader, device)
672
+ self._rng_types = self._loader.rng_types
673
+ self._loader.rng_types = None
674
+ self.device = device
675
+
676
+ def __iter__(self):
677
+ if self._rng_types is not None:
678
+ synchronize_rng_states(self._rng_types, self._loader.synchronized_generator)
679
+
680
+ return super().__iter__()
681
+
682
+ def set_epoch(self, epoch: int):
683
+ if hasattr(self.dataloader, "set_epoch"):
684
+ self.dataloader.set_epoch(epoch)
685
+
686
+ @property
687
+ def total_batch_size(self):
688
+ return self._loader.total_batch_size
689
+
690
+ @property
691
+ def total_dataset_length(self):
692
+ return self._loader.total_dataset_length
693
+
694
+ @property
695
+ def batch_sampler(self):
696
+ return self._loader.batch_sampler
697
+
698
+ @property
699
+ def dataloader(self):
700
+ return self._loader
701
+
702
+
703
+ class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin):
704
+ """
705
+ Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process
706
+ their part of the batch.
707
+
708
+ Args:
709
+ split_batches (`bool`, *optional*, defaults to `False`):
710
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
711
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
712
+ `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be
713
+ the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial
714
+ `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch
715
+ size of the `dataloader` is a round multiple of `batch_size`.
716
+ skip_batches (`int`, *optional*, defaults to 0):
717
+ The number of batches to skip at the beginning of an iteration.
718
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
719
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
720
+
721
+ **Available attributes:**
722
+
723
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
724
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
725
+ number of processes
726
+
727
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
728
+ """
729
+
730
+ def __init__(
731
+ self,
732
+ dataset,
733
+ split_batches: bool = False,
734
+ skip_batches=0,
735
+ use_stateful_dataloader=False,
736
+ _drop_last: bool = False,
737
+ _non_blocking: bool = False,
738
+ slice_fn=None,
739
+ torch_device_mesh=None,
740
+ **kwargs,
741
+ ):
742
+ shuffle = False
743
+ from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe
744
+
745
+ # We need to save the shuffling state of the DataPipe
746
+ if isinstance(dataset, ShufflerIterDataPipe):
747
+ shuffle = dataset._shuffle_enabled
748
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
749
+ self.split_batches = split_batches
750
+ if shuffle:
751
+ torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
752
+
753
+ self.gradient_state = GradientState()
754
+ self.state = PartialState()
755
+ self._drop_last = _drop_last
756
+ self._non_blocking = _non_blocking
757
+ self.skip_batches = skip_batches
758
+ self.torch_device_mesh = torch_device_mesh
759
+
760
+ self.slice_fn = slice_tensors if slice_fn is None else slice_fn
761
+ self.iteration = 0
762
+
763
+ # if a device mesh is provided extract each dimension (dp, fsdp, tp)
764
+ # device mesh may hold any number of dimensions, however,
765
+ # below code is for targetted support for dp, fsdp and tp
766
+
767
+ # device mesh will be used only if there is tp involved
768
+ # or any multi-dimensional parallelism involving tp
769
+ # (dp, tp) (fsdp, tp) (dp, fsdp, tp)
770
+ # otherwise the default behavour not using device mesh should be sufficient
771
+ # since multi dimensional parallelism devoid of tp would anyway need
772
+ # different batches for each process irrespective of dp or fsdp
773
+ self.submesh_tp = None
774
+ self.submesh_dp = None
775
+ self.submesh_fsdp = None
776
+ if self.torch_device_mesh and "tp" in self.torch_device_mesh.mesh_dim_names:
777
+ self.submesh_tp = self.torch_device_mesh["tp"]
778
+ if "dp" in self.torch_device_mesh.mesh_dim_names:
779
+ self.submesh_dp = self.torch_device_mesh["dp"]
780
+ if "fsdp" in self.torch_device_mesh.mesh_dim_names:
781
+ self.submesh_fsdp = self.torch_device_mesh["fsdp"]
782
+ if self.submesh_tp and (self.submesh_dp or self.submesh_fsdp):
783
+ raise ValueError("TP + (DP/FSDP) is not yet supported in dispatch mode")
784
+
785
+ def _fetch_batches(self, iterator):
786
+ batches, batch = None, None
787
+ # On process 0, we gather the batch to dispatch.
788
+ if self.state.process_index == 0:
789
+ # Procedure to support TP only is simpler
790
+ # since we want to dispatch the same batch of samples across all ranks
791
+ # this removes complexity of handling multiple tp rank groups when TP + DP
792
+ # combination is involved.
793
+
794
+ try:
795
+ # for TP case avoid using split_batches
796
+ # since it would mean that the dataloader should be spilling out
797
+ # duplicates of batches.
798
+ if self.split_batches:
799
+ # One batch of the main iterator is dispatched and split.
800
+ if self.submesh_tp:
801
+ logger.warning(
802
+ "Use of split_batches for TP would need the dataloader to produce duplicate batches,"
803
+ "otherwise, use dispatch_batches=True instead."
804
+ )
805
+ self._update_state_dict()
806
+ batch = next(iterator)
807
+ else:
808
+ # num_processes batches of the main iterator are concatenated then dispatched and split.
809
+ # We add the batches one by one so we have the remainder available when drop_last=False.
810
+ batches = []
811
+ if self.submesh_tp:
812
+ # when tp, extract single batch and then replicate
813
+ self._update_state_dict()
814
+ batch = next(iterator)
815
+ batches = [batch] * self.state.num_processes
816
+ else:
817
+ for _ in range(self.state.num_processes):
818
+ self._update_state_dict()
819
+ batches.append(next(iterator))
820
+ try:
821
+ batch = concatenate(batches, dim=0)
822
+ except RuntimeError as e:
823
+ raise RuntimeError(
824
+ "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`."
825
+ "either pass `dispatch_batches=False` and have each process fetch its own batch "
826
+ " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and "
827
+ "slice it into `num_processes` batches for each process."
828
+ ) from e
829
+ # In both cases, we need to get the structure of the batch that we will broadcast on other
830
+ # processes to initialize the tensors with the right shape.
831
+ # data_structure, stop_iteration
832
+ batch_info = [get_data_structure(batch), False]
833
+ except StopIteration:
834
+ batch_info = [None, True]
835
+ else:
836
+ batch_info = [None, self._stop_iteration]
837
+ # This is inplace, so after this instruction, every process has the same `batch_info` as process 0.
838
+ broadcast_object_list(batch_info)
839
+ self._stop_iteration = batch_info[1]
840
+ if self._stop_iteration:
841
+ # If drop_last is False and split_batches is False, we may have a remainder to take care of.
842
+ if not self.split_batches and not self._drop_last:
843
+ if self.state.process_index == 0 and len(batches) > 0:
844
+ batch = concatenate(batches, dim=0)
845
+ batch_info = [get_data_structure(batch), False]
846
+ else:
847
+ batch_info = [None, True]
848
+ broadcast_object_list(batch_info)
849
+ return batch, batch_info
850
+
851
+ def __iter__(self):
852
+ self.begin()
853
+ self.set_epoch(self.iteration)
854
+ main_iterator = None
855
+ if is_torch_version(">=", "2.0.1"):
856
+ # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts
857
+ # shared seed to all dist processes. Thus, we need to create iterator for all dist processes.
858
+ # But, we only iterate through the DataLoader on process 0.
859
+ main_iterator = self.base_dataloader.__iter__()
860
+ elif self.state.process_index == 0:
861
+ main_iterator = self.base_dataloader.__iter__()
862
+ stop_iteration = False
863
+ self._stop_iteration = False
864
+ first_batch = None
865
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
866
+ batch_index = 0
867
+ while not stop_iteration:
868
+ batch, batch_info = next_batch, next_batch_info
869
+
870
+ if self.state.process_index != 0:
871
+ # Initialize tensors on other processes than process 0.
872
+ batch = initialize_tensors(batch_info[0])
873
+ batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking)
874
+ # Broadcast the batch before splitting it.
875
+ batch = broadcast(batch, from_process=0)
876
+
877
+ if not self._drop_last and first_batch is None:
878
+ # We keep at least num processes elements of the first batch to be able to complete the last batch
879
+ first_batch = self.slice_fn(
880
+ batch,
881
+ slice(0, self.state.num_processes),
882
+ process_index=self.state.process_index,
883
+ num_processes=self.state.num_processes,
884
+ )
885
+
886
+ if batch is None:
887
+ raise ValueError(
888
+ f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration."
889
+ )
890
+
891
+ observed_batch_size = find_batch_size(batch)
892
+ batch_size = observed_batch_size // self.state.num_processes
893
+
894
+ stop_iteration = self._stop_iteration
895
+ if not stop_iteration:
896
+ # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in
897
+ # the dataloader since the number of batches is a round multiple of the number of processes.
898
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
899
+ # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them.
900
+ if self._stop_iteration and next_batch_info[0] is None:
901
+ stop_iteration = True
902
+
903
+ if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0:
904
+ # If the last batch is not complete, let's add the first batch to it.
905
+ batch = concatenate([batch, first_batch], dim=0)
906
+ # Batch size computation above is wrong, it's off by 1 so we fix it.
907
+ batch_size += 1
908
+
909
+ data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size)
910
+ batch = self.slice_fn(
911
+ batch,
912
+ data_slice,
913
+ process_index=self.state.process_index,
914
+ num_processes=self.state.num_processes,
915
+ )
916
+
917
+ if stop_iteration:
918
+ self.end_of_dataloader = True
919
+ self._update_state_dict()
920
+ self.remainder = observed_batch_size
921
+ if batch_index >= self.skip_batches:
922
+ yield batch
923
+ batch_index += 1
924
+ self.iteration += 1
925
+ self.end()
926
+
927
+ def set_epoch(self, epoch: int):
928
+ # In case it is manually passed in, the user can set it to what they like
929
+ if self.iteration != epoch:
930
+ self.iteration = epoch
931
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
932
+ self.batch_sampler.sampler.set_epoch(epoch)
933
+ elif hasattr(self.dataset, "set_epoch"):
934
+ self.dataset.set_epoch(epoch)
935
+
936
+ def __len__(self):
937
+ whole_length = len(self.base_dataloader)
938
+ if self.split_batches:
939
+ return whole_length
940
+ elif self._drop_last:
941
+ return whole_length // self.state.num_processes
942
+ else:
943
+ return math.ceil(whole_length / self.state.num_processes)
944
+
945
+ def __reduce__(self):
946
+ """
947
+ Define the `__reduce__` method to ensure a `DataLoaderDispatcher` can be pickled and unpickled. This needs to
948
+ be explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
949
+ `__class__` member.
950
+ """
951
+ args = super().__reduce__()
952
+ return (DataLoaderDispatcher, *args[1:])
953
+
954
+ @property
955
+ def total_batch_size(self):
956
+ return (
957
+ self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes)
958
+ )
959
+
960
+ @property
961
+ def total_dataset_length(self):
962
+ return len(self.dataset)
963
+
964
+ def get_sampler(self):
965
+ return get_sampler(self)
966
+
967
+ def set_sampler(self, sampler):
968
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
969
+ if sampler_is_batch_sampler:
970
+ self.sampler.sampler = sampler
971
+ else:
972
+ self.batch_sampler.sampler = sampler
973
+ if hasattr(self.batch_sampler, "batch_sampler"):
974
+ self.batch_sampler.batch_sampler.sampler = sampler
975
+
976
+
977
+ def get_sampler(dataloader):
978
+ """
979
+ Get the sampler associated to the dataloader
980
+
981
+ Args:
982
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
983
+ The data loader to split across several devices.
984
+ Returns:
985
+ `torch.utils.data.Sampler`: The sampler associated to the dataloader
986
+ """
987
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
988
+ if sampler_is_batch_sampler:
989
+ sampler = getattr(dataloader.sampler, "sampler", None)
990
+ else:
991
+ sampler = getattr(dataloader.batch_sampler, "sampler", None)
992
+ return sampler
993
+
994
+
995
+ def prepare_data_loader(
996
+ dataloader: DataLoader,
997
+ device: Optional[torch.device] = None,
998
+ num_processes: Optional[int] = None,
999
+ process_index: Optional[int] = None,
1000
+ split_batches: bool = False,
1001
+ put_on_device: bool = False,
1002
+ rng_types: Optional[list[Union[str, RNGType]]] = None,
1003
+ dispatch_batches: Optional[bool] = None,
1004
+ even_batches: bool = True,
1005
+ slice_fn_for_dispatch: Optional[Callable] = None,
1006
+ use_seedable_sampler: bool = False,
1007
+ data_seed: Optional[int] = None,
1008
+ non_blocking: bool = False,
1009
+ use_stateful_dataloader: bool = False,
1010
+ torch_device_mesh=None,
1011
+ ) -> DataLoader:
1012
+ """
1013
+ Wraps a PyTorch `DataLoader` to generate batches for one of the processes only.
1014
+
1015
+ Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration
1016
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
1017
+
1018
+ Args:
1019
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
1020
+ The data loader to split across several devices.
1021
+ device (`torch.device`):
1022
+ The target device for the returned `DataLoader`.
1023
+ num_processes (`int`, *optional*):
1024
+ The number of processes running concurrently. Will default to the value given by [`~state.PartialState`].
1025
+ process_index (`int`, *optional*):
1026
+ The index of the current process. Will default to the value given by [`~state.PartialState`].
1027
+ split_batches (`bool`, *optional*, defaults to `False`):
1028
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
1029
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
1030
+ `num_processes` batches at each iteration).
1031
+
1032
+ Another way to see this is that the observed batch size will be the same as the initial `dataloader` if
1033
+ this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes`
1034
+ otherwise.
1035
+
1036
+ Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of
1037
+ `batch_size`.
1038
+ put_on_device (`bool`, *optional*, defaults to `False`):
1039
+ Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or
1040
+ dictionaries of tensors).
1041
+ rng_types (list of `str` or [`~utils.RNGType`]):
1042
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
1043
+ several of:
1044
+
1045
+ - `"torch"`: the base torch random number generator
1046
+ - `"cuda"`: the CUDA random number generator (GPU only)
1047
+ - `"xla"`: the XLA random number generator (TPU only)
1048
+ - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
1049
+ dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.
1050
+
1051
+ dispatch_batches (`bool`, *optional*):
1052
+ If set to `True`, the dataloader prepared is only iterated through on the main process and then the batches
1053
+ are split and broadcast to each process. Will default to `True` when the underlying dataset is an
1054
+ `IterableDataset`, `False` otherwise.
1055
+ even_batches (`bool`, *optional*, defaults to `True`):
1056
+ If set to `True`, in cases where the total batch size across all processes does not exactly divide the
1057
+ dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
1058
+ all workers.
1059
+ slice_fn_for_dispatch (`Callable`, *optional*`):
1060
+ If passed, this function will be used to slice tensors across `num_processes`. Will default to
1061
+ [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be
1062
+ ignored otherwise.
1063
+ use_seedable_sampler (`bool`, *optional*, defaults to `False`):
1064
+ Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better
1065
+ reproducability. Comes at a cost of potentially different performances due to different shuffling
1066
+ algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every
1067
+ `self.set_epoch`
1068
+ data_seed (`int`, *optional*, defaults to `None`):
1069
+ The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator
1070
+ will use the current default seed from torch.
1071
+ non_blocking (`bool`, *optional*, defaults to `False`):
1072
+ If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has
1073
+ `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations.
1074
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
1075
+ "If set to true, the dataloader prepared by the Accelerator will be backed by "
1076
+ "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
1077
+ This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed."
1078
+ torch_device_mesh (`torch.distributed.DeviceMesh`, *optional*, defaults to `None`):
1079
+ PyTorch device mesh.
1080
+
1081
+
1082
+ Returns:
1083
+ `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches
1084
+
1085
+ <Tip warning={true}>
1086
+
1087
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
1088
+ equal to `False`
1089
+
1090
+ </Tip>
1091
+ """
1092
+ if dispatch_batches is None:
1093
+ if not put_on_device:
1094
+ dispatch_batches = False
1095
+ else:
1096
+ dispatch_batches = isinstance(dataloader.dataset, IterableDataset)
1097
+
1098
+ if dispatch_batches and not put_on_device:
1099
+ raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.")
1100
+ # Grab defaults from PartialState
1101
+ state = PartialState()
1102
+ if num_processes is None:
1103
+ num_processes = state.num_processes
1104
+
1105
+ if process_index is None:
1106
+ process_index = state.process_index
1107
+
1108
+ if torch_device_mesh:
1109
+ if state.distributed_type == DistributedType.DEEPSPEED:
1110
+ # In DeepSpeed, the optimizer sharing level in DP is determined by the config file.
1111
+ # Only considers "dp" and "tp".
1112
+ # Given a device mesh (dp, tp) = (2, 3):
1113
+ # - From the data parallel perspective, ranks should be structured as: 0 0 0 1 1 1
1114
+ # - Processes with the same DP rank will receive the same batch.
1115
+ if "tp" in torch_device_mesh.mesh_dim_names:
1116
+ submesh_tp_size = torch_device_mesh["tp"].size()
1117
+ process_index = process_index // submesh_tp_size
1118
+ num_processes = num_processes // submesh_tp_size
1119
+ else:
1120
+ # when device mesh is used, specifically with TP
1121
+ # then there is need to update process_index and num_processes
1122
+ # to bring in the effect of generating same batch across TP ranks
1123
+ # and different batch across FSDP and DP ranks.
1124
+ # Example:
1125
+ # if device mesh is (dp,fsdp,tp) = (2, 2, 3)
1126
+ # ranks would range from 0...11
1127
+ # from data angle ranks should look like 0 0 0 1 1 1 2 2 2 3 3 3
1128
+ # processes with same ranks/ids would receive the same batch
1129
+ submesh_fsdp_size = 1
1130
+ submesh_dp_size = 1
1131
+ submesh_tp_size = 1
1132
+ if "tp" in torch_device_mesh.mesh_dim_names:
1133
+ submesh_tp_size = torch_device_mesh["tp"].size()
1134
+ if "dp" in torch_device_mesh.mesh_dim_names:
1135
+ submesh_dp_size = torch_device_mesh["dp"].size()
1136
+ if "fsdp" in torch_device_mesh.mesh_dim_names:
1137
+ submesh_fsdp_size = torch_device_mesh["fsdp"].size()
1138
+ process_index = process_index // submesh_tp_size
1139
+ num_processes = submesh_fsdp_size * submesh_dp_size
1140
+
1141
+ # Sanity check
1142
+ if split_batches:
1143
+ if dataloader.batch_size is not None:
1144
+ batch_size_for_check = dataloader.batch_size
1145
+ else:
1146
+ # For custom batch_sampler
1147
+ if hasattr(dataloader.batch_sampler, "batch_size"):
1148
+ batch_size_for_check = dataloader.batch_sampler.batch_size
1149
+ else:
1150
+ raise ValueError(
1151
+ "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed "
1152
+ "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. "
1153
+ "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` "
1154
+ f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set."
1155
+ )
1156
+
1157
+ if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0:
1158
+ raise ValueError(
1159
+ f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) "
1160
+ f"needs to be a round multiple of the number of processes ({num_processes})."
1161
+ )
1162
+
1163
+ new_dataset = dataloader.dataset
1164
+ # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it
1165
+ new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None
1166
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1167
+ synchronized_generator = None
1168
+
1169
+ sampler = get_sampler(dataloader)
1170
+ if isinstance(sampler, RandomSampler) and use_seedable_sampler:
1171
+ # When iterating through the dataloader during distributed processes
1172
+ # we want to ensure that on each process we are iterating through the same
1173
+ # samples in the same order if a seed is set. This requires a tweak
1174
+ # to the `torch.utils.data.RandomSampler` class (if used).
1175
+ sampler = SeedableRandomSampler(
1176
+ data_source=sampler.data_source,
1177
+ replacement=sampler.replacement,
1178
+ num_samples=sampler._num_samples,
1179
+ generator=getattr(
1180
+ sampler,
1181
+ "generator",
1182
+ torch.Generator(device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"),
1183
+ ),
1184
+ data_seed=data_seed,
1185
+ )
1186
+
1187
+ if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA:
1188
+ # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled.
1189
+ generator = torch.Generator(
1190
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
1191
+ )
1192
+ seed = int(torch.empty((), dtype=torch.int64).random_().item())
1193
+ generator.manual_seed(seed)
1194
+ dataloader.generator = generator
1195
+ dataloader.sampler.generator = generator
1196
+ # No change if no multiprocess
1197
+ if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches:
1198
+ if is_datasets_available():
1199
+ from datasets import IterableDataset as DatasetsIterableDataset
1200
+ if (
1201
+ is_datasets_available()
1202
+ and isinstance(new_dataset, DatasetsIterableDataset)
1203
+ and not split_batches
1204
+ and new_dataset.n_shards > num_processes
1205
+ ):
1206
+ new_dataset = new_dataset.shard(num_shards=num_processes, index=process_index)
1207
+ elif isinstance(new_dataset, IterableDataset):
1208
+ if getattr(dataloader.dataset, "generator", None) is not None:
1209
+ synchronized_generator = dataloader.dataset.generator
1210
+ new_dataset = IterableDatasetShard(
1211
+ new_dataset,
1212
+ batch_size=dataloader.batch_size,
1213
+ drop_last=dataloader.drop_last,
1214
+ num_processes=num_processes,
1215
+ process_index=process_index,
1216
+ split_batches=split_batches,
1217
+ )
1218
+ else:
1219
+ if not use_seedable_sampler and hasattr(sampler, "generator"):
1220
+ if sampler.generator is None:
1221
+ sampler.generator = torch.Generator(
1222
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
1223
+ )
1224
+ seed = int(torch.empty((), dtype=torch.int64).random_().item())
1225
+ sampler.generator.manual_seed(seed)
1226
+ synchronized_generator = sampler.generator
1227
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1228
+ new_batch_sampler = BatchSamplerShard(
1229
+ batch_sampler,
1230
+ num_processes=num_processes,
1231
+ process_index=process_index,
1232
+ split_batches=split_batches,
1233
+ even_batches=even_batches,
1234
+ )
1235
+
1236
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1237
+ ignore_kwargs = [
1238
+ "batch_size",
1239
+ "shuffle",
1240
+ "sampler",
1241
+ "batch_sampler",
1242
+ "drop_last",
1243
+ ]
1244
+
1245
+ if rng_types is not None and synchronized_generator is None and "generator" in rng_types:
1246
+ rng_types.remove("generator")
1247
+
1248
+ kwargs = {
1249
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1250
+ for k in _PYTORCH_DATALOADER_KWARGS
1251
+ if k not in ignore_kwargs
1252
+ }
1253
+
1254
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1255
+ if new_batch_sampler is None:
1256
+ kwargs["drop_last"] = dataloader.drop_last
1257
+ kwargs["batch_size"] = (
1258
+ dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size
1259
+ )
1260
+ if dispatch_batches:
1261
+ kwargs.pop("generator")
1262
+ dataloader = DataLoaderDispatcher(
1263
+ new_dataset,
1264
+ split_batches=split_batches,
1265
+ batch_sampler=new_batch_sampler,
1266
+ _drop_last=dataloader.drop_last,
1267
+ _non_blocking=non_blocking,
1268
+ slice_fn=slice_fn_for_dispatch,
1269
+ use_stateful_dataloader=use_stateful_dataloader,
1270
+ torch_device_mesh=torch_device_mesh,
1271
+ **kwargs,
1272
+ )
1273
+ elif sampler_is_batch_sampler:
1274
+ dataloader = DataLoaderShard(
1275
+ new_dataset,
1276
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1277
+ sampler=new_batch_sampler,
1278
+ batch_size=dataloader.batch_size,
1279
+ rng_types=rng_types,
1280
+ _drop_last=dataloader.drop_last,
1281
+ _non_blocking=non_blocking,
1282
+ synchronized_generator=synchronized_generator,
1283
+ use_stateful_dataloader=use_stateful_dataloader,
1284
+ **kwargs,
1285
+ )
1286
+ else:
1287
+ dataloader = DataLoaderShard(
1288
+ new_dataset,
1289
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1290
+ batch_sampler=new_batch_sampler,
1291
+ rng_types=rng_types,
1292
+ synchronized_generator=synchronized_generator,
1293
+ _drop_last=dataloader.drop_last,
1294
+ _non_blocking=non_blocking,
1295
+ use_stateful_dataloader=use_stateful_dataloader,
1296
+ **kwargs,
1297
+ )
1298
+
1299
+ if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler:
1300
+ dataloader.set_sampler(sampler)
1301
+ if state.distributed_type == DistributedType.XLA:
1302
+ return MpDeviceLoaderWrapper(dataloader, device)
1303
+ return dataloader
1304
+
1305
+
1306
+ class SkipBatchSampler(BatchSampler):
1307
+ """
1308
+ A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`.
1309
+ Should not be used if the original dataloader is a `StatefulDataLoader`.
1310
+ """
1311
+
1312
+ def __init__(self, batch_sampler, skip_batches=0):
1313
+ self.batch_sampler = batch_sampler
1314
+ self.skip_batches = skip_batches
1315
+
1316
+ def __iter__(self):
1317
+ for index, samples in enumerate(self.batch_sampler):
1318
+ if index >= self.skip_batches:
1319
+ yield samples
1320
+
1321
+ @property
1322
+ def total_length(self):
1323
+ return len(self.batch_sampler)
1324
+
1325
+ def __len__(self):
1326
+ return len(self.batch_sampler) - self.skip_batches
1327
+
1328
+
1329
+ class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin):
1330
+ """
1331
+ Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use
1332
+ `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class.
1333
+
1334
+ Args:
1335
+ dataset (`torch.utils.data.dataset.Dataset`):
1336
+ The dataset to use to build this dataloader.
1337
+ skip_batches (`int`, *optional*, defaults to 0):
1338
+ The number of batches to skip at the beginning.
1339
+ kwargs:
1340
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
1341
+ """
1342
+
1343
+ def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs):
1344
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
1345
+ self.skip_batches = skip_batches
1346
+ self.gradient_state = GradientState()
1347
+
1348
+ def __iter__(self):
1349
+ self.begin()
1350
+ for index, batch in enumerate(self.base_dataloader.__iter__()):
1351
+ if index >= self.skip_batches:
1352
+ self._update_state_dict()
1353
+ yield batch
1354
+ self.end()
1355
+
1356
+ def __len__(self):
1357
+ return len(self.base_dataloader) - self.skip_batches
1358
+
1359
+ def __reduce__(self):
1360
+ """
1361
+ Define the `__reduce__` method to ensure a `SkipDataLoader` can be pickled and unpickled. This needs to be
1362
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
1363
+ `__class__` member.
1364
+ """
1365
+ args = super().__reduce__()
1366
+ return (SkipDataLoader, *args[1:])
1367
+
1368
+
1369
+ def skip_first_batches(dataloader, num_batches=0):
1370
+ """
1371
+ Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if
1372
+ the original dataloader is a `StatefulDataLoader`.
1373
+ """
1374
+ state = PartialState()
1375
+ if state.distributed_type == DistributedType.XLA:
1376
+ device = dataloader.device
1377
+ dataloader = dataloader.dataloader
1378
+
1379
+ dataset = dataloader.dataset
1380
+ sampler_is_batch_sampler = False
1381
+ if isinstance(dataset, IterableDataset):
1382
+ new_batch_sampler = None
1383
+ else:
1384
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1385
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1386
+ new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches)
1387
+
1388
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1389
+ ignore_kwargs = [
1390
+ "batch_size",
1391
+ "shuffle",
1392
+ "sampler",
1393
+ "batch_sampler",
1394
+ "drop_last",
1395
+ ]
1396
+
1397
+ kwargs = {
1398
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1399
+ for k in _PYTORCH_DATALOADER_KWARGS
1400
+ if k not in ignore_kwargs
1401
+ }
1402
+
1403
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1404
+ if new_batch_sampler is None:
1405
+ kwargs["drop_last"] = dataloader.drop_last
1406
+ kwargs["batch_size"] = dataloader.batch_size
1407
+
1408
+ if isinstance(dataloader, DataLoaderDispatcher):
1409
+ if new_batch_sampler is None:
1410
+ # Need to manually skip batches in the dataloader
1411
+ kwargs["skip_batches"] = num_batches
1412
+ dataloader = DataLoaderDispatcher(
1413
+ dataset,
1414
+ split_batches=dataloader.split_batches,
1415
+ batch_sampler=new_batch_sampler,
1416
+ _drop_last=dataloader._drop_last,
1417
+ **kwargs,
1418
+ )
1419
+ elif isinstance(dataloader, DataLoaderShard):
1420
+ if new_batch_sampler is None:
1421
+ # Need to manually skip batches in the dataloader
1422
+ kwargs["skip_batches"] = num_batches
1423
+ elif sampler_is_batch_sampler:
1424
+ kwargs["sampler"] = new_batch_sampler
1425
+ kwargs["batch_size"] = dataloader.batch_size
1426
+ else:
1427
+ kwargs["batch_sampler"] = new_batch_sampler
1428
+ dataloader = DataLoaderShard(
1429
+ dataset,
1430
+ device=dataloader.device,
1431
+ rng_types=dataloader.rng_types,
1432
+ synchronized_generator=dataloader.synchronized_generator,
1433
+ **kwargs,
1434
+ )
1435
+ else:
1436
+ if new_batch_sampler is None:
1437
+ # Need to manually skip batches in the dataloader
1438
+ dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs)
1439
+ else:
1440
+ dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs)
1441
+
1442
+ if state.distributed_type == DistributedType.XLA:
1443
+ dataloader = MpDeviceLoaderWrapper(dataloader, device)
1444
+
1445
+ return dataloader
python_embeded/Lib/site-packages/accelerate/hooks.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import functools
16
+ from collections.abc import Mapping
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from .state import PartialState
23
+ from .utils import (
24
+ PrefixedDataset,
25
+ find_device,
26
+ named_module_tensors,
27
+ send_to_device,
28
+ set_module_tensor_to_device,
29
+ )
30
+ from .utils.imports import (
31
+ is_mlu_available,
32
+ is_musa_available,
33
+ is_npu_available,
34
+ )
35
+ from .utils.memory import clear_device_cache
36
+ from .utils.modeling import get_non_persistent_buffers
37
+ from .utils.other import recursive_getattr
38
+
39
+
40
+ _accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "sdaa", "musa"]
41
+
42
+
43
+ class ModelHook:
44
+ """
45
+ A hook that contains callbacks to be executed just before and after the forward method of a model. The difference
46
+ with PyTorch existing hooks is that they get passed along the kwargs.
47
+
48
+ Class attribute:
49
+ - **no_grad** (`bool`, *optional*, defaults to `False`) -- Whether or not to execute the actual forward pass under
50
+ the `torch.no_grad()` context manager.
51
+ """
52
+
53
+ no_grad = False
54
+
55
+ def init_hook(self, module):
56
+ """
57
+ To be executed when the hook is attached to the module.
58
+
59
+ Args:
60
+ module (`torch.nn.Module`): The module attached to this hook.
61
+ """
62
+ return module
63
+
64
+ def pre_forward(self, module, *args, **kwargs):
65
+ """
66
+ To be executed just before the forward method of the model.
67
+
68
+ Args:
69
+ module (`torch.nn.Module`): The module whose forward pass will be executed just after this event.
70
+ args (`Tuple[Any]`): The positional arguments passed to the module.
71
+ kwargs (`Dict[Str, Any]`): The keyword arguments passed to the module.
72
+
73
+ Returns:
74
+ `Tuple[Tuple[Any], Dict[Str, Any]]`: A tuple with the treated `args` and `kwargs`.
75
+ """
76
+ return args, kwargs
77
+
78
+ def post_forward(self, module, output):
79
+ """
80
+ To be executed just after the forward method of the model.
81
+
82
+ Args:
83
+ module (`torch.nn.Module`): The module whose forward pass been executed just before this event.
84
+ output (`Any`): The output of the module.
85
+
86
+ Returns:
87
+ `Any`: The processed `output`.
88
+ """
89
+ return output
90
+
91
+ def detach_hook(self, module):
92
+ """
93
+ To be executed when the hook is detached from a module.
94
+
95
+ Args:
96
+ module (`torch.nn.Module`): The module detached from this hook.
97
+ """
98
+ return module
99
+
100
+
101
+ class SequentialHook(ModelHook):
102
+ """
103
+ A hook that can contain several hooks and iterates through them at each event.
104
+ """
105
+
106
+ def __init__(self, *hooks):
107
+ self.hooks = hooks
108
+
109
+ def init_hook(self, module):
110
+ for hook in self.hooks:
111
+ module = hook.init_hook(module)
112
+ return module
113
+
114
+ def pre_forward(self, module, *args, **kwargs):
115
+ for hook in self.hooks:
116
+ args, kwargs = hook.pre_forward(module, *args, **kwargs)
117
+ return args, kwargs
118
+
119
+ def post_forward(self, module, output):
120
+ for hook in self.hooks:
121
+ output = hook.post_forward(module, output)
122
+ return output
123
+
124
+ def detach_hook(self, module):
125
+ for hook in self.hooks:
126
+ module = hook.detach_hook(module)
127
+ return module
128
+
129
+
130
+ def add_hook_to_module(module: nn.Module, hook: ModelHook, append: bool = False):
131
+ """
132
+ Adds a hook to a given module. This will rewrite the `forward` method of the module to include the hook, to remove
133
+ this behavior and restore the original `forward` method, use `remove_hook_from_module`.
134
+
135
+ <Tip warning={true}>
136
+
137
+ If the module already contains a hook, this will replace it with the new hook passed by default. To chain two hooks
138
+ together, pass `append=True`, so it chains the current and new hook into an instance of the `SequentialHook` class.
139
+
140
+ </Tip>
141
+
142
+ Args:
143
+ module (`torch.nn.Module`):
144
+ The module to attach a hook to.
145
+ hook (`ModelHook`):
146
+ The hook to attach.
147
+ append (`bool`, *optional*, defaults to `False`):
148
+ Whether the hook should be chained with an existing one (if module already contains a hook) or not.
149
+
150
+ Returns:
151
+ `torch.nn.Module`: The same module, with the hook attached (the module is modified in place, so the result can
152
+ be discarded).
153
+ """
154
+ if append and (getattr(module, "_hf_hook", None) is not None):
155
+ old_hook = module._hf_hook
156
+ remove_hook_from_module(module)
157
+ hook = SequentialHook(old_hook, hook)
158
+
159
+ if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"):
160
+ # If we already put some hook on this module, we replace it with the new one.
161
+ old_forward = module._old_forward
162
+ else:
163
+ old_forward = module.forward
164
+ module._old_forward = old_forward
165
+
166
+ module = hook.init_hook(module)
167
+ module._hf_hook = hook
168
+
169
+ def new_forward(module, *args, **kwargs):
170
+ args, kwargs = module._hf_hook.pre_forward(module, *args, **kwargs)
171
+ if module._hf_hook.no_grad:
172
+ with torch.no_grad():
173
+ output = module._old_forward(*args, **kwargs)
174
+ else:
175
+ output = module._old_forward(*args, **kwargs)
176
+ return module._hf_hook.post_forward(module, output)
177
+
178
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
179
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
180
+ if "GraphModuleImpl" in str(type(module)):
181
+ module.__class__.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
182
+ else:
183
+ module.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
184
+
185
+ return module
186
+
187
+
188
+ def remove_hook_from_module(module: nn.Module, recurse=False):
189
+ """
190
+ Removes any hook attached to a module via `add_hook_to_module`.
191
+
192
+ Args:
193
+ module (`torch.nn.Module`): The module to attach a hook to.
194
+ recurse (`bool`, **optional**): Whether to remove the hooks recursively
195
+
196
+ Returns:
197
+ `torch.nn.Module`: The same module, with the hook detached (the module is modified in place, so the result can
198
+ be discarded).
199
+ """
200
+
201
+ if hasattr(module, "_hf_hook"):
202
+ module._hf_hook.detach_hook(module)
203
+ delattr(module, "_hf_hook")
204
+
205
+ if hasattr(module, "_old_forward"):
206
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
207
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
208
+ if "GraphModuleImpl" in str(type(module)):
209
+ module.__class__.forward = module._old_forward
210
+ else:
211
+ module.forward = module._old_forward
212
+ delattr(module, "_old_forward")
213
+
214
+ # Remove accelerate added warning hooks from dispatch_model
215
+ for attr in _accelerate_added_attributes:
216
+ module.__dict__.pop(attr, None)
217
+
218
+ if recurse:
219
+ for child in module.children():
220
+ remove_hook_from_module(child, recurse)
221
+
222
+ return module
223
+
224
+
225
+ class AlignDevicesHook(ModelHook):
226
+ """
227
+ A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the
228
+ associated module, potentially offloading the weights after the forward pass.
229
+
230
+ Args:
231
+ execution_device (`torch.device`, *optional*):
232
+ The device on which inputs and model weights should be placed before the forward pass.
233
+ offload (`bool`, *optional*, defaults to `False`):
234
+ Whether or not the weights should be offloaded after the forward pass.
235
+ io_same_device (`bool`, *optional*, defaults to `False`):
236
+ Whether or not the output should be placed on the same device as the input was.
237
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
238
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
239
+ offload_buffers (`bool`, *optional*, defaults to `False`):
240
+ Whether or not to include the associated module's buffers when offloading.
241
+ place_submodules (`bool`, *optional*, defaults to `False`):
242
+ Whether to place the submodules on `execution_device` during the `init_hook` event.
243
+ """
244
+
245
+ def __init__(
246
+ self,
247
+ execution_device: Optional[Union[int, str, torch.device]] = None,
248
+ offload: bool = False,
249
+ io_same_device: bool = False,
250
+ weights_map: Optional[Mapping] = None,
251
+ offload_buffers: bool = False,
252
+ place_submodules: bool = False,
253
+ skip_keys: Optional[Union[str, list[str]]] = None,
254
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
255
+ ):
256
+ self.execution_device = execution_device
257
+ self.offload = offload
258
+ self.io_same_device = io_same_device
259
+ self.weights_map = weights_map
260
+ self.offload_buffers = offload_buffers
261
+ self.place_submodules = place_submodules
262
+ self.skip_keys = skip_keys
263
+
264
+ # Will contain the input device when `io_same_device=True`.
265
+ self.input_device = None
266
+ self.param_original_devices = {}
267
+ self.buffer_original_devices = {}
268
+ self.tied_params_names = set()
269
+
270
+ # The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory
271
+ # for tied weights already loaded on the target execution device.
272
+ self.tied_params_map = tied_params_map
273
+
274
+ def __repr__(self):
275
+ return (
276
+ f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, "
277
+ f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, "
278
+ f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})"
279
+ )
280
+
281
+ def init_hook(self, module):
282
+ # In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero.
283
+ if self.execution_device == "meta" or self.execution_device == torch.device("meta"):
284
+ self.tied_params_map = None
285
+
286
+ if not self.offload and self.execution_device is not None:
287
+ for name, _ in named_module_tensors(module, recurse=self.place_submodules):
288
+ set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map)
289
+ elif self.offload:
290
+ self.original_devices = {
291
+ name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules)
292
+ }
293
+ if self.weights_map is None:
294
+ self.weights_map = {
295
+ name: param.to("cpu")
296
+ for name, param in named_module_tensors(
297
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules
298
+ )
299
+ }
300
+ for name, _ in named_module_tensors(
301
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True
302
+ ):
303
+ # When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer,
304
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
305
+ # As we have no reliable way to track the shared data pointer of tied weights in this case, we use tied_params_names: List[str]
306
+ # to add on the fly pointers to `tied_params_map` in the pre_forward call.
307
+ if (
308
+ self.tied_params_map is not None
309
+ and recursive_getattr(module, name).data_ptr() in self.tied_params_map
310
+ ):
311
+ self.tied_params_names.add(name)
312
+
313
+ set_module_tensor_to_device(module, name, "meta")
314
+
315
+ if not self.offload_buffers and self.execution_device is not None:
316
+ for name, _ in module.named_buffers(recurse=self.place_submodules):
317
+ set_module_tensor_to_device(
318
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
319
+ )
320
+ elif self.offload_buffers and self.execution_device is not None:
321
+ for name in get_non_persistent_buffers(module, recurse=self.place_submodules):
322
+ set_module_tensor_to_device(
323
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
324
+ )
325
+
326
+ return module
327
+
328
+ def pre_forward(self, module, *args, **kwargs):
329
+ if self.io_same_device:
330
+ self.input_device = find_device([args, kwargs])
331
+ if self.offload:
332
+ self.tied_pointers_to_remove = set()
333
+
334
+ for name, _ in named_module_tensors(
335
+ module,
336
+ include_buffers=self.offload_buffers,
337
+ recurse=self.place_submodules,
338
+ remove_non_persistent=True,
339
+ ):
340
+ fp16_statistics = None
341
+ value = self.weights_map[name]
342
+ if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys():
343
+ if value.dtype == torch.int8:
344
+ fp16_statistics = self.weights_map[name.replace("weight", "SCB")]
345
+
346
+ # In case we are using offloading with tied weights, we need to keep track of the offloaded weights
347
+ # that are loaded on device at this point, as we will need to remove them as well from the dictionary
348
+ # self.tied_params_map in order to allow to free memory.
349
+ if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map:
350
+ self.tied_params_map[value.data_ptr()] = {}
351
+
352
+ if (
353
+ value is not None
354
+ and self.tied_params_map is not None
355
+ and value.data_ptr() in self.tied_params_map
356
+ and self.execution_device not in self.tied_params_map[value.data_ptr()]
357
+ ):
358
+ self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device))
359
+
360
+ set_module_tensor_to_device(
361
+ module,
362
+ name,
363
+ self.execution_device,
364
+ value=value,
365
+ fp16_statistics=fp16_statistics,
366
+ tied_params_map=self.tied_params_map,
367
+ )
368
+
369
+ return send_to_device(args, self.execution_device), send_to_device(
370
+ kwargs, self.execution_device, skip_keys=self.skip_keys
371
+ )
372
+
373
+ def post_forward(self, module, output):
374
+ if self.offload:
375
+ for name, _ in named_module_tensors(
376
+ module,
377
+ include_buffers=self.offload_buffers,
378
+ recurse=self.place_submodules,
379
+ remove_non_persistent=True,
380
+ ):
381
+ set_module_tensor_to_device(module, name, "meta")
382
+ if type(module).__name__ == "Linear8bitLt":
383
+ module.state.SCB = None
384
+ module.state.CxB = None
385
+
386
+ # We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from
387
+ # this dictionary to allow the garbage collector to do its job.
388
+ for value_pointer, device in self.tied_pointers_to_remove:
389
+ if isinstance(device, int):
390
+ if is_npu_available():
391
+ device = f"npu:{device}"
392
+ elif is_mlu_available():
393
+ device = f"mlu:{device}"
394
+ elif is_musa_available():
395
+ device = f"musa:{device}"
396
+ if device in self.tied_params_map[value_pointer]:
397
+ del self.tied_params_map[value_pointer][device]
398
+ self.tied_pointers_to_remove = set()
399
+ if self.io_same_device and self.input_device is not None:
400
+ output = send_to_device(output, self.input_device, skip_keys=self.skip_keys)
401
+
402
+ return output
403
+
404
+ def detach_hook(self, module):
405
+ if self.offload:
406
+ for name, device in self.original_devices.items():
407
+ if device != torch.device("meta"):
408
+ set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None))
409
+ return module
410
+
411
+
412
+ def attach_execution_device_hook(
413
+ module: torch.nn.Module,
414
+ execution_device: Union[int, str, torch.device],
415
+ skip_keys: Optional[Union[str, list[str]]] = None,
416
+ preload_module_classes: Optional[list[str]] = None,
417
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
418
+ ):
419
+ """
420
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model to make sure they have the right
421
+ execution device
422
+
423
+ Args:
424
+ module (`torch.nn.Module`):
425
+ The module where we want to attach the hooks.
426
+ execution_device (`int`, `str` or `torch.device`):
427
+ The device on which inputs and model weights should be placed before the forward pass.
428
+ skip_keys (`str` or `List[str]`, *optional*):
429
+ A list of keys to ignore when moving inputs or outputs between devices.
430
+ preload_module_classes (`List[str]`, *optional*):
431
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
432
+ of the forward. This should only be used for classes that have submodules which are registered but not
433
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
434
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
435
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
436
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
437
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
438
+ instead of duplicating memory.
439
+ """
440
+ if not hasattr(module, "_hf_hook") and len(module.state_dict()) > 0:
441
+ add_hook_to_module(
442
+ module,
443
+ AlignDevicesHook(execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map),
444
+ )
445
+
446
+ # Break the recursion if we get to a preload module.
447
+ if preload_module_classes is not None and module.__class__.__name__ in preload_module_classes:
448
+ return
449
+
450
+ for child in module.children():
451
+ attach_execution_device_hook(
452
+ child,
453
+ execution_device,
454
+ skip_keys=skip_keys,
455
+ preload_module_classes=preload_module_classes,
456
+ tied_params_map=tied_params_map,
457
+ )
458
+
459
+
460
+ def attach_align_device_hook(
461
+ module: torch.nn.Module,
462
+ execution_device: Optional[torch.device] = None,
463
+ offload: bool = False,
464
+ weights_map: Optional[Mapping] = None,
465
+ offload_buffers: bool = False,
466
+ module_name: str = "",
467
+ skip_keys: Optional[Union[str, list[str]]] = None,
468
+ preload_module_classes: Optional[list[str]] = None,
469
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
470
+ ):
471
+ """
472
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model that have direct parameters and/or
473
+ buffers.
474
+
475
+ Args:
476
+ module (`torch.nn.Module`):
477
+ The module where we want to attach the hooks.
478
+ execution_device (`torch.device`, *optional*):
479
+ The device on which inputs and model weights should be placed before the forward pass.
480
+ offload (`bool`, *optional*, defaults to `False`):
481
+ Whether or not the weights should be offloaded after the forward pass.
482
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
483
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
484
+ offload_buffers (`bool`, *optional*, defaults to `False`):
485
+ Whether or not to include the associated module's buffers when offloading.
486
+ module_name (`str`, *optional*, defaults to `""`):
487
+ The name of the module.
488
+ skip_keys (`str` or `List[str]`, *optional*):
489
+ A list of keys to ignore when moving inputs or outputs between devices.
490
+ preload_module_classes (`List[str]`, *optional*):
491
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
492
+ of the forward. This should only be used for classes that have submodules which are registered but not
493
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
494
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
495
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
496
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
497
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
498
+ instead of duplicating memory.
499
+ """
500
+ # Attach the hook on this module if it has any direct tensor.
501
+ directs = named_module_tensors(module)
502
+ full_offload = (
503
+ offload and preload_module_classes is not None and module.__class__.__name__ in preload_module_classes
504
+ )
505
+
506
+ if len(list(directs)) > 0 or full_offload:
507
+ if weights_map is not None:
508
+ prefix = f"{module_name}." if len(module_name) > 0 else ""
509
+ prefixed_weights_map = PrefixedDataset(weights_map, prefix)
510
+ else:
511
+ prefixed_weights_map = None
512
+ hook = AlignDevicesHook(
513
+ execution_device=execution_device,
514
+ offload=offload,
515
+ weights_map=prefixed_weights_map,
516
+ offload_buffers=offload_buffers,
517
+ place_submodules=full_offload,
518
+ skip_keys=skip_keys,
519
+ tied_params_map=tied_params_map,
520
+ )
521
+ add_hook_to_module(module, hook, append=True)
522
+
523
+ # We stop the recursion in case we hit the full offload.
524
+ if full_offload:
525
+ return
526
+
527
+ # Recurse on all children of the module.
528
+ for child_name, child in module.named_children():
529
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
530
+ attach_align_device_hook(
531
+ child,
532
+ execution_device=execution_device,
533
+ offload=offload,
534
+ weights_map=weights_map,
535
+ offload_buffers=offload_buffers,
536
+ module_name=child_name,
537
+ preload_module_classes=preload_module_classes,
538
+ skip_keys=skip_keys,
539
+ tied_params_map=tied_params_map,
540
+ )
541
+
542
+
543
+ def remove_hook_from_submodules(module: nn.Module):
544
+ """
545
+ Recursively removes all hooks attached on the submodules of a given model.
546
+
547
+ Args:
548
+ module (`torch.nn.Module`): The module on which to remove all hooks.
549
+ """
550
+ remove_hook_from_module(module)
551
+ for child in module.children():
552
+ remove_hook_from_submodules(child)
553
+
554
+
555
+ def attach_align_device_hook_on_blocks(
556
+ module: nn.Module,
557
+ execution_device: Optional[Union[torch.device, dict[str, torch.device]]] = None,
558
+ offload: Union[bool, dict[str, bool]] = False,
559
+ weights_map: Mapping = None,
560
+ offload_buffers: bool = False,
561
+ module_name: str = "",
562
+ skip_keys: Optional[Union[str, list[str]]] = None,
563
+ preload_module_classes: Optional[list[str]] = None,
564
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
565
+ ):
566
+ """
567
+ Attaches `AlignDevicesHook` to all blocks of a given model as needed.
568
+
569
+ Args:
570
+ module (`torch.nn.Module`):
571
+ The module where we want to attach the hooks.
572
+ execution_device (`torch.device` or `Dict[str, torch.device]`, *optional*):
573
+ The device on which inputs and model weights should be placed before the forward pass. It can be one device
574
+ for the whole module, or a dictionary mapping module name to device.
575
+ offload (`bool`, *optional*, defaults to `False`):
576
+ Whether or not the weights should be offloaded after the forward pass. It can be one boolean for the whole
577
+ module, or a dictionary mapping module name to boolean.
578
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
579
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
580
+ offload_buffers (`bool`, *optional*, defaults to `False`):
581
+ Whether or not to include the associated module's buffers when offloading.
582
+ module_name (`str`, *optional*, defaults to `""`):
583
+ The name of the module.
584
+ skip_keys (`str` or `List[str]`, *optional*):
585
+ A list of keys to ignore when moving inputs or outputs between devices.
586
+ preload_module_classes (`List[str]`, *optional*):
587
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
588
+ of the forward. This should only be used for classes that have submodules which are registered but not
589
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
590
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
591
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
592
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
593
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
594
+ instead of duplicating memory.
595
+ """
596
+ # If one device and one offload, we've got one hook.
597
+ if not isinstance(execution_device, Mapping) and not isinstance(offload, dict):
598
+ if not offload:
599
+ hook = AlignDevicesHook(
600
+ execution_device=execution_device,
601
+ io_same_device=True,
602
+ skip_keys=skip_keys,
603
+ place_submodules=True,
604
+ tied_params_map=tied_params_map,
605
+ )
606
+ add_hook_to_module(module, hook)
607
+ else:
608
+ attach_align_device_hook(
609
+ module,
610
+ execution_device=execution_device,
611
+ offload=True,
612
+ weights_map=weights_map,
613
+ offload_buffers=offload_buffers,
614
+ module_name=module_name,
615
+ skip_keys=skip_keys,
616
+ tied_params_map=tied_params_map,
617
+ )
618
+ return
619
+
620
+ if not isinstance(execution_device, Mapping):
621
+ execution_device = {key: execution_device for key in offload.keys()}
622
+ if not isinstance(offload, Mapping):
623
+ offload = {key: offload for key in execution_device.keys()}
624
+
625
+ if module_name in execution_device and module_name in offload and not offload[module_name]:
626
+ hook = AlignDevicesHook(
627
+ execution_device=execution_device[module_name],
628
+ offload_buffers=offload_buffers,
629
+ io_same_device=(module_name == ""),
630
+ place_submodules=True,
631
+ skip_keys=skip_keys,
632
+ tied_params_map=tied_params_map,
633
+ )
634
+ add_hook_to_module(module, hook)
635
+ attach_execution_device_hook(
636
+ module, execution_device[module_name], skip_keys=skip_keys, tied_params_map=tied_params_map
637
+ )
638
+ elif module_name in execution_device and module_name in offload:
639
+ attach_align_device_hook(
640
+ module,
641
+ execution_device=execution_device[module_name],
642
+ offload=True,
643
+ weights_map=weights_map,
644
+ offload_buffers=offload_buffers,
645
+ module_name=module_name,
646
+ skip_keys=skip_keys,
647
+ preload_module_classes=preload_module_classes,
648
+ tied_params_map=tied_params_map,
649
+ )
650
+ if not hasattr(module, "_hf_hook"):
651
+ hook = AlignDevicesHook(
652
+ execution_device=execution_device[module_name],
653
+ io_same_device=(module_name == ""),
654
+ skip_keys=skip_keys,
655
+ tied_params_map=tied_params_map,
656
+ )
657
+ add_hook_to_module(module, hook)
658
+ attach_execution_device_hook(
659
+ module,
660
+ execution_device[module_name],
661
+ preload_module_classes=preload_module_classes,
662
+ skip_keys=skip_keys,
663
+ tied_params_map=tied_params_map,
664
+ )
665
+ elif module_name == "":
666
+ hook = AlignDevicesHook(
667
+ execution_device=execution_device.get(""),
668
+ io_same_device=True,
669
+ skip_keys=skip_keys,
670
+ tied_params_map=tied_params_map,
671
+ )
672
+ add_hook_to_module(module, hook)
673
+
674
+ for child_name, child in module.named_children():
675
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
676
+ attach_align_device_hook_on_blocks(
677
+ child,
678
+ execution_device=execution_device,
679
+ offload=offload,
680
+ weights_map=weights_map,
681
+ offload_buffers=offload_buffers,
682
+ module_name=child_name,
683
+ preload_module_classes=preload_module_classes,
684
+ skip_keys=skip_keys,
685
+ tied_params_map=tied_params_map,
686
+ )
687
+
688
+
689
+ class CpuOffload(ModelHook):
690
+ """
691
+ Offloads a model on the CPU until its forward pass is called. The model will not be offloaded back to the CPU after
692
+ the forward, the user needs to call the `init_hook` method again for this.
693
+
694
+ Args:
695
+ execution_device(`str`, `int` or `torch.device`, *optional*):
696
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
697
+ GPU 0 if there is a GPU, and finally to the CPU.
698
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
699
+ The hook sent back by [`cpu_offload_with_hook`] for a previous model in the pipeline you are running. If
700
+ passed, its offload method will be called just before the forward of the model to which this hook is
701
+ attached.
702
+ """
703
+
704
+ def __init__(
705
+ self,
706
+ execution_device: Optional[Union[str, int, torch.device]] = None,
707
+ prev_module_hook: Optional["UserCpuOffloadHook"] = None,
708
+ ):
709
+ self.prev_module_hook = prev_module_hook
710
+
711
+ self.execution_device = execution_device if execution_device is not None else PartialState().default_device
712
+
713
+ def init_hook(self, module):
714
+ return module.to("cpu")
715
+
716
+ def pre_forward(self, module, *args, **kwargs):
717
+ if self.prev_module_hook is not None:
718
+ self.prev_module_hook.offload()
719
+ clear_device_cache()
720
+ module.to(self.execution_device)
721
+ return send_to_device(args, self.execution_device), send_to_device(kwargs, self.execution_device)
722
+
723
+
724
+ class UserCpuOffloadHook:
725
+ """
726
+ A simple hook grouping a model and a `ModelHook`, which provides easy APIs for to call the init method of the hook
727
+ or remove it entirely.
728
+ """
729
+
730
+ def __init__(self, model, hook):
731
+ self.model = model
732
+ self.hook = hook
733
+
734
+ def offload(self):
735
+ self.hook.init_hook(self.model)
736
+
737
+ def remove(self):
738
+ remove_hook_from_module(self.model)
739
+
740
+
741
+ class LayerwiseCastingHook(ModelHook):
742
+ r"""
743
+ A hook that casts the weights of a module to a high precision dtype for computation, and to a low precision dtype
744
+ for storage. This process may lead to quality loss in the output, but can significantly reduce the memory
745
+ footprint.
746
+ """
747
+
748
+ _is_stateful = False
749
+
750
+ def __init__(self, storage_dtype: torch.dtype, compute_dtype: torch.dtype, non_blocking: bool) -> None:
751
+ self.storage_dtype = storage_dtype
752
+ self.compute_dtype = compute_dtype
753
+ self.non_blocking = non_blocking
754
+
755
+ def init_hook(self, module: torch.nn.Module):
756
+ module.to(dtype=self.storage_dtype, non_blocking=self.non_blocking)
757
+ return module
758
+
759
+ def pre_forward(self, module: torch.nn.Module, *args, **kwargs):
760
+ module.to(dtype=self.compute_dtype, non_blocking=self.non_blocking)
761
+ return args, kwargs
762
+
763
+ def post_forward(self, module: torch.nn.Module, output):
764
+ module.to(dtype=self.storage_dtype, non_blocking=self.non_blocking)
765
+ return output
python_embeded/Lib/site-packages/accelerate/inference.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ from types import MethodType
16
+ from typing import Any, Optional, Union
17
+
18
+ from .state import PartialState
19
+ from .utils import (
20
+ calculate_maximum_sizes,
21
+ convert_bytes,
22
+ copy_tensor_to_devices,
23
+ ignorant_find_batch_size,
24
+ infer_auto_device_map,
25
+ is_pippy_available,
26
+ pad_input_tensors,
27
+ send_to_device,
28
+ )
29
+
30
+
31
+ def generate_device_map(model, num_processes: int = 1, no_split_module_classes=None, max_memory: dict = None):
32
+ """
33
+ Calculates the device map for `model` with an offset for PiPPy
34
+ """
35
+ if num_processes == 1:
36
+ return infer_auto_device_map(model, no_split_module_classes=no_split_module_classes, clean_result=False)
37
+ if max_memory is None:
38
+ model_size, shared = calculate_maximum_sizes(model)
39
+
40
+ # Split into `n` chunks for each GPU
41
+ memory = (model_size + shared[0]) / num_processes
42
+ memory = convert_bytes(memory)
43
+ value, ending = memory.split(" ")
44
+
45
+ # Add a chunk to deal with potential extra shared memory instances
46
+ memory = math.ceil(float(value)) * 1.1
47
+ memory = f"{memory} {ending}"
48
+ max_memory = {i: memory for i in range(num_processes)}
49
+ device_map = infer_auto_device_map(
50
+ model,
51
+ max_memory=max_memory,
52
+ no_split_module_classes=no_split_module_classes,
53
+ clean_result=False,
54
+ )
55
+ return device_map
56
+
57
+
58
+ def find_pippy_batch_size(args, kwargs):
59
+ found_batch_size = None
60
+ if args is not None:
61
+ for arg in args:
62
+ found_batch_size = ignorant_find_batch_size(arg)
63
+ if found_batch_size is not None:
64
+ break
65
+ if kwargs is not None and found_batch_size is None:
66
+ for kwarg in kwargs.values():
67
+ found_batch_size = ignorant_find_batch_size(kwarg)
68
+ if found_batch_size is not None:
69
+ break
70
+ return found_batch_size
71
+
72
+
73
+ def build_pipeline(model, split_points, args, kwargs, num_chunks):
74
+ """
75
+ Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing
76
+ in needed `args` and `kwargs` as the model needs on the CPU.
77
+
78
+ Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use
79
+ `AcceleratorState.num_processes`
80
+ """
81
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
82
+ from torch.distributed.pipelining import ScheduleGPipe, SplitPoint, pipeline
83
+
84
+ # We need to annotate the split points in the model for PiPPy
85
+ state = PartialState()
86
+ split_spec = {split_point: SplitPoint.BEGINNING for split_point in split_points}
87
+ pipe = pipeline(
88
+ model,
89
+ mb_args=args,
90
+ mb_kwargs=kwargs,
91
+ split_spec=split_spec,
92
+ )
93
+ stage = pipe.build_stage(state.local_process_index, device=state.device)
94
+ schedule = ScheduleGPipe(stage, num_chunks)
95
+
96
+ return schedule
97
+
98
+
99
+ def pippy_forward(forward, num_chunks, gather_output, *args, **kwargs):
100
+ state = PartialState()
101
+ output = None
102
+
103
+ if state.num_processes == 1:
104
+ output = forward(*args, **kwargs)
105
+ elif state.is_local_main_process:
106
+ found_batch_size = find_pippy_batch_size(args, kwargs)
107
+ if found_batch_size is None:
108
+ raise ValueError("Could not find batch size from args or kwargs")
109
+ else:
110
+ if found_batch_size != num_chunks:
111
+ args = pad_input_tensors(args, found_batch_size, num_chunks)
112
+ kwargs = pad_input_tensors(kwargs, found_batch_size, num_chunks)
113
+ forward(*args, **kwargs)
114
+ elif state.is_last_process:
115
+ output = forward()
116
+ else:
117
+ forward()
118
+ if gather_output:
119
+ # Each node will get a copy of the full output which is only on the last GPU
120
+ output = copy_tensor_to_devices(output)
121
+ return output
122
+
123
+
124
+ def prepare_pippy(
125
+ model,
126
+ split_points: Optional[Union[str, list[str]]] = "auto",
127
+ no_split_module_classes: Optional[list[str]] = None,
128
+ example_args: Optional[tuple[Any]] = (),
129
+ example_kwargs: Optional[dict[str, Any]] = None,
130
+ num_chunks: Optional[int] = None,
131
+ gather_output: Optional[bool] = False,
132
+ ):
133
+ """
134
+ Wraps `model` for pipeline parallel inference.
135
+
136
+ Args:
137
+ model (`torch.nn.Module`):
138
+ A model we want to split for pipeline-parallel inference
139
+ split_points (`str` or `List[str]`, defaults to 'auto'):
140
+ How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced
141
+ split given any model. Should be a list of layer names in the model to split by otherwise.
142
+ no_split_module_classes (`List[str]`):
143
+ A list of class names for layers we don't want to be split.
144
+ example_args (tuple of model inputs):
145
+ The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use
146
+ this method if possible.
147
+ example_kwargs (dict of model inputs)
148
+ The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a
149
+ *highly* limiting structure that requires the same keys be present at *all* inference calls. Not
150
+ recommended unless the prior condition is true for all cases.
151
+ num_chunks (`int`, defaults to the number of available GPUs):
152
+ The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but
153
+ this can be tuned and played with. In general one should have num_chunks >= num_gpus.
154
+ gather_output (`bool`, defaults to `False`):
155
+ If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs.
156
+ """
157
+ if not is_pippy_available():
158
+ raise ImportError("Using `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.")
159
+ state = PartialState()
160
+ example_args = send_to_device(example_args, "cpu")
161
+ example_kwargs = send_to_device(example_kwargs, "cpu")
162
+ if num_chunks is None:
163
+ num_chunks = state.num_processes
164
+ if split_points == "auto":
165
+ device_map = generate_device_map(model, num_chunks, no_split_module_classes=no_split_module_classes)
166
+ split_points = []
167
+ for i in range(1, num_chunks):
168
+ split_points.append(next(k for k, v in device_map.items() if v == i))
169
+ model.hf_split_points = split_points
170
+ stage = build_pipeline(model, split_points, example_args, example_kwargs, num_chunks)
171
+ model._original_forward = model.forward
172
+ model._original_call = model.__call__
173
+ model.pippy_stage = stage
174
+ model.hf_split_points = split_points
175
+
176
+ def forward(*args, **kwargs):
177
+ return pippy_forward(stage.step, num_chunks, gather_output, *args, **kwargs)
178
+
179
+ # To act like a decorator so that it can be popped when doing `extract_model_from_parallel`
180
+ # Note: creates an infinite recursion loop with `generate`
181
+ model_forward = MethodType(forward, model)
182
+ forward.__wrapped__ = model_forward
183
+ model.forward = forward
184
+ return model
python_embeded/Lib/site-packages/accelerate/launchers.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import sys
17
+ import tempfile
18
+
19
+ import torch
20
+
21
+ from .state import AcceleratorState, PartialState
22
+ from .utils import (
23
+ PrecisionType,
24
+ PrepareForLaunch,
25
+ are_libraries_initialized,
26
+ check_cuda_p2p_ib_support,
27
+ get_gpu_info,
28
+ is_mps_available,
29
+ is_torch_version,
30
+ patch_environment,
31
+ )
32
+ from .utils.constants import ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION
33
+
34
+
35
+ def test_launch():
36
+ "Verify a `PartialState` can be initialized."
37
+ _ = PartialState()
38
+
39
+
40
+ def notebook_launcher(
41
+ function,
42
+ args=(),
43
+ num_processes=None,
44
+ mixed_precision="no",
45
+ use_port="29500",
46
+ master_addr="127.0.0.1",
47
+ node_rank=0,
48
+ num_nodes=1,
49
+ rdzv_backend="static",
50
+ rdzv_endpoint="",
51
+ rdzv_conf=None,
52
+ rdzv_id="none",
53
+ max_restarts=0,
54
+ monitor_interval=0.1,
55
+ log_line_prefix_template=None,
56
+ ):
57
+ """
58
+ Launches a training function, using several processes or multiple nodes if it's possible in the current environment
59
+ (TPU with multiple cores for instance).
60
+
61
+ <Tip warning={true}>
62
+
63
+ To use this function absolutely zero calls to a CUDA device must be made in the notebook session before calling. If
64
+ any have been made, you will need to restart the notebook and make sure no cells use any CUDA capability.
65
+
66
+ Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none
67
+ of those calls have been made.
68
+
69
+ </Tip>
70
+
71
+ Args:
72
+ function (`Callable`):
73
+ The training function to execute. If it accepts arguments, the first argument should be the index of the
74
+ process run.
75
+ args (`Tuple`):
76
+ Tuple of arguments to pass to the function (it will receive `*args`).
77
+ num_processes (`int`, *optional*):
78
+ The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to
79
+ the number of GPUs available otherwise.
80
+ mixed_precision (`str`, *optional*, defaults to `"no"`):
81
+ If `fp16` or `bf16`, will use mixed precision training on multi-GPU.
82
+ use_port (`str`, *optional*, defaults to `"29500"`):
83
+ The port to use to communicate between processes when launching a multi-GPU training.
84
+ master_addr (`str`, *optional*, defaults to `"127.0.0.1"`):
85
+ The address to use for communication between processes.
86
+ node_rank (`int`, *optional*, defaults to 0):
87
+ The rank of the current node.
88
+ num_nodes (`int`, *optional*, defaults to 1):
89
+ The number of nodes to use for training.
90
+ rdzv_backend (`str`, *optional*, defaults to `"static"`):
91
+ The rendezvous method to use, such as 'static' (the default) or 'c10d'
92
+ rdzv_endpoint (`str`, *optional*, defaults to `""`):
93
+ The endpoint of the rdzv sync. storage.
94
+ rdzv_conf (`Dict`, *optional*, defaults to `None`):
95
+ Additional rendezvous configuration.
96
+ rdzv_id (`str`, *optional*, defaults to `"none"`):
97
+ The unique run id of the job.
98
+ max_restarts (`int`, *optional*, defaults to 0):
99
+ The maximum amount of restarts that elastic agent will conduct on workers before failure.
100
+ monitor_interval (`float`, *optional*, defaults to 0.1):
101
+ The interval in seconds that is used by the elastic_agent as a period of monitoring workers.
102
+ log_line_prefix_template (`str`, *optional*, defaults to `None`):
103
+ The prefix template for elastic launch logging. Available from PyTorch 2.2.0.
104
+
105
+ Example:
106
+
107
+ ```python
108
+ # Assume this is defined in a Jupyter Notebook on an instance with two GPUs
109
+ from accelerate import notebook_launcher
110
+
111
+
112
+ def train(*args):
113
+ # Your training function here
114
+ ...
115
+
116
+
117
+ notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16")
118
+ ```
119
+ """
120
+ # Are we in a google colab or a Kaggle Kernel?
121
+ in_colab = False
122
+ in_kaggle = False
123
+ if any(key.startswith("KAGGLE") for key in os.environ.keys()):
124
+ in_kaggle = True
125
+ elif "IPython" in sys.modules:
126
+ in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython())
127
+
128
+ try:
129
+ mixed_precision = PrecisionType(mixed_precision.lower())
130
+ except ValueError:
131
+ raise ValueError(
132
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
133
+ )
134
+
135
+ if (in_colab or in_kaggle) and (
136
+ (os.environ.get("TPU_NAME", None) is not None) or (os.environ.get("PJRT_DEVICE", "") == "TPU")
137
+ ):
138
+ # TPU launch
139
+ import torch_xla.distributed.xla_multiprocessing as xmp
140
+
141
+ if len(AcceleratorState._shared_state) > 0:
142
+ raise ValueError(
143
+ "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
144
+ "your training function. Restart your notebook and make sure no cells initializes an "
145
+ "`Accelerator`."
146
+ )
147
+
148
+ launcher = PrepareForLaunch(function, distributed_type="XLA")
149
+ print("Launching a training on TPU cores.")
150
+ xmp.spawn(launcher, args=args, start_method="fork")
151
+ elif in_colab and get_gpu_info()[1] < 2:
152
+ # No need for a distributed launch otherwise as it's either CPU or one GPU.
153
+ if torch.cuda.is_available():
154
+ print("Launching training on one GPU.")
155
+ else:
156
+ print("Launching training on one CPU.")
157
+ function(*args)
158
+ else:
159
+ if num_processes is None:
160
+ raise ValueError(
161
+ "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."
162
+ )
163
+ if node_rank >= num_nodes:
164
+ raise ValueError("The node_rank must be less than the number of nodes.")
165
+ if num_processes > 1:
166
+ # Multi-GPU launch
167
+ from torch.distributed.launcher.api import LaunchConfig, elastic_launch
168
+ from torch.multiprocessing import start_processes
169
+ from torch.multiprocessing.spawn import ProcessRaisedException
170
+
171
+ if len(AcceleratorState._shared_state) > 0:
172
+ raise ValueError(
173
+ "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
174
+ "inside your training function. Restart your notebook and make sure no cells initializes an "
175
+ "`Accelerator`."
176
+ )
177
+ # Check for specific libraries known to initialize CUDA that users constantly use
178
+ problematic_imports = are_libraries_initialized("bitsandbytes")
179
+ if len(problematic_imports) > 0:
180
+ err = (
181
+ "Could not start distributed process. Libraries known to initialize CUDA upon import have been "
182
+ "imported already. Please keep these imports inside your training function to try and help with this:"
183
+ )
184
+ for lib_name in problematic_imports:
185
+ err += f"\n\t* `{lib_name}`"
186
+ raise RuntimeError(err)
187
+
188
+ patched_env = dict(
189
+ nproc=num_processes,
190
+ node_rank=node_rank,
191
+ world_size=num_nodes * num_processes,
192
+ master_addr=master_addr,
193
+ master_port=use_port,
194
+ mixed_precision=mixed_precision,
195
+ )
196
+
197
+ # Check for CUDA P2P and IB issues
198
+ if not check_cuda_p2p_ib_support():
199
+ patched_env["nccl_p2p_disable"] = "1"
200
+ patched_env["nccl_ib_disable"] = "1"
201
+
202
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
203
+ # process here (the other ones will be set be the launcher).
204
+ with patch_environment(**patched_env):
205
+ # First dummy launch
206
+ if os.environ.get("ACCELERATE_DEBUG_MODE", "false").lower() == "true":
207
+ launcher = PrepareForLaunch(test_launch, distributed_type="MULTI_GPU")
208
+ try:
209
+ start_processes(launcher, args=(), nprocs=num_processes, start_method="fork")
210
+ except ProcessRaisedException as e:
211
+ err = "An issue was found when verifying a stable environment for the notebook launcher."
212
+ if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
213
+ raise RuntimeError(
214
+ f"{err}"
215
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
216
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
217
+ "which one is problematic and causing CUDA to be initialized."
218
+ ) from e
219
+ else:
220
+ raise RuntimeError(f"{err} The following error was raised: {e}") from e
221
+ # Now the actual launch
222
+ launcher = PrepareForLaunch(function, distributed_type="MULTI_GPU")
223
+ print(f"Launching training on {num_processes} GPUs.")
224
+ try:
225
+ if rdzv_conf is None:
226
+ rdzv_conf = {}
227
+ if rdzv_backend == "static":
228
+ rdzv_conf["rank"] = node_rank
229
+ if not rdzv_endpoint:
230
+ rdzv_endpoint = f"{master_addr}:{use_port}"
231
+ launch_config_kwargs = dict(
232
+ min_nodes=num_nodes,
233
+ max_nodes=num_nodes,
234
+ nproc_per_node=num_processes,
235
+ run_id=rdzv_id,
236
+ rdzv_endpoint=rdzv_endpoint,
237
+ rdzv_backend=rdzv_backend,
238
+ rdzv_configs=rdzv_conf,
239
+ max_restarts=max_restarts,
240
+ monitor_interval=monitor_interval,
241
+ start_method="fork",
242
+ )
243
+ if is_torch_version(">=", ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION):
244
+ launch_config_kwargs["log_line_prefix_template"] = log_line_prefix_template
245
+ elastic_launch(config=LaunchConfig(**launch_config_kwargs), entrypoint=function)(*args)
246
+ except ProcessRaisedException as e:
247
+ if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
248
+ raise RuntimeError(
249
+ "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
250
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
251
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
252
+ "which one is problematic and causing CUDA to be initialized."
253
+ ) from e
254
+ else:
255
+ raise RuntimeError(f"An issue was found when launching the training: {e}") from e
256
+
257
+ else:
258
+ # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
259
+ if is_mps_available():
260
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
261
+ print("Launching training on MPS.")
262
+ elif torch.cuda.is_available():
263
+ print("Launching training on one GPU.")
264
+ else:
265
+ print("Launching training on CPU.")
266
+ function(*args)
267
+
268
+
269
+ def debug_launcher(function, args=(), num_processes=2):
270
+ """
271
+ Launches a training function using several processes on CPU for debugging purposes.
272
+
273
+ <Tip warning={true}>
274
+
275
+ This function is provided for internal testing and debugging, but it's not intended for real trainings. It will
276
+ only use the CPU.
277
+
278
+ </Tip>
279
+
280
+ Args:
281
+ function (`Callable`):
282
+ The training function to execute.
283
+ args (`Tuple`):
284
+ Tuple of arguments to pass to the function (it will receive `*args`).
285
+ num_processes (`int`, *optional*, defaults to 2):
286
+ The number of processes to use for training.
287
+ """
288
+ from torch.multiprocessing import start_processes
289
+
290
+ with tempfile.NamedTemporaryFile() as tmp_file:
291
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
292
+ # process here (the other ones will be set be the launcher).
293
+ with patch_environment(
294
+ world_size=num_processes,
295
+ master_addr="127.0.0.1",
296
+ master_port="29500",
297
+ accelerate_mixed_precision="no",
298
+ accelerate_debug_rdv_file=tmp_file.name,
299
+ accelerate_use_cpu="yes",
300
+ ):
301
+ launcher = PrepareForLaunch(function, debug=True)
302
+ start_processes(launcher, args=args, nprocs=num_processes, start_method="fork")
python_embeded/Lib/site-packages/accelerate/local_sgd.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+
16
+ from accelerate import Accelerator, DistributedType
17
+
18
+
19
+ class LocalSGD:
20
+ """
21
+ A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently
22
+ on each device, and averages model weights every K synchronization step.
23
+
24
+ It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular,
25
+ this is a simple implementation that cannot support scenarios such as model parallelism.
26
+
27
+
28
+ Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes
29
+ back to at least:
30
+
31
+ Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint
32
+ arXiv:1606.07365.](https://arxiv.org/abs/1606.07365)
33
+
34
+ We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of).
35
+
36
+ Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on
37
+ Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767)
38
+
39
+ """
40
+
41
+ def __enter__(self):
42
+ if self.enabled:
43
+ self.model_sync_obj = self.model.no_sync()
44
+ self.model_sync_obj.__enter__()
45
+
46
+ return self
47
+
48
+ def __exit__(self, type, value, tb):
49
+ if self.enabled:
50
+ # Average all models on exit
51
+ self._sync_and_avg_model_params()
52
+ self.model_sync_obj.__exit__(type, value, tb)
53
+
54
+ def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True):
55
+ """
56
+ Constructor.
57
+
58
+ Args:
59
+ model (`torch.nn.Module):
60
+ The model whose parameters we need to average.
61
+ accelerator (`Accelerator`):
62
+ Accelerator object.
63
+ local_sgd_steps (`int`):
64
+ A number of local SGD steps (before model parameters are synchronized).
65
+ enabled (`bool):
66
+ Local SGD is disabled if this parameter set to `False`.
67
+ """
68
+ if accelerator.distributed_type not in [
69
+ DistributedType.NO,
70
+ DistributedType.MULTI_CPU,
71
+ DistributedType.MULTI_GPU,
72
+ DistributedType.MULTI_XPU,
73
+ DistributedType.MULTI_MLU,
74
+ DistributedType.MULTI_HPU,
75
+ DistributedType.MULTI_SDAA,
76
+ DistributedType.MULTI_MUSA,
77
+ DistributedType.MULTI_NPU,
78
+ ]:
79
+ raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)")
80
+ self.enabled = enabled and accelerator.distributed_type != DistributedType.NO
81
+ self.num_steps = 0
82
+ if self.enabled:
83
+ self.accelerator = accelerator
84
+ self.model = model
85
+ self.local_sgd_steps = local_sgd_steps
86
+
87
+ def step(self):
88
+ """
89
+ This function makes a "step" and synchronizes model parameters if necessary.
90
+ """
91
+ self.num_steps += 1
92
+ if not self.enabled:
93
+ return
94
+
95
+ if self.num_steps % self.local_sgd_steps == 0:
96
+ self._sync_and_avg_model_params()
97
+
98
+ def _sync_and_avg_model_params(self):
99
+ """
100
+ Synchronize + Average model parameters across all GPUs
101
+ """
102
+
103
+ self.accelerator.wait_for_everyone()
104
+ with self.accelerator.autocast():
105
+ for param in self.model.parameters():
106
+ param.data = self.accelerator.reduce(param.data, reduction="mean")
python_embeded/Lib/site-packages/accelerate/logging.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import functools
16
+ import logging
17
+ import os
18
+
19
+ from .state import PartialState
20
+
21
+
22
+ class MultiProcessAdapter(logging.LoggerAdapter):
23
+ """
24
+ An adapter to assist with logging in multiprocess.
25
+
26
+ `log` takes in an additional `main_process_only` kwarg, which dictates whether it should be called on all processes
27
+ or only the main executed one. Default is `main_process_only=True`.
28
+
29
+ Does not require an `Accelerator` object to be created first.
30
+ """
31
+
32
+ @staticmethod
33
+ def _should_log(main_process_only):
34
+ "Check if log should be performed"
35
+ state = PartialState()
36
+ return not main_process_only or (main_process_only and state.is_main_process)
37
+
38
+ def log(self, level, msg, *args, **kwargs):
39
+ """
40
+ Delegates logger call after checking if we should log.
41
+
42
+ Accepts a new kwarg of `main_process_only`, which will dictate whether it will be logged across all processes
43
+ or only the main executed one. Default is `True` if not passed
44
+
45
+ Also accepts "in_order", which if `True` makes the processes log one by one, in order. This is much easier to
46
+ read, but comes at the cost of sometimes needing to wait for the other processes. Default is `False` to not
47
+ break with the previous behavior.
48
+
49
+ `in_order` is ignored if `main_process_only` is passed.
50
+ """
51
+ if PartialState._shared_state == {}:
52
+ raise RuntimeError(
53
+ "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility."
54
+ )
55
+ main_process_only = kwargs.pop("main_process_only", True)
56
+ in_order = kwargs.pop("in_order", False)
57
+ # set `stacklevel` to exclude ourself in `Logger.findCaller()` while respecting user's choice
58
+ kwargs.setdefault("stacklevel", 2)
59
+
60
+ if self.isEnabledFor(level):
61
+ if self._should_log(main_process_only):
62
+ msg, kwargs = self.process(msg, kwargs)
63
+ self.logger.log(level, msg, *args, **kwargs)
64
+
65
+ elif in_order:
66
+ state = PartialState()
67
+ for i in range(state.num_processes):
68
+ if i == state.process_index:
69
+ msg, kwargs = self.process(msg, kwargs)
70
+ self.logger.log(level, msg, *args, **kwargs)
71
+ state.wait_for_everyone()
72
+
73
+ @functools.lru_cache(None)
74
+ def warning_once(self, *args, **kwargs):
75
+ """
76
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
77
+
78
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the
79
+ cache. The assumption here is that all warning messages are unique across the code. If they aren't then need to
80
+ switch to another type of cache that includes the caller frame information in the hashing function.
81
+ """
82
+ self.warning(*args, **kwargs)
83
+
84
+
85
+ def get_logger(name: str, log_level: str = None):
86
+ """
87
+ Returns a `logging.Logger` for `name` that can handle multiprocessing.
88
+
89
+ If a log should be called on all processes, pass `main_process_only=False` If a log should be called on all
90
+ processes and in order, also pass `in_order=True`
91
+
92
+ Args:
93
+ name (`str`):
94
+ The name for the logger, such as `__file__`
95
+ log_level (`str`, *optional*):
96
+ The log level to use. If not passed, will default to the `LOG_LEVEL` environment variable, or `INFO` if not
97
+
98
+ Example:
99
+
100
+ ```python
101
+ >>> from accelerate.logging import get_logger
102
+ >>> from accelerate import Accelerator
103
+
104
+ >>> logger = get_logger(__name__)
105
+
106
+ >>> accelerator = Accelerator()
107
+ >>> logger.info("My log", main_process_only=False)
108
+ >>> logger.debug("My log", main_process_only=True)
109
+
110
+ >>> logger = get_logger(__name__, log_level="DEBUG")
111
+ >>> logger.info("My log")
112
+ >>> logger.debug("My second log")
113
+
114
+ >>> array = ["a", "b", "c", "d"]
115
+ >>> letter_at_rank = array[accelerator.process_index]
116
+ >>> logger.info(letter_at_rank, in_order=True)
117
+ ```
118
+ """
119
+ if log_level is None:
120
+ log_level = os.environ.get("ACCELERATE_LOG_LEVEL", None)
121
+ logger = logging.getLogger(name)
122
+ if log_level is not None:
123
+ logger.setLevel(log_level.upper())
124
+ logger.root.setLevel(log_level.upper())
125
+ return MultiProcessAdapter(logger, {})
python_embeded/Lib/site-packages/accelerate/memory_utils.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+
17
+
18
+ warnings.warn(
19
+ "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: "
20
+ "`from accelerate import find_executable_batch_size` to avoid this warning.",
21
+ FutureWarning,
22
+ )
python_embeded/Lib/site-packages/accelerate/optimizer.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+
17
+ import torch
18
+
19
+ from .state import AcceleratorState, GradientState
20
+ from .utils import DistributedType, honor_type, is_lomo_available, is_torch_xla_available
21
+
22
+
23
+ if is_torch_xla_available():
24
+ import torch_xla.core.xla_model as xm
25
+ import torch_xla.runtime as xr
26
+
27
+
28
+ def move_to_device(state, device):
29
+ if isinstance(state, (list, tuple)):
30
+ return honor_type(state, (move_to_device(t, device) for t in state))
31
+ elif isinstance(state, dict):
32
+ return type(state)({k: move_to_device(v, device) for k, v in state.items()})
33
+ elif isinstance(state, torch.Tensor):
34
+ return state.to(device)
35
+ return state
36
+
37
+
38
+ class AcceleratedOptimizer(torch.optim.Optimizer):
39
+ """
40
+ Internal wrapper around a torch optimizer.
41
+
42
+ Conditionally will perform `step` and `zero_grad` if gradients should be synchronized when performing gradient
43
+ accumulation.
44
+
45
+ Args:
46
+ optimizer (`torch.optim.optimizer.Optimizer`):
47
+ The optimizer to wrap.
48
+ device_placement (`bool`, *optional*, defaults to `True`):
49
+ Whether or not the optimizer should handle device placement. If so, it will place the state dictionary of
50
+ `optimizer` on the right device.
51
+ scaler (`torch.amp.GradScaler` or `torch.cuda.amp.GradScaler`, *optional*):
52
+ The scaler to use in the step function if training with mixed precision.
53
+ """
54
+
55
+ def __init__(self, optimizer, device_placement=True, scaler=None):
56
+ self.optimizer = optimizer
57
+ self.scaler = scaler
58
+ self.accelerator_state = AcceleratorState()
59
+ self.gradient_state = GradientState()
60
+ self.device_placement = device_placement
61
+ self._is_overflow = False
62
+
63
+ if self.scaler is not None:
64
+ self._accelerate_step_called = False
65
+ self._optimizer_original_step_method = self.optimizer.step
66
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
67
+
68
+ # Handle device placement
69
+ if device_placement:
70
+ state_dict = self.optimizer.state_dict()
71
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
72
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
73
+ else:
74
+ state_dict = move_to_device(state_dict, self.accelerator_state.device)
75
+ self.optimizer.load_state_dict(state_dict)
76
+
77
+ @property
78
+ def state(self):
79
+ return self.optimizer.state
80
+
81
+ @state.setter
82
+ def state(self, state):
83
+ self.optimizer.state = state
84
+
85
+ @property
86
+ def param_groups(self):
87
+ return self.optimizer.param_groups
88
+
89
+ @param_groups.setter
90
+ def param_groups(self, param_groups):
91
+ self.optimizer.param_groups = param_groups
92
+
93
+ @property
94
+ def defaults(self):
95
+ return self.optimizer.defaults
96
+
97
+ @defaults.setter
98
+ def defaults(self, defaults):
99
+ self.optimizer.defaults = defaults
100
+
101
+ def add_param_group(self, param_group):
102
+ self.optimizer.add_param_group(param_group)
103
+
104
+ def load_state_dict(self, state_dict):
105
+ if self.accelerator_state.distributed_type == DistributedType.XLA and self.device_placement:
106
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
107
+ self.optimizer.load_state_dict(state_dict)
108
+
109
+ def state_dict(self):
110
+ return self.optimizer.state_dict()
111
+
112
+ def zero_grad(self, set_to_none=None):
113
+ if self.gradient_state.sync_gradients:
114
+ accept_arg = "set_to_none" in inspect.signature(self.optimizer.zero_grad).parameters
115
+ if accept_arg:
116
+ if set_to_none is None:
117
+ set_to_none = True
118
+ self.optimizer.zero_grad(set_to_none=set_to_none)
119
+ else:
120
+ if set_to_none is not None:
121
+ raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.")
122
+ self.optimizer.zero_grad()
123
+
124
+ def train(self):
125
+ """
126
+ Sets the optimizer to "train" mode. Useful for optimizers like `schedule_free`
127
+ """
128
+ if hasattr(self.optimizer, "train") and callable(self.optimizer.train):
129
+ self.optimizer.train()
130
+ elif (
131
+ hasattr(self.optimizer, "optimizer")
132
+ and hasattr(self.optimizer.optimizer, "train")
133
+ and callable(self.optimizer.optimizer.train)
134
+ ):
135
+ # the deepspeed optimizer further wraps the optimizer
136
+ self.optimizer.optimizer.train()
137
+
138
+ def eval(self):
139
+ """
140
+ Sets the optimizer to "eval" mode. Useful for optimizers like `schedule_free`
141
+ """
142
+ if hasattr(self.optimizer, "eval") and callable(self.optimizer.eval):
143
+ self.optimizer.eval()
144
+
145
+ def step(self, closure=None):
146
+ if is_lomo_available():
147
+ from lomo_optim import AdaLomo, Lomo
148
+
149
+ if (
150
+ not self.gradient_state.is_xla_gradients_synced
151
+ and self.accelerator_state.distributed_type == DistributedType.XLA
152
+ ):
153
+ gradients = xm._fetch_gradients(self.optimizer)
154
+ xm.all_reduce("sum", gradients, scale=1.0 / xr.world_size())
155
+ self.gradient_state.is_xla_gradients_synced = True
156
+
157
+ if is_lomo_available():
158
+ # `step` should be a no-op for LOMO optimizers.
159
+ if isinstance(self.optimizer, (Lomo, AdaLomo)):
160
+ return
161
+
162
+ if self.gradient_state.sync_gradients:
163
+ if self.scaler is not None:
164
+ self.optimizer.step = self._optimizer_patched_step_method
165
+
166
+ self.scaler.step(self.optimizer, closure)
167
+ self.scaler.update()
168
+
169
+ if not self._accelerate_step_called:
170
+ # If the optimizer step was skipped, gradient overflow was detected.
171
+ self._is_overflow = True
172
+ else:
173
+ self._is_overflow = False
174
+ # Reset the step method to the original one
175
+ self.optimizer.step = self._optimizer_original_step_method
176
+ # Reset the indicator
177
+ self._accelerate_step_called = False
178
+ else:
179
+ self.optimizer.step(closure)
180
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
181
+ self.gradient_state.is_xla_gradients_synced = False
182
+
183
+ def _switch_parameters(self, parameters_map):
184
+ for param_group in self.optimizer.param_groups:
185
+ param_group["params"] = [parameters_map.get(p, p) for p in param_group["params"]]
186
+
187
+ @property
188
+ def step_was_skipped(self):
189
+ """Whether or not the optimizer step was skipped."""
190
+ return self._is_overflow
191
+
192
+ def __getstate__(self):
193
+ _ignored_keys = [
194
+ "_accelerate_step_called",
195
+ "_optimizer_original_step_method",
196
+ "_optimizer_patched_step_method",
197
+ ]
198
+ return {k: v for k, v in self.__dict__.items() if k not in _ignored_keys}
199
+
200
+ def __setstate__(self, state):
201
+ self.__dict__.update(state)
202
+ if self.scaler is not None:
203
+ self._accelerate_step_called = False
204
+ self._optimizer_original_step_method = self.optimizer.step
205
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
206
+
207
+
208
+ def patch_optimizer_step(accelerated_optimizer: AcceleratedOptimizer, method):
209
+ def patched_step(*args, **kwargs):
210
+ accelerated_optimizer._accelerate_step_called = True
211
+ return method(*args, **kwargs)
212
+
213
+ return patched_step
python_embeded/Lib/site-packages/accelerate/scheduler.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation
16
+
17
+ import warnings
18
+
19
+ from .state import AcceleratorState, GradientState
20
+
21
+
22
+ warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler")
23
+
24
+
25
+ class AcceleratedScheduler:
26
+ """
27
+ A wrapper around a learning rate scheduler that will only step when the optimizer(s) have a training step. Useful
28
+ to avoid making a scheduler step too fast when gradients went overflow and there was no training step (in mixed
29
+ precision training)
30
+
31
+ When performing gradient accumulation scheduler lengths should not be changed accordingly, Accelerate will always
32
+ step the scheduler to account for it.
33
+
34
+ Args:
35
+ scheduler (`torch.optim.lr_scheduler._LRScheduler`):
36
+ The scheduler to wrap.
37
+ optimizers (one or a list of `torch.optim.Optimizer`):
38
+ The optimizers used.
39
+ step_with_optimizer (`bool`, *optional*, defaults to `True`):
40
+ Whether or not the scheduler should be stepped at each optimizer step.
41
+ split_batches (`bool`, *optional*, defaults to `False`):
42
+ Whether or not the dataloaders split one batch across the different processes (so batch size is the same
43
+ regardless of the number of processes) or create batches on each process (so batch size is the original
44
+ batch size multiplied by the number of processes).
45
+ """
46
+
47
+ def __init__(self, scheduler, optimizers, step_with_optimizer: bool = True, split_batches: bool = False):
48
+ self.scheduler = scheduler
49
+ self.optimizers = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers]
50
+ self.split_batches = split_batches
51
+ self.step_with_optimizer = step_with_optimizer
52
+ self.gradient_state = GradientState()
53
+
54
+ def step(self, *args, **kwargs):
55
+ if not self.step_with_optimizer:
56
+ # No link between scheduler and optimizer -> just step
57
+ self.scheduler.step(*args, **kwargs)
58
+ return
59
+
60
+ # Otherwise, first make sure the optimizer was stepped.
61
+ if not self.gradient_state.sync_gradients:
62
+ if self.gradient_state.adjust_scheduler:
63
+ self.scheduler._step_count += 1
64
+ return
65
+
66
+ for opt in self.optimizers:
67
+ if opt.step_was_skipped:
68
+ return
69
+ if self.split_batches:
70
+ # Split batches -> the training dataloader batch size is not changed so one step per training step
71
+ self.scheduler.step(*args, **kwargs)
72
+ else:
73
+ # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
74
+ # num_processes steps per training step
75
+ num_processes = AcceleratorState().num_processes
76
+ for _ in range(num_processes):
77
+ # Special case when using OneCycle and `drop_last` was not used
78
+ if hasattr(self.scheduler, "total_steps"):
79
+ if self.scheduler._step_count <= self.scheduler.total_steps:
80
+ self.scheduler.step(*args, **kwargs)
81
+ else:
82
+ self.scheduler.step(*args, **kwargs)
83
+
84
+ # Passthroughs
85
+ def get_last_lr(self):
86
+ return self.scheduler.get_last_lr()
87
+
88
+ def state_dict(self):
89
+ return self.scheduler.state_dict()
90
+
91
+ def load_state_dict(self, state_dict):
92
+ self.scheduler.load_state_dict(state_dict)
93
+
94
+ def get_lr(self):
95
+ return self.scheduler.get_lr()
96
+
97
+ def print_lr(self, *args, **kwargs):
98
+ return self.scheduler.print_lr(*args, **kwargs)
python_embeded/Lib/site-packages/accelerate/state.py ADDED
@@ -0,0 +1,1344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ import threading
20
+ import warnings
21
+ import weakref
22
+ from contextlib import contextmanager
23
+ from functools import partial
24
+ from typing import Any, Callable
25
+
26
+ import torch
27
+
28
+ from .utils import (
29
+ DistributedType,
30
+ DynamoBackend,
31
+ GradientAccumulationPlugin,
32
+ check_cuda_fp8_capability,
33
+ check_cuda_p2p_ib_support,
34
+ deepspeed_required,
35
+ get_cpu_distributed_information,
36
+ get_int_from_env,
37
+ is_ccl_available,
38
+ is_datasets_available,
39
+ is_deepspeed_available,
40
+ is_fp8_available,
41
+ is_habana_gaudi1,
42
+ is_hpu_available,
43
+ is_ipex_available,
44
+ is_mlu_available,
45
+ is_mps_available,
46
+ is_musa_available,
47
+ is_npu_available,
48
+ is_sdaa_available,
49
+ is_torch_xla_available,
50
+ is_xccl_available,
51
+ is_xpu_available,
52
+ parse_choice_from_env,
53
+ parse_flag_from_env,
54
+ set_numa_affinity,
55
+ )
56
+ from .utils.dataclasses import SageMakerDistributedType
57
+
58
+
59
+ if is_torch_xla_available():
60
+ import torch_xla.core.xla_model as xm
61
+ import torch_xla.runtime as xr
62
+
63
+ if is_mlu_available(check_device=False):
64
+ import torch_mlu # noqa: F401
65
+
66
+ if is_sdaa_available(check_device=False):
67
+ import torch_sdaa # noqa: F401
68
+
69
+ if is_musa_available(check_device=False):
70
+ import torch_musa # noqa: F401
71
+
72
+ if is_npu_available(check_device=False):
73
+ import torch_npu # noqa: F401
74
+
75
+
76
+ logger = logging.getLogger(__name__)
77
+
78
+
79
+ def is_initialized() -> bool:
80
+ """
81
+ Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`,
82
+ but works as a module method.
83
+ """
84
+ return AcceleratorState._shared_state != {}
85
+
86
+
87
+ # Lambda function that does nothing
88
+ def do_nothing(*args, **kwargs):
89
+ return None
90
+
91
+
92
+ class ThreadLocalSharedDict(threading.local):
93
+ """
94
+ Descriptor that holds a dict shared between instances of a class in the same thread.
95
+
96
+ Note: Descriptors have slightly different semantics than just a dict field on its own.
97
+ `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the
98
+ underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside
99
+ the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor
100
+ object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`).
101
+
102
+ See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html
103
+
104
+ This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3).
105
+
106
+ See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3
107
+ """
108
+
109
+ def __init__(self, thread_local: bool = False):
110
+ self._storage = {}
111
+
112
+ def __get__(self, obj, objtype=None):
113
+ return self._storage
114
+
115
+ def __set__(self, obj, value):
116
+ self._storage = value
117
+
118
+
119
+ # Prefer global shared dictionary, except when using TPU.
120
+ SharedDict = dict if not is_torch_xla_available() else ThreadLocalSharedDict
121
+
122
+
123
+ # Inspired by Alex Martelli's 'Borg'.
124
+ class PartialState:
125
+ """
126
+ Singleton class that has information about the current training environment and functions to help with process
127
+ control. Designed to be used when only process control and device execution states are needed. Does *not* need to
128
+ be initialized from `Accelerator`.
129
+
130
+ Args:
131
+ cpu (`bool`, *optional*):
132
+ Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to
133
+ `True` and force the execution on the CPU.
134
+ kwargs (additional keyword arguments, *optional*):
135
+ Additional keyword arguments to pass to the relevant `init_process_group` function. Valid `kwargs` can be
136
+ found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage.
137
+
138
+ **Available attributes:**
139
+
140
+ - **device** (`torch.device`) -- The device to use.
141
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
142
+ in use.
143
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
144
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
145
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
146
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
147
+ - **process_index** (`int`) -- The index of the current process.
148
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
149
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
150
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
151
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
152
+
153
+ Example:
154
+ ```python
155
+ from accelerate.utils import InitProcessGroupKwargs
156
+
157
+ # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
158
+ kwargs = InitProcessGroupKwargs(...).to_kwargs()
159
+ state = PartialState(**kwargs)
160
+ ```
161
+ """
162
+
163
+ _shared_state = SharedDict()
164
+ _known_attrs = [
165
+ "_cpu",
166
+ "_mixed_precision",
167
+ "_shared_state",
168
+ "backend",
169
+ "debug",
170
+ "device",
171
+ "distributed_type",
172
+ "fork_launched",
173
+ "local_process_index",
174
+ "num_processes",
175
+ "process_index",
176
+ ]
177
+
178
+ def __init__(self, cpu: bool = False, **kwargs):
179
+ self.__dict__ = self._shared_state
180
+ if not self.initialized:
181
+ self._cpu = cpu
182
+ self.backend = None
183
+ env_device = os.environ.get("ACCELERATE_TORCH_DEVICE", None)
184
+ self.device = torch.device(env_device) if env_device is not None else None
185
+ self.debug = parse_flag_from_env("ACCELERATE_DEBUG_MODE")
186
+ use_sagemaker_dp = kwargs.pop("_use_sagemaker_dp", None)
187
+ dist_information = None
188
+ if use_sagemaker_dp is None:
189
+ use_sagemaker_dp = (
190
+ os.environ.get("ACCELERATE_USE_SAGEMAKER", "false") == "true"
191
+ and os.environ.get("ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE") != SageMakerDistributedType.NO
192
+ )
193
+
194
+ # Sets up self.backend + imports
195
+ original_backend = kwargs.pop("backend", None)
196
+ backend, distributed_type = self._prepare_backend(cpu, use_sagemaker_dp, original_backend)
197
+ if original_backend is not None and backend != original_backend:
198
+ raise ValueError(f"Your assigned backend {original_backend} is not avaliable, please use {backend}")
199
+ self.backend = backend
200
+ self.distributed_type = distributed_type
201
+ use_deepspeed = False
202
+ if not cpu and self.backend != "xla":
203
+ if int(os.environ.get("LOCAL_RANK", -1)) != -1:
204
+ # Deal with spawning deepspeed
205
+ if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true":
206
+ if not is_deepspeed_available():
207
+ raise ImportError(
208
+ "DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source"
209
+ )
210
+ from deepspeed import comm as dist
211
+
212
+ if not dist.is_initialized():
213
+ if self.backend == "tccl":
214
+ local_rank = os.environ.get("LOCAL_RANK", -1)
215
+ torch.sdaa.set_device(f"sdaa:{local_rank}")
216
+ if (
217
+ self.backend == "nccl"
218
+ and os.environ.get("ACCELERATE_USE_FSDP", "false") == "true"
219
+ and os.environ.get("FSDP_OFFLOAD_PARAMS", "false") == "true"
220
+ ):
221
+ self.backend = "cuda:nccl,cpu:gloo"
222
+ dist.init_distributed(dist_backend=self.backend, auto_mpi_discovery=False, **kwargs)
223
+ # We need to flag to `use_deepspeed` to be True to override `distributed_type` later
224
+ use_deepspeed = True
225
+ # Deal with all other backends but XPU and CPU, that gets handled special later
226
+ elif (
227
+ self.distributed_type not in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU)
228
+ and not torch.distributed.is_initialized()
229
+ ):
230
+ if self.backend == "tccl":
231
+ local_rank = os.environ.get("LOCAL_RANK", -1)
232
+ torch.sdaa.set_device(f"sdaa:{local_rank}")
233
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
234
+
235
+ # XPU and CPU require special env configs to be set
236
+ if self.distributed_type in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU):
237
+ dist_information = get_cpu_distributed_information()
238
+ os.environ["RANK"] = str(dist_information.rank)
239
+ os.environ["WORLD_SIZE"] = str(dist_information.world_size)
240
+ os.environ["LOCAL_RANK"] = str(dist_information.local_rank)
241
+ os.environ["LOCAL_WORLD_SIZE"] = str(dist_information.local_world_size)
242
+ if not os.environ.get("MASTER_PORT", None):
243
+ os.environ["MASTER_PORT"] = "29500"
244
+ if (
245
+ not os.environ.get("MASTER_ADDR", None)
246
+ and dist_information.local_world_size != dist_information.world_size
247
+ and self.backend != "mpi"
248
+ ):
249
+ raise ValueError(
250
+ "Tried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, "
251
+ "please try exporting rank 0's hostname as `MASTER_ADDR`"
252
+ )
253
+ kwargs["rank"] = dist_information.rank
254
+ kwargs["world_size"] = dist_information.world_size
255
+
256
+ if (
257
+ self.distributed_type == DistributedType.MULTI_CPU
258
+ and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0
259
+ ):
260
+ import psutil
261
+
262
+ num_cpu_threads_per_process = int(
263
+ psutil.cpu_count(logical=False) / dist_information.local_world_size
264
+ )
265
+ if num_cpu_threads_per_process == 0:
266
+ num_cpu_threads_per_process = 1
267
+ torch.set_num_threads(num_cpu_threads_per_process)
268
+ warnings.warn(
269
+ f"OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at {num_cpu_threads_per_process} to improve oob"
270
+ " performance."
271
+ )
272
+
273
+ if not torch.distributed.is_initialized():
274
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
275
+
276
+ # No backend == no distributed training
277
+ if self.backend is None:
278
+ self.distributed_type = DistributedType.NO
279
+ self.num_processes = 1
280
+ self.process_index = 0
281
+ self.local_process_index = 0
282
+ elif self.backend == "xla":
283
+ # XLA needs device setting first for `set_replication`
284
+ self.set_device()
285
+ xm.set_replication(self.device, xm.get_xla_supported_devices())
286
+ self.num_processes = xr.world_size()
287
+ self.process_index = xr.global_ordinal()
288
+ if is_torch_xla_available(check_is_tpu=True):
289
+ self.local_process_index = xm.get_local_ordinal()
290
+ else:
291
+ self.local_process_index = int(os.environ.get("LOCAL_RANK", -1))
292
+ else:
293
+ self.num_processes = torch.distributed.get_world_size()
294
+ self.process_index = torch.distributed.get_rank()
295
+ self.local_process_index = (
296
+ int(os.environ.get("LOCAL_RANK", -1)) if dist_information is None else dist_information.local_rank
297
+ )
298
+ self.set_device()
299
+ # Now we can change to deepseed
300
+ if use_deepspeed:
301
+ self.distributed_type = DistributedType.DEEPSPEED
302
+
303
+ # Set CPU affinity if enabled
304
+ if parse_flag_from_env("ACCELERATE_CPU_AFFINITY", False):
305
+ set_numa_affinity(self.local_process_index)
306
+
307
+ # Check for old RTX 4000's that can't use P2P or IB and are on old drivers
308
+ if self.device.type == "cuda" and not check_cuda_p2p_ib_support():
309
+ if "NCCL_P2P_DISABLE" not in os.environ or "NCCL_IB_DISABLE" not in os.environ:
310
+ raise NotImplementedError(
311
+ "Using RTX 4000 series doesn't support faster communication broadband via P2P or IB. "
312
+ 'Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which '
313
+ "will do this automatically."
314
+ )
315
+
316
+ # Important: This should be the *only* code outside of `self.initialized!`
317
+ self.fork_launched = parse_flag_from_env("FORK_LAUNCHED", 0)
318
+
319
+ def __repr__(self) -> str:
320
+ return (
321
+ f"Distributed environment: {self.distributed_type}{(' Backend: ' + self.backend) if self.backend else ''}\n"
322
+ f"Num processes: {self.num_processes}\n"
323
+ f"Process index: {self.process_index}\n"
324
+ f"Local process index: {self.local_process_index}\n"
325
+ f"Device: {self.device}\n"
326
+ )
327
+
328
+ @staticmethod
329
+ def _reset_state():
330
+ "Resets `_shared_state`, is used internally and should not be called"
331
+ PartialState._shared_state.clear()
332
+
333
+ @property
334
+ def initialized(self) -> bool:
335
+ "Returns whether the `PartialState` has been initialized"
336
+ return self._shared_state != {}
337
+
338
+ @property
339
+ def use_distributed(self):
340
+ """
341
+ Whether the Accelerator is configured for distributed training
342
+ """
343
+ return self.distributed_type != DistributedType.NO and self.num_processes > 1
344
+
345
+ @property
346
+ def is_last_process(self) -> bool:
347
+ "Returns whether the current process is the last one"
348
+ return self.process_index == self.num_processes - 1
349
+
350
+ @property
351
+ def is_main_process(self) -> bool:
352
+ "Returns whether the current process is the main process"
353
+ return (
354
+ self.process_index == 0 if self.distributed_type != DistributedType.MEGATRON_LM else self.is_last_process
355
+ )
356
+
357
+ @property
358
+ def is_local_main_process(self) -> bool:
359
+ "Returns whether the current process is the main process on the local node"
360
+ return (
361
+ self.local_process_index == 0
362
+ if self.distributed_type != DistributedType.MEGATRON_LM
363
+ else self.is_last_process
364
+ )
365
+
366
+ def wait_for_everyone(self):
367
+ """
368
+ Will stop the execution of the current process until every other process has reached that point (so this does
369
+ nothing when the script is only run in one process). Useful to do before saving a model.
370
+
371
+ Example:
372
+
373
+ ```python
374
+ >>> # Assuming two GPU processes
375
+ >>> import time
376
+ >>> from accelerate.state import PartialState
377
+
378
+ >>> state = PartialState()
379
+ >>> if state.is_main_process:
380
+ ... time.sleep(2)
381
+ >>> else:
382
+ ... print("I'm waiting for the main process to finish its sleep...")
383
+ >>> state.wait_for_everyone()
384
+ >>> # Should print on every process at the same time
385
+ >>> print("Everyone is here")
386
+ ```
387
+ """
388
+ if self.distributed_type in (
389
+ DistributedType.MULTI_GPU,
390
+ DistributedType.MULTI_MLU,
391
+ DistributedType.MULTI_SDAA,
392
+ DistributedType.MULTI_MUSA,
393
+ DistributedType.MULTI_NPU,
394
+ DistributedType.MULTI_XPU,
395
+ DistributedType.MULTI_CPU,
396
+ DistributedType.MULTI_HPU,
397
+ DistributedType.DEEPSPEED,
398
+ DistributedType.FSDP,
399
+ ):
400
+ torch.distributed.barrier()
401
+ elif self.distributed_type == DistributedType.XLA:
402
+ xm.rendezvous("accelerate.utils.wait_for_everyone")
403
+
404
+ def _goes_first(self, is_main: bool):
405
+ if not is_main:
406
+ self.wait_for_everyone()
407
+
408
+ yield
409
+
410
+ if is_main:
411
+ self.wait_for_everyone()
412
+
413
+ @contextmanager
414
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
415
+ """
416
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
417
+ distributed inference, such as with different prompts.
418
+
419
+ Note that when using a `dict`, all keys need to have the same number of elements.
420
+
421
+ Args:
422
+ inputs (`list`, `tuple`, `torch.Tensor`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`):
423
+ The input to split between processes.
424
+ apply_padding (`bool`, `optional`, defaults to `False`):
425
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
426
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
427
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
428
+
429
+
430
+ Example:
431
+
432
+ ```python
433
+ # Assume there are two processes
434
+ from accelerate import PartialState
435
+
436
+ state = PartialState()
437
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
438
+ print(inputs)
439
+ # Process 0
440
+ ["A", "B"]
441
+ # Process 1
442
+ ["C"]
443
+
444
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
445
+ print(inputs)
446
+ # Process 0
447
+ ["A", "B"]
448
+ # Process 1
449
+ ["C", "C"]
450
+ ```
451
+ """
452
+ if self.num_processes == 1:
453
+ yield inputs
454
+ return
455
+ length = len(inputs)
456
+ # Nested dictionary of any types
457
+ if isinstance(inputs, dict):
458
+ length = len(inputs[list(inputs.keys())[0]])
459
+ if not all(len(v) == length for v in inputs.values()):
460
+ raise ValueError("All values in the dictionary must have the same length")
461
+ num_samples_per_process, num_extras = divmod(length, self.num_processes)
462
+ start_index = self.process_index * num_samples_per_process + min(self.process_index, num_extras)
463
+ end_index = start_index + num_samples_per_process + (1 if self.process_index < num_extras else 0)
464
+
465
+ def _split_values(inputs, start_index, end_index):
466
+ if isinstance(inputs, (list, tuple, torch.Tensor)):
467
+ if start_index >= len(inputs):
468
+ result = inputs[-1:]
469
+ else:
470
+ result = inputs[start_index:end_index]
471
+ if apply_padding:
472
+ if isinstance(result, torch.Tensor):
473
+ from accelerate.utils import pad_across_processes, send_to_device
474
+
475
+ # The tensor needs to be on the device before we can pad it
476
+ tensorized_result = send_to_device(result, self.device)
477
+ result = pad_across_processes(tensorized_result, pad_index=inputs[-1])
478
+ else:
479
+ result += [result[-1]] * (num_samples_per_process + (1 if num_extras > 0 else 0) - len(result))
480
+ return result
481
+ elif isinstance(inputs, dict):
482
+ for key in inputs.keys():
483
+ inputs[key] = _split_values(inputs[key], start_index, end_index)
484
+ return inputs
485
+ else:
486
+ if is_datasets_available():
487
+ from datasets import Dataset
488
+
489
+ if isinstance(inputs, Dataset):
490
+ if start_index >= len(inputs):
491
+ start_index = len(inputs) - 1
492
+ if end_index > len(inputs):
493
+ end_index = len(inputs)
494
+ result_idcs = list(range(start_index, end_index))
495
+ if apply_padding:
496
+ result_idcs += [end_index - 1] * (
497
+ num_samples_per_process + (1 if num_extras > 0 else 0) - len(result_idcs)
498
+ )
499
+ return inputs.select(result_idcs)
500
+ return inputs
501
+
502
+ yield _split_values(inputs, start_index, end_index)
503
+
504
+ @contextmanager
505
+ def main_process_first(self):
506
+ """
507
+ Lets the main process go first inside a with block.
508
+
509
+ The other processes will enter the with block after the main process exits.
510
+
511
+ Example:
512
+
513
+ ```python
514
+ >>> from accelerate import Accelerator
515
+
516
+ >>> accelerator = Accelerator()
517
+ >>> with accelerator.main_process_first():
518
+ ... # This will be printed first by process 0 then in a seemingly
519
+ ... # random order by the other processes.
520
+ ... print(f"This will be printed by process {accelerator.process_index}")
521
+ ```
522
+ """
523
+ yield from self._goes_first(self.is_main_process)
524
+
525
+ @contextmanager
526
+ def local_main_process_first(self):
527
+ """
528
+ Lets the local main process go inside a with block.
529
+
530
+ The other processes will enter the with block after the main process exits.
531
+
532
+ Example:
533
+
534
+ ```python
535
+ >>> from accelerate.state import PartialState
536
+
537
+ >>> state = PartialState()
538
+ >>> with state.local_main_process_first():
539
+ ... # This will be printed first by local process 0 then in a seemingly
540
+ ... # random order by the other processes.
541
+ ... print(f"This will be printed by process {state.local_process_index}")
542
+ ```
543
+ """
544
+ yield from self._goes_first(self.is_local_main_process)
545
+
546
+ def on_main_process(self, function: Callable[..., Any] = None):
547
+ """
548
+ Decorator that only runs the decorated function on the main process.
549
+
550
+ Args:
551
+ function (`Callable`): The function to decorate.
552
+
553
+ Example:
554
+
555
+ ```python
556
+ >>> from accelerate.state import PartialState
557
+
558
+ >>> state = PartialState()
559
+
560
+
561
+ >>> @state.on_main_process
562
+ ... def print_something():
563
+ ... print("This will be printed by process 0 only.")
564
+
565
+
566
+ >>> print_something()
567
+ "This will be printed by process 0 only"
568
+ ```
569
+ """
570
+ if not self.initialized:
571
+ raise ValueError("The `PartialState` or `Accelerator` must be initialized before calling this function.")
572
+ if self.is_main_process or not self.use_distributed:
573
+ return function
574
+ return do_nothing
575
+
576
+ def on_local_main_process(self, function: Callable[..., Any] = None):
577
+ """
578
+ Decorator that only runs the decorated function on the local main process.
579
+
580
+ Args:
581
+ function (`Callable`): The function to decorate.
582
+
583
+ Example:
584
+ ```python
585
+ # Assume we have 2 servers with 4 processes each.
586
+ from accelerate.state import PartialState
587
+
588
+ state = PartialState()
589
+
590
+
591
+ @state.on_local_main_process
592
+ def print_something():
593
+ print("This will be printed by process 0 only on each server.")
594
+
595
+
596
+ print_something()
597
+ # On server 1:
598
+ "This will be printed by process 0 only"
599
+ # On server 2:
600
+ "This will be printed by process 0 only"
601
+ ```
602
+ """
603
+ if self.is_local_main_process or not self.use_distributed:
604
+ return function
605
+ return do_nothing
606
+
607
+ def on_last_process(self, function: Callable[..., Any]):
608
+ """
609
+ Decorator that only runs the decorated function on the last process.
610
+
611
+ Args:
612
+ function (`Callable`): The function to decorate.
613
+
614
+ Example:
615
+ ```python
616
+ # Assume we have 4 processes.
617
+ from accelerate.state import PartialState
618
+
619
+ state = PartialState()
620
+
621
+
622
+ @state.on_last_process
623
+ def print_something():
624
+ print(f"Printed on process {state.process_index}")
625
+
626
+
627
+ print_something()
628
+ "Printed on process 3"
629
+ ```
630
+ """
631
+ if self.is_last_process or not self.use_distributed:
632
+ return function
633
+ return do_nothing
634
+
635
+ def on_process(self, function: Callable[..., Any] = None, process_index: int = None):
636
+ """
637
+ Decorator that only runs the decorated function on the process with the given index.
638
+
639
+ Args:
640
+ function (`Callable`, `optional`):
641
+ The function to decorate.
642
+ process_index (`int`, `optional`):
643
+ The index of the process on which to run the function.
644
+
645
+ Example:
646
+ ```python
647
+ # Assume we have 4 processes.
648
+ from accelerate.state import PartialState
649
+
650
+ state = PartialState()
651
+
652
+
653
+ @state.on_process(process_index=2)
654
+ def print_something():
655
+ print(f"Printed on process {state.process_index}")
656
+
657
+
658
+ print_something()
659
+ "Printed on process 2"
660
+ ```
661
+ """
662
+ if function is None:
663
+ return partial(self.on_process, process_index=process_index)
664
+ if (self.process_index == process_index) or (not self.use_distributed):
665
+ return function
666
+ return do_nothing
667
+
668
+ def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None):
669
+ """
670
+ Decorator that only runs the decorated function on the process with the given index on the current node.
671
+
672
+ Args:
673
+ function (`Callable`, *optional*):
674
+ The function to decorate.
675
+ local_process_index (`int`, *optional*):
676
+ The index of the local process on which to run the function.
677
+
678
+ Example:
679
+ ```python
680
+ # Assume we have 2 servers with 4 processes each.
681
+ from accelerate import Accelerator
682
+
683
+ accelerator = Accelerator()
684
+
685
+
686
+ @accelerator.on_local_process(local_process_index=2)
687
+ def print_something():
688
+ print(f"Printed on process {accelerator.local_process_index}")
689
+
690
+
691
+ print_something()
692
+ # On server 1:
693
+ "Printed on process 2"
694
+ # On server 2:
695
+ "Printed on process 2"
696
+ ```
697
+ """
698
+ if function is None:
699
+ return partial(self.on_local_process, local_process_index=local_process_index)
700
+ if (self.local_process_index == local_process_index) or (not self.use_distributed):
701
+ return function
702
+ return do_nothing
703
+
704
+ def print(self, *args, **kwargs):
705
+ if self.is_local_main_process:
706
+ print(*args, **kwargs)
707
+
708
+ @property
709
+ def default_device(self) -> torch.device:
710
+ """
711
+ Returns the default device which is:
712
+ - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True.
713
+ - CUDA if `torch.cuda.is_available()`
714
+ - MLU if `is_mlu_available()`
715
+ - SDAA if `is_sdaa_available()`
716
+ - MUSA if `is_musa_available()`
717
+ - NPU if `is_npu_available()`
718
+ - HPU if `is_hpu_available()`
719
+ - CPU otherwise
720
+ """
721
+ if is_mps_available():
722
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
723
+ return torch.device("mps")
724
+ elif is_mlu_available():
725
+ return torch.device("mlu")
726
+ elif is_sdaa_available():
727
+ return torch.device("sdaa")
728
+ elif is_musa_available():
729
+ return torch.device("musa")
730
+ # NPU should be checked before CUDA when using `transfer_to_npu`
731
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
732
+ elif is_npu_available():
733
+ return torch.device("npu")
734
+ elif is_hpu_available():
735
+ return torch.device("hpu")
736
+ elif torch.cuda.is_available():
737
+ return torch.device("cuda")
738
+ elif is_xpu_available():
739
+ return torch.device("xpu")
740
+ else:
741
+ return torch.device("cpu")
742
+
743
+ def _prepare_backend(
744
+ self, cpu: bool = False, sagemaker_dp=False, backend: str = None
745
+ ) -> tuple[str, DistributedType]:
746
+ "Prepares any imports needed before initializing the distributed backend and sets `self.backend` properly"
747
+ distributed_type = None
748
+ if sagemaker_dp:
749
+ import smdistributed.dataparallel.torch.torch_smddp # noqa
750
+
751
+ backend = "smddp"
752
+ distributed_type = DistributedType.MULTI_GPU
753
+ elif is_torch_xla_available():
754
+ backend = "xla"
755
+ distributed_type = DistributedType.XLA
756
+
757
+ elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu:
758
+ if is_mlu_available():
759
+ backend = "cncl"
760
+ distributed_type = DistributedType.MULTI_MLU
761
+ if is_sdaa_available():
762
+ backend = "tccl"
763
+ distributed_type = DistributedType.MULTI_SDAA
764
+ elif is_musa_available():
765
+ backend = "mccl"
766
+ distributed_type = DistributedType.MULTI_MUSA
767
+ # NPU should be checked before CUDA when using `transfer_to_npu`
768
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
769
+ elif is_npu_available():
770
+ backend = "hccl"
771
+ distributed_type = DistributedType.MULTI_NPU
772
+ elif is_hpu_available(init_hccl=True):
773
+ if backend is None:
774
+ backend = "hccl"
775
+ distributed_type = DistributedType.MULTI_HPU
776
+ elif torch.cuda.is_available():
777
+ if backend is None:
778
+ backend = "nccl"
779
+ distributed_type = DistributedType.MULTI_GPU
780
+ elif is_xpu_available() and is_xccl_available():
781
+ if backend is None:
782
+ backend = "xccl"
783
+ distributed_type = DistributedType.MULTI_XPU
784
+
785
+ if distributed_type is None and (
786
+ int(os.environ.get("LOCAL_RANK", -1)) != -1
787
+ or get_int_from_env(["PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", "WORLD_SIZE"], 1) > 1
788
+ ):
789
+ if not cpu and is_xpu_available():
790
+ distributed_type = DistributedType.MULTI_XPU
791
+ else:
792
+ distributed_type = DistributedType.MULTI_CPU
793
+
794
+ if (
795
+ backend in (None, "ccl")
796
+ and is_ccl_available()
797
+ and (get_int_from_env(["CCL_WORKER_COUNT"], 0) > 0 or distributed_type == DistributedType.MULTI_XPU)
798
+ ):
799
+ import oneccl_bindings_for_pytorch # noqa: F401
800
+
801
+ backend = "ccl"
802
+ elif backend in (None, "mpi") and torch.distributed.is_mpi_available():
803
+ backend = "mpi"
804
+ else:
805
+ backend = "gloo"
806
+ if distributed_type is None:
807
+ distributed_type = DistributedType.NO
808
+
809
+ return backend, distributed_type
810
+
811
+ def set_device(self):
812
+ """
813
+ Sets the device in `self.device` to the current distributed environment.
814
+ """
815
+ if self.device is not None:
816
+ return
817
+ if self.distributed_type == DistributedType.NO:
818
+ self.device = torch.device("cpu") if self._cpu else self.default_device
819
+ return
820
+ device = str(self.distributed_type).split(".")[-1].replace("MULTI_", "").lower()
821
+ if device not in ("cpu", "gpu", "mlu", "musa", "npu", "xpu", "xla", "hpu", "sdaa"):
822
+ raise ValueError(
823
+ f"Can't set device for {self.distributed_type} ({device}), verify we should be calling `_set_device()` for it!"
824
+ )
825
+ if device == "xla":
826
+ self.device = xm.xla_device()
827
+ elif device == "hpu":
828
+ self.device = torch.device("hpu", torch.hpu.current_device())
829
+ else:
830
+ if device == "gpu":
831
+ device = "cuda"
832
+ device_module = getattr(torch, device)
833
+ device_index = self.local_process_index % device_module.device_count()
834
+ self.device = torch.device(device, device_index)
835
+ device_module.set_device(self.device)
836
+
837
+ def destroy_process_group(self, group=None):
838
+ """
839
+ Destroys the process group. If one is not specified, the default process group is destroyed.
840
+ """
841
+ if self.fork_launched and group is None:
842
+ return
843
+ # needed when using torch.distributed.init_process_group
844
+ if torch.distributed.is_initialized():
845
+ torch.distributed.destroy_process_group(group)
846
+
847
+ def __getattr__(self, name: str):
848
+ # By this point we know that no attributes of `self` contain `name`,
849
+ # so we just modify the error message
850
+ if name in self._known_attrs:
851
+ raise AttributeError(
852
+ f"`PartialState` object has no attribute `{name}`. "
853
+ "This happens if `PartialState._reset_state()` was called and "
854
+ "an `Accelerator` or `PartialState` was not reinitialized."
855
+ )
856
+ # Raise a typical AttributeError
857
+ raise AttributeError(f"'PartialState' object has no attribute '{name}'")
858
+
859
+
860
+ class AcceleratorState:
861
+ """
862
+ Singleton class that has information about the current training environment.
863
+
864
+ **Available attributes:**
865
+
866
+ - **device** (`torch.device`) -- The device to use.
867
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
868
+ in use.
869
+ - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`.
870
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
871
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
872
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
873
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
874
+ - **process_index** (`int`) -- The index of the current process.
875
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
876
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
877
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
878
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
879
+ """
880
+
881
+ _shared_state = SharedDict()
882
+ _known_attrs = PartialState._known_attrs + [
883
+ "deepspeed_plugin",
884
+ "use_ipex",
885
+ "fsdp_plugin",
886
+ "megatron_lm_plugin",
887
+ "dynamo_plugin",
888
+ ]
889
+
890
+ def __init__(
891
+ self,
892
+ mixed_precision: str = None,
893
+ cpu: bool = False,
894
+ dynamo_plugin=None,
895
+ deepspeed_plugin=None,
896
+ fsdp_plugin=None,
897
+ torch_tp_plugin=None,
898
+ megatron_lm_plugin=None,
899
+ _from_accelerator: bool = False,
900
+ **kwargs,
901
+ ):
902
+ self.__dict__ = self._shared_state
903
+ if parse_flag_from_env("ACCELERATE_USE_CPU"):
904
+ cpu = True
905
+ if PartialState._shared_state == {}:
906
+ PartialState(cpu, **kwargs)
907
+ self.__dict__.update(PartialState._shared_state)
908
+ self._check_initialized(mixed_precision, cpu)
909
+ if not self.initialized:
910
+ self.deepspeed_plugins = None
911
+ self.use_ipex = None
912
+ self.torch_tp_plugin = torch_tp_plugin
913
+ mixed_precision = (
914
+ parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no")
915
+ if mixed_precision is None
916
+ else mixed_precision.lower()
917
+ )
918
+ if mixed_precision == "fp8":
919
+ # this is confusing, why is is_fp8_available only checks for library availability ?
920
+ if not is_fp8_available():
921
+ raise ValueError(
922
+ "Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed."
923
+ )
924
+ elif torch.cuda.is_available() and not check_cuda_fp8_capability():
925
+ logger.warning(
926
+ f"The current device has compute capability of {torch.cuda.get_device_capability()} which is "
927
+ "insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace "
928
+ "or higher, compute capability of 8.9 or higher). Will use FP16 instead."
929
+ )
930
+ mixed_precision = "fp16"
931
+ elif is_habana_gaudi1():
932
+ logger.warning(
933
+ "The current HPU device is Gaudi1 which does not support FP8 mixed precision training (requires "
934
+ "Gaudi2 or higher). Will use BF16 instead."
935
+ )
936
+ mixed_precision = "bf16"
937
+
938
+ self.dynamo_plugin = dynamo_plugin
939
+ if not _from_accelerator:
940
+ raise ValueError(
941
+ "Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` "
942
+ "before using any functionality from the `accelerate` library."
943
+ )
944
+ # deepspeed handles mixed_precision using deepspeed_config
945
+ self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision
946
+ if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True):
947
+ if mixed_precision == "bf16":
948
+ if os.environ.get("ACCELERATE_DOWNCAST_BF16"):
949
+ os.environ["XLA_USE_BF16"] = str(0)
950
+ os.environ["XLA_DOWNCAST_BF16"] = str(1)
951
+ self.downcast_bfloat = True
952
+ else:
953
+ os.environ["XLA_USE_BF16"] = str(1)
954
+ os.environ["XLA_DOWNCAST_BF16"] = str(0)
955
+ self.downcast_bfloat = False
956
+ elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" and not cpu:
957
+ self.distributed_type = DistributedType.DEEPSPEED
958
+ if not isinstance(deepspeed_plugin, dict):
959
+ deepspeed_plugin.set_mixed_precision(mixed_precision)
960
+ deepspeed_plugin.select(_from_accelerator_state=True)
961
+ else:
962
+ for plugin in deepspeed_plugin.values():
963
+ plugin.set_mixed_precision(mixed_precision)
964
+ # The first plugin passed in is always the active one
965
+ first_plugin = next(iter(deepspeed_plugin.values()))
966
+ first_plugin.select(_from_accelerator_state=True)
967
+ self.deepspeed_plugins = deepspeed_plugin
968
+ elif self.distributed_type in [
969
+ DistributedType.MULTI_GPU,
970
+ DistributedType.MULTI_MLU,
971
+ DistributedType.MULTI_SDAA,
972
+ DistributedType.MULTI_MUSA,
973
+ DistributedType.MULTI_NPU,
974
+ DistributedType.MULTI_XPU,
975
+ DistributedType.MULTI_HPU,
976
+ ]:
977
+ if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" or fsdp_plugin is not None:
978
+ self.distributed_type = DistributedType.FSDP
979
+ if self._mixed_precision != "no":
980
+ fsdp_plugin.set_mixed_precision(self._mixed_precision)
981
+ self.fsdp_plugin = fsdp_plugin
982
+ if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true" and self.distributed_type not in [
983
+ DistributedType.MULTI_XPU,
984
+ ]:
985
+ self.distributed_type = DistributedType.MEGATRON_LM
986
+ megatron_lm_plugin.set_mixed_precision(self._mixed_precision)
987
+ self.megatron_lm_plugin = megatron_lm_plugin
988
+ if self.torch_tp_plugin is not None:
989
+ self.distributed_type = DistributedType.TP
990
+ elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]:
991
+ if is_ipex_available():
992
+ # check if user disables it explicitly
993
+ self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True)
994
+ else:
995
+ self.use_ipex = False
996
+ if (
997
+ self.dynamo_plugin.backend != DynamoBackend.NO
998
+ and self._mixed_precision == "no"
999
+ and self.device.type == "cuda"
1000
+ ):
1001
+ torch.backends.cuda.matmul.allow_tf32 = True
1002
+ if (
1003
+ self.dynamo_plugin.backend != DynamoBackend.NO
1004
+ and self._mixed_precision == "no"
1005
+ and self.device.type == "musa"
1006
+ ):
1007
+ torch.backends.musa.matmul.allow_tf32 = True
1008
+ PartialState._shared_state["distributed_type"] = self.distributed_type
1009
+
1010
+ @property
1011
+ def initialized(self) -> bool:
1012
+ return self._shared_state != PartialState._shared_state
1013
+
1014
+ def __repr__(self):
1015
+ repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n"
1016
+ if self.distributed_type == DistributedType.DEEPSPEED:
1017
+ repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n"
1018
+ return repr
1019
+
1020
+ def _check_initialized(self, mixed_precision=None, cpu=None):
1021
+ "Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized"
1022
+ if self.initialized:
1023
+ err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`."
1024
+ if cpu and self.device.type != "cpu":
1025
+ raise ValueError(err.format(flag="cpu=True"))
1026
+ if (
1027
+ mixed_precision is not None
1028
+ and mixed_precision != self._mixed_precision
1029
+ and self.distributed_type != DistributedType.DEEPSPEED
1030
+ ):
1031
+ raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'"))
1032
+
1033
+ @property
1034
+ def mixed_precision(self):
1035
+ if self.distributed_type == DistributedType.DEEPSPEED:
1036
+ config = self.deepspeed_plugin.deepspeed_config
1037
+ if config.get("fp16", {}).get("enabled", False):
1038
+ mixed_precision = "fp16"
1039
+ elif config.get("bf16", {}).get("enabled", False):
1040
+ mixed_precision = "bf16"
1041
+ else:
1042
+ mixed_precision = "no"
1043
+ else:
1044
+ mixed_precision = self._mixed_precision
1045
+ return mixed_precision
1046
+
1047
+ @staticmethod
1048
+ def _reset_state(reset_partial_state: bool = False):
1049
+ "Resets `_shared_state`, is used internally and should not be called"
1050
+ AcceleratorState._shared_state.clear()
1051
+ if reset_partial_state:
1052
+ PartialState._reset_state()
1053
+
1054
+ def destroy_process_group(self, group=None):
1055
+ """
1056
+ Destroys the process group. If one is not specified, the default process group is destroyed.
1057
+
1058
+ If `self.fork_lauched` is `True` and `group` is `None`, nothing happens.
1059
+ """
1060
+ PartialState().destroy_process_group(group)
1061
+
1062
+ @property
1063
+ def fork_launched(self):
1064
+ return PartialState().fork_launched
1065
+
1066
+ @property
1067
+ def use_distributed(self):
1068
+ """
1069
+ Whether the Accelerator is configured for distributed training
1070
+ """
1071
+ return PartialState().use_distributed
1072
+
1073
+ @property
1074
+ def is_fsdp2(self) -> bool:
1075
+ return self.distributed_type == DistributedType.FSDP and self.fsdp_plugin.fsdp_version == 2
1076
+
1077
+ @property
1078
+ def is_last_process(self) -> bool:
1079
+ "Returns whether the current process is the last one"
1080
+ return PartialState().is_last_process
1081
+
1082
+ @property
1083
+ def is_main_process(self) -> bool:
1084
+ "Returns whether the current process is the main process"
1085
+ return PartialState().is_main_process
1086
+
1087
+ @property
1088
+ def is_local_main_process(self) -> bool:
1089
+ "Returns whether the current process is the main process on the local node"
1090
+ return PartialState().is_local_main_process
1091
+
1092
+ def wait_for_everyone(self):
1093
+ PartialState().wait_for_everyone()
1094
+
1095
+ @contextmanager
1096
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
1097
+ """
1098
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
1099
+ distributed inference, such as with different prompts.
1100
+
1101
+ Note that when using a `dict`, all keys need to have the same number of elements.
1102
+
1103
+ Args:
1104
+ inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
1105
+ The input to split between processes.
1106
+ apply_padding (`bool`, `optional`, defaults to `False`):
1107
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
1108
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
1109
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
1110
+
1111
+
1112
+ Example:
1113
+
1114
+ ```python
1115
+ # Assume there are two processes
1116
+ from accelerate.state import AcceleratorState
1117
+
1118
+ state = AcceleratorState()
1119
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
1120
+ print(inputs)
1121
+ # Process 0
1122
+ ["A", "B"]
1123
+ # Process 1
1124
+ ["C"]
1125
+
1126
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
1127
+ print(inputs)
1128
+ # Process 0
1129
+ ["A", "B"]
1130
+ # Process 1
1131
+ ["C", "C"]
1132
+ ```
1133
+ """
1134
+ with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs:
1135
+ yield inputs
1136
+
1137
+ @contextmanager
1138
+ def main_process_first(self):
1139
+ """
1140
+ Lets the main process go first inside a with block.
1141
+
1142
+ The other processes will enter the with block after the main process exits.
1143
+ """
1144
+ with PartialState().main_process_first():
1145
+ yield
1146
+
1147
+ @contextmanager
1148
+ def local_main_process_first(self):
1149
+ """
1150
+ Lets the local main process go inside a with block.
1151
+
1152
+ The other processes will enter the with block after the main process exits.
1153
+ """
1154
+ with PartialState().local_main_process_first():
1155
+ yield
1156
+
1157
+ @property
1158
+ def deepspeed_plugin(self):
1159
+ """
1160
+ Returns the currently active DeepSpeedPlugin.
1161
+
1162
+ If not using deepspeed, returns `None`.
1163
+ """
1164
+ # To maintain original behavior, return None if not using deepspeed.
1165
+ if self.distributed_type != DistributedType.DEEPSPEED:
1166
+ return None
1167
+ from accelerate.utils.deepspeed import get_active_deepspeed_plugin
1168
+
1169
+ return get_active_deepspeed_plugin(self)
1170
+
1171
+ @deepspeed_required
1172
+ def get_deepspeed_plugin(self, name: str):
1173
+ """
1174
+ Returns the DeepSpeedPlugin with the given plugin_key.
1175
+ """
1176
+ return self.deepspeed_plugins[name]
1177
+
1178
+ @deepspeed_required
1179
+ def select_deepspeed_plugin(self, name: str = None):
1180
+ """
1181
+ Activates the DeepSpeedPlugin with the given `name`, and will disable all other plugins.
1182
+ """
1183
+ for key, plugin in self.deepspeed_plugins.items():
1184
+ if key != name:
1185
+ plugin._unselect()
1186
+ self.deepspeed_plugins[name].select(_from_accelerator_state=True)
1187
+
1188
+ def print(self, *args, **kwargs):
1189
+ PartialState().print(*args, **kwargs)
1190
+
1191
+ def __getattr__(self, name: str):
1192
+ # By this point we know that no attributes of `self` contain `name`,
1193
+ # so we just modify the error message
1194
+ if name in self._known_attrs:
1195
+ raise AttributeError(
1196
+ f"`AcceleratorState` object has no attribute `{name}`. "
1197
+ "This happens if `AcceleratorState._reset_state()` was called and "
1198
+ "an `Accelerator` or `PartialState` was not reinitialized."
1199
+ )
1200
+ # Raise a typical AttributeError
1201
+ raise AttributeError(f"'AcceleratorState' object has no attribute '{name}'")
1202
+
1203
+
1204
+ class GradientState:
1205
+ """
1206
+ Singleton class that has information related to gradient synchronization for gradient accumulation
1207
+
1208
+ **Available attributes:**
1209
+
1210
+ - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader
1211
+ - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader
1212
+ - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices
1213
+ - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over
1214
+ - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are
1215
+ being iterated over
1216
+ - **num_steps** (`int`) -- The number of steps to accumulate over
1217
+ - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient
1218
+ accumulation
1219
+ - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader
1220
+ iteration and the number of total steps reset
1221
+ - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized
1222
+ as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently,
1223
+ after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence
1224
+ is_xla_gradients_synced is always true.
1225
+ """
1226
+
1227
+ _shared_state = SharedDict()
1228
+
1229
+ def __init__(self, gradient_accumulation_plugin: GradientAccumulationPlugin | None = None):
1230
+ self.__dict__ = self._shared_state
1231
+ if not self.initialized:
1232
+ self.sync_gradients = True
1233
+ self._dataloader_references_ref = [None]
1234
+ self.plugin_kwargs = (
1235
+ gradient_accumulation_plugin.to_kwargs() if gradient_accumulation_plugin is not None else {}
1236
+ )
1237
+ self._is_xla_gradients_synced = False
1238
+
1239
+ # Plugin args are different and can be updated
1240
+ if gradient_accumulation_plugin is not None and self.plugin_kwargs != gradient_accumulation_plugin.to_kwargs():
1241
+ self.plugin_kwargs = gradient_accumulation_plugin.to_kwargs()
1242
+
1243
+ @property
1244
+ def num_steps(self) -> int:
1245
+ "Returns the number of steps to accumulate over"
1246
+ return self.plugin_kwargs.get("num_steps", 1)
1247
+
1248
+ @property
1249
+ def adjust_scheduler(self) -> bool:
1250
+ "Returns whether the scheduler should be adjusted"
1251
+ return self.plugin_kwargs.get("adjust_scheduler", False)
1252
+
1253
+ @property
1254
+ def sync_with_dataloader(self) -> bool:
1255
+ "Returns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset"
1256
+ return self.plugin_kwargs.get("sync_with_dataloader", True)
1257
+
1258
+ @property
1259
+ def initialized(self) -> bool:
1260
+ "Returns whether the `GradientState` has been initialized"
1261
+ return GradientState._shared_state != {}
1262
+
1263
+ @property
1264
+ def end_of_dataloader(self) -> bool:
1265
+ "Returns whether we have reached the end of the current dataloader"
1266
+ if not self.in_dataloader:
1267
+ return False
1268
+ return self.active_dataloader.end_of_dataloader
1269
+
1270
+ @property
1271
+ def remainder(self) -> int:
1272
+ "Returns the number of extra samples that were added from padding the dataloader"
1273
+ if not self.in_dataloader:
1274
+ return -1
1275
+ return self.active_dataloader.remainder
1276
+
1277
+ def __repr__(self):
1278
+ return (
1279
+ f"Sync Gradients: {self.sync_gradients}\n"
1280
+ f"At end of current dataloader: {self.end_of_dataloader}\n"
1281
+ f"Extra samples added: {self.remainder}\n"
1282
+ f"Gradient accumulation plugin: {self.plugin_kwargs}\n"
1283
+ )
1284
+
1285
+ @property
1286
+ def is_xla_gradients_synced(self):
1287
+ "Returns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true."
1288
+ if parse_flag_from_env("ACCELERATE_USE_FSDP", default=False):
1289
+ return True
1290
+ return self._is_xla_gradients_synced
1291
+
1292
+ @is_xla_gradients_synced.setter
1293
+ def is_xla_gradients_synced(self, is_synced):
1294
+ "Set the _is_xla_gradients_synced attribute."
1295
+ self._is_xla_gradients_synced = is_synced
1296
+
1297
+ def _set_sync_gradients(self, sync_gradients):
1298
+ "Private function that sets whether gradients should be synchronized. Users should not have to call this."
1299
+ self.sync_gradients = sync_gradients
1300
+ # Allow grad-sync to automatically work on TPUs
1301
+ if (
1302
+ self.sync_gradients
1303
+ and is_torch_xla_available(check_is_tpu=True)
1304
+ and PartialState().distributed_type == DistributedType.XLA
1305
+ ):
1306
+ xm.mark_step()
1307
+
1308
+ def _add_dataloader(self, dataloader):
1309
+ "Private function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this."
1310
+ # We explicitly use assignment to ensure that the property setter is triggered, which is required for garbage collection.
1311
+ # Avoid using self.dataloader_references.append as it will not trigger the setter.
1312
+ self.dataloader_references += [dataloader]
1313
+
1314
+ def _remove_dataloader(self, dataloader):
1315
+ "Private function that removes a dataloader from `self.dataloader_references` and sets `in_dataloader` to `False` if there are no more dataloaders. Users should not have to call this."
1316
+ # We explicitly use assignment to ensure that the property setter is triggered.
1317
+ self.dataloader_references = [
1318
+ dataloader_ref for dataloader_ref in self.dataloader_references if dataloader_ref != dataloader
1319
+ ]
1320
+
1321
+ @property
1322
+ def active_dataloader(self):
1323
+ return self.dataloader_references[-1]
1324
+
1325
+ @property
1326
+ def dataloader_references(self):
1327
+ # We use a property getter and setter with weakrefs to avoid circular references that prevent garbage collection
1328
+ return [reference() if reference is not None else reference for reference in self._dataloader_references_ref]
1329
+
1330
+ @dataloader_references.setter
1331
+ def dataloader_references(self, references):
1332
+ self._dataloader_references_ref = [
1333
+ weakref.ref(dataloader) if dataloader is not None else dataloader for dataloader in references
1334
+ ]
1335
+
1336
+ @property
1337
+ def in_dataloader(self) -> bool:
1338
+ "Returns whether the current process is in a dataloader"
1339
+ return self.active_dataloader is not None
1340
+
1341
+ @staticmethod
1342
+ def _reset_state():
1343
+ "Resets `_shared_state`, is used internally and should not be called"
1344
+ GradientState._shared_state.clear()
python_embeded/Lib/site-packages/accelerate/tracking.py ADDED
@@ -0,0 +1,1233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Expectation:
16
+ # Provide a project dir name, then each type of logger gets stored in project/{`logging_dir`}
17
+
18
+ import json
19
+ import os
20
+ import time
21
+ from functools import wraps
22
+ from typing import Any, Optional, Union
23
+
24
+ import yaml
25
+ from packaging import version
26
+
27
+ from .logging import get_logger
28
+ from .state import PartialState
29
+ from .utils import (
30
+ LoggerType,
31
+ compare_versions,
32
+ is_aim_available,
33
+ is_clearml_available,
34
+ is_comet_ml_available,
35
+ is_dvclive_available,
36
+ is_mlflow_available,
37
+ is_swanlab_available,
38
+ is_tensorboard_available,
39
+ is_wandb_available,
40
+ listify,
41
+ )
42
+
43
+
44
+ _available_trackers = []
45
+
46
+ if is_tensorboard_available():
47
+ _available_trackers.append(LoggerType.TENSORBOARD)
48
+
49
+ if is_wandb_available():
50
+ _available_trackers.append(LoggerType.WANDB)
51
+
52
+ if is_comet_ml_available():
53
+ _available_trackers.append(LoggerType.COMETML)
54
+
55
+ if is_aim_available():
56
+ _available_trackers.append(LoggerType.AIM)
57
+
58
+ if is_mlflow_available():
59
+ _available_trackers.append(LoggerType.MLFLOW)
60
+
61
+ if is_clearml_available():
62
+ _available_trackers.append(LoggerType.CLEARML)
63
+
64
+ if is_dvclive_available():
65
+ _available_trackers.append(LoggerType.DVCLIVE)
66
+
67
+ if is_swanlab_available():
68
+ _available_trackers.append(LoggerType.SWANLAB)
69
+
70
+ logger = get_logger(__name__)
71
+
72
+
73
+ def on_main_process(function):
74
+ """
75
+ Decorator to selectively run the decorated function on the main process only based on the `main_process_only`
76
+ attribute in a class.
77
+
78
+ Checks at function execution rather than initialization time, not triggering the initialization of the
79
+ `PartialState`.
80
+ """
81
+
82
+ @wraps(function)
83
+ def execute_on_main_process(self, *args, **kwargs):
84
+ if getattr(self, "main_process_only", False):
85
+ return PartialState().on_main_process(function)(self, *args, **kwargs)
86
+ else:
87
+ return function(self, *args, **kwargs)
88
+
89
+ return execute_on_main_process
90
+
91
+
92
+ def get_available_trackers():
93
+ "Returns a list of all supported available trackers in the system"
94
+ return _available_trackers
95
+
96
+
97
+ class GeneralTracker:
98
+ """
99
+ A base Tracker class to be used for all logging integration implementations.
100
+
101
+ Each function should take in `**kwargs` that will automatically be passed in from a base dictionary provided to
102
+ [`Accelerator`].
103
+
104
+ Should implement `name`, `requires_logging_directory`, and `tracker` properties such that:
105
+
106
+ `name` (`str`): String representation of the tracker class name, such as "TensorBoard" `requires_logging_directory`
107
+ (`bool`): Whether the logger requires a directory to store their logs. `tracker` (`object`): Should return internal
108
+ tracking mechanism used by a tracker class (such as the `run` for wandb)
109
+
110
+ Implementations can also include a `main_process_only` (`bool`) attribute to toggle if relevent logging, init, and
111
+ other functions should occur on the main process or across all processes (by default will use `True`)
112
+ """
113
+
114
+ main_process_only = True
115
+
116
+ def __init__(self, _blank=False):
117
+ if not _blank:
118
+ err = ""
119
+ if not hasattr(self, "name"):
120
+ err += "`name`"
121
+ if not hasattr(self, "requires_logging_directory"):
122
+ if len(err) > 0:
123
+ err += ", "
124
+ err += "`requires_logging_directory`"
125
+
126
+ # as tracker is a @property that relies on post-init
127
+ if "tracker" not in dir(self):
128
+ if len(err) > 0:
129
+ err += ", "
130
+ err += "`tracker`"
131
+ if len(err) > 0:
132
+ raise NotImplementedError(
133
+ f"The implementation for this tracker class is missing the following "
134
+ f"required attributes. Please define them in the class definition: "
135
+ f"{err}"
136
+ )
137
+
138
+ def start(self):
139
+ """
140
+ Lazy initialization of the tracker inside Accelerator to avoid initializing PartialState before
141
+ InitProcessGroupKwargs.
142
+ """
143
+ pass
144
+
145
+ def store_init_configuration(self, values: dict):
146
+ """
147
+ Logs `values` as hyperparameters for the run. Implementations should use the experiment configuration
148
+ functionality of a tracking API.
149
+
150
+ Args:
151
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
152
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
153
+ `str`, `float`, `int`, or `None`.
154
+ """
155
+ pass
156
+
157
+ def log(self, values: dict, step: Optional[int], **kwargs):
158
+ """
159
+ Logs `values` to the current run. Base `log` implementations of a tracking API should go in here, along with
160
+ special behavior for the `step parameter.
161
+
162
+ Args:
163
+ values (Dictionary `str` to `str`, `float`, or `int`):
164
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
165
+ step (`int`, *optional*):
166
+ The run step. If included, the log will be affiliated with this step.
167
+ """
168
+ pass
169
+
170
+ def finish(self):
171
+ """
172
+ Should run any finalizing functions within the tracking API. If the API should not have one, just don't
173
+ overwrite that method.
174
+ """
175
+ pass
176
+
177
+
178
+ class TensorBoardTracker(GeneralTracker):
179
+ """
180
+ A `Tracker` class that supports `tensorboard`. Should be initialized at the start of your script.
181
+
182
+ Args:
183
+ run_name (`str`):
184
+ The name of the experiment run
185
+ logging_dir (`str`, `os.PathLike`):
186
+ Location for TensorBoard logs to be stored.
187
+ **kwargs (additional keyword arguments, *optional*):
188
+ Additional key word arguments passed along to the `tensorboard.SummaryWriter.__init__` method.
189
+ """
190
+
191
+ name = "tensorboard"
192
+ requires_logging_directory = True
193
+
194
+ def __init__(self, run_name: str, logging_dir: Union[str, os.PathLike], **kwargs):
195
+ super().__init__()
196
+ self.run_name = run_name
197
+ self.logging_dir_param = logging_dir
198
+ self.init_kwargs = kwargs
199
+
200
+ @on_main_process
201
+ def start(self):
202
+ try:
203
+ from torch.utils import tensorboard
204
+ except ModuleNotFoundError:
205
+ import tensorboardX as tensorboard
206
+ self.logging_dir = os.path.join(self.logging_dir_param, self.run_name)
207
+ self.writer = tensorboard.SummaryWriter(self.logging_dir, **self.init_kwargs)
208
+ logger.debug(f"Initialized TensorBoard project {self.run_name} logging to {self.logging_dir}")
209
+ logger.debug(
210
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
211
+ )
212
+
213
+ @property
214
+ def tracker(self):
215
+ return self.writer
216
+
217
+ @on_main_process
218
+ def store_init_configuration(self, values: dict):
219
+ """
220
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
221
+ hyperparameters in a yaml file for future use.
222
+
223
+ Args:
224
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
225
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
226
+ `str`, `float`, `int`, or `None`.
227
+ """
228
+ self.writer.add_hparams(values, metric_dict={})
229
+ self.writer.flush()
230
+ project_run_name = time.time()
231
+ dir_name = os.path.join(self.logging_dir, str(project_run_name))
232
+ os.makedirs(dir_name, exist_ok=True)
233
+ with open(os.path.join(dir_name, "hparams.yml"), "w") as outfile:
234
+ try:
235
+ yaml.dump(values, outfile)
236
+ except yaml.representer.RepresenterError:
237
+ logger.error("Serialization to store hyperparameters failed")
238
+ raise
239
+ logger.debug("Stored initial configuration hyperparameters to TensorBoard and hparams yaml file")
240
+
241
+ @on_main_process
242
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
243
+ """
244
+ Logs `values` to the current run.
245
+
246
+ Args:
247
+ values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
248
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
249
+ `str` to `float`/`int`.
250
+ step (`int`, *optional*):
251
+ The run step. If included, the log will be affiliated with this step.
252
+ kwargs:
253
+ Additional key word arguments passed along to either `SummaryWriter.add_scaler`,
254
+ `SummaryWriter.add_text`, or `SummaryWriter.add_scalers` method based on the contents of `values`.
255
+ """
256
+ values = listify(values)
257
+ for k, v in values.items():
258
+ if isinstance(v, (int, float)):
259
+ self.writer.add_scalar(k, v, global_step=step, **kwargs)
260
+ elif isinstance(v, str):
261
+ self.writer.add_text(k, v, global_step=step, **kwargs)
262
+ elif isinstance(v, dict):
263
+ self.writer.add_scalars(k, v, global_step=step, **kwargs)
264
+ self.writer.flush()
265
+ logger.debug("Successfully logged to TensorBoard")
266
+
267
+ @on_main_process
268
+ def log_images(self, values: dict, step: Optional[int], **kwargs):
269
+ """
270
+ Logs `images` to the current run.
271
+
272
+ Args:
273
+ values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
274
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
275
+ step (`int`, *optional*):
276
+ The run step. If included, the log will be affiliated with this step.
277
+ kwargs:
278
+ Additional key word arguments passed along to the `SummaryWriter.add_image` method.
279
+ """
280
+ for k, v in values.items():
281
+ self.writer.add_images(k, v, global_step=step, **kwargs)
282
+ logger.debug("Successfully logged images to TensorBoard")
283
+
284
+ @on_main_process
285
+ def finish(self):
286
+ """
287
+ Closes `TensorBoard` writer
288
+ """
289
+ self.writer.close()
290
+ logger.debug("TensorBoard writer closed")
291
+
292
+
293
+ class WandBTracker(GeneralTracker):
294
+ """
295
+ A `Tracker` class that supports `wandb`. Should be initialized at the start of your script.
296
+
297
+ Args:
298
+ run_name (`str`):
299
+ The name of the experiment run.
300
+ **kwargs (additional keyword arguments, *optional*):
301
+ Additional key word arguments passed along to the `wandb.init` method.
302
+ """
303
+
304
+ name = "wandb"
305
+ requires_logging_directory = False
306
+ main_process_only = False
307
+
308
+ def __init__(self, run_name: str, **kwargs):
309
+ super().__init__()
310
+ self.run_name = run_name
311
+ self.init_kwargs = kwargs
312
+
313
+ @on_main_process
314
+ def start(self):
315
+ import wandb
316
+
317
+ self.run = wandb.init(project=self.run_name, **self.init_kwargs)
318
+ logger.debug(f"Initialized WandB project {self.run_name}")
319
+ logger.debug(
320
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
321
+ )
322
+
323
+ @property
324
+ def tracker(self):
325
+ return self.run
326
+
327
+ @on_main_process
328
+ def store_init_configuration(self, values: dict):
329
+ """
330
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
331
+
332
+ Args:
333
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
334
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
335
+ `str`, `float`, `int`, or `None`.
336
+ """
337
+ import wandb
338
+
339
+ wandb.config.update(values, allow_val_change=True)
340
+ logger.debug("Stored initial configuration hyperparameters to WandB")
341
+
342
+ @on_main_process
343
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
344
+ """
345
+ Logs `values` to the current run.
346
+
347
+ Args:
348
+ values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
349
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
350
+ `str` to `float`/`int`.
351
+ step (`int`, *optional*):
352
+ The run step. If included, the log will be affiliated with this step.
353
+ kwargs:
354
+ Additional key word arguments passed along to the `wandb.log` method.
355
+ """
356
+ self.run.log(values, step=step, **kwargs)
357
+ logger.debug("Successfully logged to WandB")
358
+
359
+ @on_main_process
360
+ def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
361
+ """
362
+ Logs `images` to the current run.
363
+
364
+ Args:
365
+ values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
366
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
367
+ step (`int`, *optional*):
368
+ The run step. If included, the log will be affiliated with this step.
369
+ kwargs:
370
+ Additional key word arguments passed along to the `wandb.log` method.
371
+ """
372
+ import wandb
373
+
374
+ for k, v in values.items():
375
+ self.log({k: [wandb.Image(image) for image in v]}, step=step, **kwargs)
376
+ logger.debug("Successfully logged images to WandB")
377
+
378
+ @on_main_process
379
+ def log_table(
380
+ self,
381
+ table_name: str,
382
+ columns: list[str] = None,
383
+ data: list[list[Any]] = None,
384
+ dataframe: Any = None,
385
+ step: Optional[int] = None,
386
+ **kwargs,
387
+ ):
388
+ """
389
+ Log a Table containing any object type (text, image, audio, video, molecule, html, etc). Can be defined either
390
+ with `columns` and `data` or with `dataframe`.
391
+
392
+ Args:
393
+ table_name (`str`):
394
+ The name to give to the logged table on the wandb workspace
395
+ columns (list of `str`, *optional*):
396
+ The name of the columns on the table
397
+ data (List of List of Any data type, *optional*):
398
+ The data to be logged in the table
399
+ dataframe (Any data type, *optional*):
400
+ The data to be logged in the table
401
+ step (`int`, *optional*):
402
+ The run step. If included, the log will be affiliated with this step.
403
+ """
404
+ import wandb
405
+
406
+ values = {table_name: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
407
+ self.log(values, step=step, **kwargs)
408
+
409
+ @on_main_process
410
+ def finish(self):
411
+ """
412
+ Closes `wandb` writer
413
+ """
414
+ self.run.finish()
415
+ logger.debug("WandB run closed")
416
+
417
+
418
+ class CometMLTracker(GeneralTracker):
419
+ """
420
+ A `Tracker` class that supports `comet_ml`. Should be initialized at the start of your script.
421
+
422
+ API keys must be stored in a Comet config file.
423
+
424
+ Note:
425
+ For `comet_ml` versions < 3.41.0, additional keyword arguments are passed to `comet_ml.Experiment` instead:
426
+ https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/Experiment/#comet_ml.Experiment.__init__
427
+
428
+ Args:
429
+ run_name (`str`):
430
+ The name of the experiment run.
431
+ **kwargs (additional keyword arguments, *optional*):
432
+ Additional key word arguments passed along to the `comet_ml.start` method:
433
+ https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/start/
434
+ """
435
+
436
+ name = "comet_ml"
437
+ requires_logging_directory = False
438
+
439
+ def __init__(self, run_name: str, **kwargs):
440
+ super().__init__()
441
+ self.run_name = run_name
442
+ self.init_kwargs = kwargs
443
+
444
+ @on_main_process
445
+ def start(self):
446
+ import comet_ml
447
+
448
+ comet_version = version.parse(comet_ml.__version__)
449
+ if compare_versions(comet_version, ">=", "3.41.0"):
450
+ self.writer = comet_ml.start(project_name=self.run_name, **self.init_kwargs)
451
+ else:
452
+ logger.info("Update `comet_ml` (>=3.41.0) for experiment reuse and offline support.")
453
+ self.writer = comet_ml.Experiment(project_name=self.run_name, **self.init_kwargs)
454
+
455
+ logger.debug(f"Initialized CometML project {self.run_name}")
456
+ logger.debug(
457
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
458
+ )
459
+
460
+ @property
461
+ def tracker(self):
462
+ return self.writer
463
+
464
+ @on_main_process
465
+ def store_init_configuration(self, values: dict):
466
+ """
467
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
468
+
469
+ Args:
470
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
471
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
472
+ `str`, `float`, `int`, or `None`.
473
+ """
474
+ self.writer.log_parameters(values)
475
+ logger.debug("Stored initial configuration hyperparameters to Comet")
476
+
477
+ @on_main_process
478
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
479
+ """
480
+ Logs `values` to the current run.
481
+
482
+ Args:
483
+ values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
484
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
485
+ `str` to `float`/`int`.
486
+ step (`int`, *optional*):
487
+ The run step. If included, the log will be affiliated with this step.
488
+ kwargs:
489
+ Additional key word arguments passed along to either `Experiment.log_metric`, `Experiment.log_other`,
490
+ or `Experiment.log_metrics` method based on the contents of `values`.
491
+ """
492
+ if step is not None:
493
+ self.writer.set_step(step)
494
+ for k, v in values.items():
495
+ if isinstance(v, (int, float)):
496
+ self.writer.log_metric(k, v, step=step, **kwargs)
497
+ elif isinstance(v, str):
498
+ self.writer.log_other(k, v, **kwargs)
499
+ elif isinstance(v, dict):
500
+ self.writer.log_metrics(v, step=step, **kwargs)
501
+ logger.debug("Successfully logged to Comet")
502
+
503
+ @on_main_process
504
+ def finish(self):
505
+ """
506
+ Flush `comet-ml` writer
507
+ """
508
+ self.writer.end()
509
+ logger.debug("Comet run flushed")
510
+
511
+
512
+ class AimTracker(GeneralTracker):
513
+ """
514
+ A `Tracker` class that supports `aim`. Should be initialized at the start of your script.
515
+
516
+ Args:
517
+ run_name (`str`):
518
+ The name of the experiment run.
519
+ **kwargs (additional keyword arguments, *optional*):
520
+ Additional key word arguments passed along to the `Run.__init__` method.
521
+ """
522
+
523
+ name = "aim"
524
+ requires_logging_directory = True
525
+
526
+ def __init__(self, run_name: str, logging_dir: Optional[Union[str, os.PathLike]] = ".", **kwargs):
527
+ super().__init__()
528
+ self.run_name = run_name
529
+ self.aim_repo_path = logging_dir
530
+ self.init_kwargs = kwargs
531
+
532
+ @on_main_process
533
+ def start(self):
534
+ from aim import Run
535
+
536
+ self.writer = Run(repo=self.aim_repo_path, **self.init_kwargs)
537
+ self.writer.name = self.run_name
538
+ logger.debug(f"Initialized Aim project {self.run_name}")
539
+ logger.debug(
540
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
541
+ )
542
+
543
+ @property
544
+ def tracker(self):
545
+ return self.writer
546
+
547
+ @on_main_process
548
+ def store_init_configuration(self, values: dict):
549
+ """
550
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
551
+
552
+ Args:
553
+ values (`dict`):
554
+ Values to be stored as initial hyperparameters as key-value pairs.
555
+ """
556
+ self.writer["hparams"] = values
557
+
558
+ @on_main_process
559
+ def log(self, values: dict, step: Optional[int], **kwargs):
560
+ """
561
+ Logs `values` to the current run.
562
+
563
+ Args:
564
+ values (`dict`):
565
+ Values to be logged as key-value pairs.
566
+ step (`int`, *optional*):
567
+ The run step. If included, the log will be affiliated with this step.
568
+ kwargs:
569
+ Additional key word arguments passed along to the `Run.track` method.
570
+ """
571
+ # Note: replace this with the dictionary support when merged
572
+ for key, value in values.items():
573
+ self.writer.track(value, name=key, step=step, **kwargs)
574
+
575
+ @on_main_process
576
+ def log_images(self, values: dict, step: Optional[int] = None, kwargs: Optional[dict[str, dict]] = None):
577
+ """
578
+ Logs `images` to the current run.
579
+
580
+ Args:
581
+ values (`Dict[str, Union[np.ndarray, PIL.Image, Tuple[np.ndarray, str], Tuple[PIL.Image, str]]]`):
582
+ Values to be logged as key-value pairs. The values need to have type `np.ndarray` or PIL.Image. If a
583
+ tuple is provided, the first element should be the image and the second element should be the caption.
584
+ step (`int`, *optional*):
585
+ The run step. If included, the log will be affiliated with this step.
586
+ kwargs (`Dict[str, dict]`):
587
+ Additional key word arguments passed along to the `Run.Image` and `Run.track` method specified by the
588
+ keys `aim_image` and `track`, respectively.
589
+ """
590
+ import aim
591
+
592
+ aim_image_kw = {}
593
+ track_kw = {}
594
+
595
+ if kwargs is not None:
596
+ aim_image_kw = kwargs.get("aim_image", {})
597
+ track_kw = kwargs.get("track", {})
598
+
599
+ for key, value in values.items():
600
+ if isinstance(value, tuple):
601
+ img, caption = value
602
+ else:
603
+ img, caption = value, ""
604
+ aim_image = aim.Image(img, caption=caption, **aim_image_kw)
605
+ self.writer.track(aim_image, name=key, step=step, **track_kw)
606
+
607
+ @on_main_process
608
+ def finish(self):
609
+ """
610
+ Closes `aim` writer
611
+ """
612
+ self.writer.close()
613
+
614
+
615
+ class MLflowTracker(GeneralTracker):
616
+ """
617
+ A `Tracker` class that supports `mlflow`. Should be initialized at the start of your script.
618
+
619
+ Args:
620
+ experiment_name (`str`, *optional*):
621
+ Name of the experiment. Environment variable MLFLOW_EXPERIMENT_NAME has priority over this argument.
622
+ logging_dir (`str` or `os.PathLike`, defaults to `"."`):
623
+ Location for mlflow logs to be stored.
624
+ run_id (`str`, *optional*):
625
+ If specified, get the run with the specified UUID and log parameters and metrics under that run. The run’s
626
+ end time is unset and its status is set to running, but the run’s other attributes (source_version,
627
+ source_type, etc.) are not changed. Environment variable MLFLOW_RUN_ID has priority over this argument.
628
+ tags (`Dict[str, str]`, *optional*):
629
+ An optional `dict` of `str` keys and values, or a `str` dump from a `dict`, to set as tags on the run. If a
630
+ run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are
631
+ set on the new run. Environment variable MLFLOW_TAGS has priority over this argument.
632
+ nested_run (`bool`, *optional*, defaults to `False`):
633
+ Controls whether run is nested in parent run. True creates a nested run. Environment variable
634
+ MLFLOW_NESTED_RUN has priority over this argument.
635
+ run_name (`str`, *optional*):
636
+ Name of new run (stored as a mlflow.runName tag). Used only when `run_id` is unspecified.
637
+ description (`str`, *optional*):
638
+ An optional string that populates the description box of the run. If a run is being resumed, the
639
+ description is set on the resumed run. If a new run is being created, the description is set on the new
640
+ run.
641
+ """
642
+
643
+ name = "mlflow"
644
+ requires_logging_directory = False
645
+
646
+ def __init__(
647
+ self,
648
+ experiment_name: str = None,
649
+ logging_dir: Optional[Union[str, os.PathLike]] = None,
650
+ run_id: Optional[str] = None,
651
+ tags: Optional[Union[dict[str, Any], str]] = None,
652
+ nested_run: Optional[bool] = False,
653
+ run_name: Optional[str] = None,
654
+ description: Optional[str] = None,
655
+ ):
656
+ experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME", experiment_name)
657
+ run_id = os.environ.get("MLFLOW_RUN_ID", run_id)
658
+ tags = os.environ.get("MLFLOW_TAGS", tags)
659
+ if isinstance(tags, str):
660
+ tags = json.loads(tags)
661
+
662
+ nested_run = os.environ.get("MLFLOW_NESTED_RUN", nested_run)
663
+
664
+ self.experiment_name = experiment_name
665
+ self.logging_dir = logging_dir
666
+ self.run_id = run_id
667
+ self.tags = tags
668
+ self.nested_run = nested_run
669
+ self.run_name = run_name
670
+ self.description = description
671
+
672
+ @on_main_process
673
+ def start(self):
674
+ import mlflow
675
+
676
+ exps = mlflow.search_experiments(filter_string=f"name = '{self.experiment_name}'")
677
+ if len(exps) > 0:
678
+ if len(exps) > 1:
679
+ logger.warning("Multiple experiments with the same name found. Using first one.")
680
+ experiment_id = exps[0].experiment_id
681
+ else:
682
+ experiment_id = mlflow.create_experiment(
683
+ name=self.experiment_name,
684
+ artifact_location=self.logging_dir,
685
+ tags=self.tags,
686
+ )
687
+
688
+ self.active_run = mlflow.start_run(
689
+ run_id=self.run_id,
690
+ experiment_id=experiment_id,
691
+ run_name=self.run_name,
692
+ nested=self.nested_run,
693
+ tags=self.tags,
694
+ description=self.description,
695
+ )
696
+
697
+ logger.debug(f"Initialized mlflow experiment {self.experiment_name}")
698
+ logger.debug(
699
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
700
+ )
701
+
702
+ @property
703
+ def tracker(self):
704
+ return self.active_run
705
+
706
+ @on_main_process
707
+ def store_init_configuration(self, values: dict):
708
+ """
709
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
710
+
711
+ Args:
712
+ values (`dict`):
713
+ Values to be stored as initial hyperparameters as key-value pairs.
714
+ """
715
+ import mlflow
716
+
717
+ for name, value in list(values.items()):
718
+ # internally, all values are converted to str in MLflow
719
+ if len(str(value)) > mlflow.utils.validation.MAX_PARAM_VAL_LENGTH:
720
+ logger.warning_once(
721
+ f'Accelerate is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
722
+ f" log_param() only accepts values no longer than {mlflow.utils.validation.MAX_PARAM_VAL_LENGTH} characters so we dropped this attribute."
723
+ )
724
+ del values[name]
725
+
726
+ values_list = list(values.items())
727
+
728
+ # MLflow cannot log more than 100 values in one go, so we have to split it
729
+ for i in range(0, len(values_list), mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH):
730
+ mlflow.log_params(dict(values_list[i : i + mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH]))
731
+
732
+ logger.debug("Stored initial configuration hyperparameters to MLflow")
733
+
734
+ @on_main_process
735
+ def log(self, values: dict, step: Optional[int]):
736
+ """
737
+ Logs `values` to the current run.
738
+
739
+ Args:
740
+ values (`dict`):
741
+ Values to be logged as key-value pairs.
742
+ step (`int`, *optional*):
743
+ The run step. If included, the log will be affiliated with this step.
744
+ """
745
+ metrics = {}
746
+ for k, v in values.items():
747
+ if isinstance(v, (int, float)):
748
+ metrics[k] = v
749
+ else:
750
+ logger.warning_once(
751
+ f'MLflowTracker is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
752
+ "MLflow's log_metric() only accepts float and int types so we dropped this attribute."
753
+ )
754
+ import mlflow
755
+
756
+ mlflow.log_metrics(metrics, step=step)
757
+ logger.debug("Successfully logged to mlflow")
758
+
759
+ @on_main_process
760
+ def log_figure(self, figure: Any, artifact_file: str, **save_kwargs):
761
+ """
762
+ Logs an figure to the current run.
763
+
764
+ Args:
765
+ figure (Any):
766
+ The figure to be logged.
767
+ artifact_file (`str`, *optional*):
768
+ The run-relative artifact file path in posixpath format to which the image is saved.
769
+ If not provided, the image is saved to a default location.
770
+ **kwargs:
771
+ Additional keyword arguments passed to the underlying mlflow.log_image function.
772
+ """
773
+ import mlflow
774
+
775
+ mlflow.log_figure(figure=figure, artifact_file=artifact_file, **save_kwargs)
776
+ logger.debug("Successfully logged image to mlflow")
777
+
778
+ @on_main_process
779
+ def log_artifacts(self, local_dir: str, artifact_path: Optional[str] = None):
780
+ """
781
+ Logs an artifacts (all content of a dir) to the current run.
782
+
783
+ local_dir (`str`):
784
+ Path to the directory to be logged as an artifact.
785
+ artifact_path (`str`, *optional*):
786
+ Directory within the run's artifact directory where the artifact will be logged. If omitted, the
787
+ artifact will be logged to the root of the run's artifact directory. The run step. If included, the
788
+ artifact will be affiliated with this step.
789
+ """
790
+ import mlflow
791
+
792
+ mlflow.log_artifacts(local_dir=local_dir, artifact_path=artifact_path)
793
+ logger.debug("Successfully logged artofact to mlflow")
794
+
795
+ @on_main_process
796
+ def log_artifact(self, local_path: str, artifact_path: Optional[str] = None):
797
+ """
798
+ Logs an artifact (file) to the current run.
799
+
800
+ local_path (`str`):
801
+ Path to the file to be logged as an artifact.
802
+ artifact_path (`str`, *optional*):
803
+ Directory within the run's artifact directory where the artifact will be logged. If omitted, the
804
+ artifact will be logged to the root of the run's artifact directory. The run step. If included, the
805
+ artifact will be affiliated with this step.
806
+ """
807
+ import mlflow
808
+
809
+ mlflow.log_artifact(local_path=local_path, artifact_path=artifact_path)
810
+ logger.debug("Successfully logged artofact to mlflow")
811
+
812
+ @on_main_process
813
+ def finish(self):
814
+ """
815
+ End the active MLflow run.
816
+ """
817
+ import mlflow
818
+
819
+ mlflow.end_run()
820
+
821
+
822
+ class ClearMLTracker(GeneralTracker):
823
+ """
824
+ A `Tracker` class that supports `clearml`. Should be initialized at the start of your script.
825
+
826
+ Args:
827
+ run_name (`str`, *optional*):
828
+ Name of the experiment. Environment variables `CLEARML_PROJECT` and `CLEARML_TASK` have priority over this
829
+ argument.
830
+ **kwargs (additional keyword arguments, *optional*):
831
+ Kwargs passed along to the `Task.__init__` method.
832
+ """
833
+
834
+ name = "clearml"
835
+ requires_logging_directory = False
836
+
837
+ def __init__(self, run_name: str = None, **kwargs):
838
+ super().__init__()
839
+ self.user_provided_run_name = run_name
840
+ self._initialized_externally = False
841
+ self.init_kwargs = kwargs
842
+
843
+ @on_main_process
844
+ def start(self):
845
+ from clearml import Task
846
+
847
+ current_task = Task.current_task()
848
+ if current_task:
849
+ self._initialized_externally = True
850
+ self.task = current_task
851
+ return
852
+
853
+ task_init_args = {**self.init_kwargs}
854
+ task_init_args.setdefault("project_name", os.environ.get("CLEARML_PROJECT", self.user_provided_run_name))
855
+ task_init_args.setdefault("task_name", os.environ.get("CLEARML_TASK", self.user_provided_run_name))
856
+ self.task = Task.init(**task_init_args)
857
+
858
+ @property
859
+ def tracker(self):
860
+ return self.task
861
+
862
+ @on_main_process
863
+ def store_init_configuration(self, values: dict):
864
+ """
865
+ Connect configuration dictionary to the Task object. Should be run at the beginning of your experiment.
866
+
867
+ Args:
868
+ values (`dict`):
869
+ Values to be stored as initial hyperparameters as key-value pairs.
870
+ """
871
+ return self.task.connect_configuration(values)
872
+
873
+ @on_main_process
874
+ def log(self, values: dict[str, Union[int, float]], step: Optional[int] = None, **kwargs):
875
+ """
876
+ Logs `values` dictionary to the current run. The dictionary keys must be strings. The dictionary values must be
877
+ ints or floats
878
+
879
+ Args:
880
+ values (`Dict[str, Union[int, float]]`):
881
+ Values to be logged as key-value pairs. If the key starts with 'eval_'/'test_'/'train_', the value will
882
+ be reported under the 'eval'/'test'/'train' series and the respective prefix will be removed.
883
+ Otherwise, the value will be reported under the 'train' series, and no prefix will be removed.
884
+ step (`int`, *optional*):
885
+ If specified, the values will be reported as scalars, with the iteration number equal to `step`.
886
+ Otherwise they will be reported as single values.
887
+ kwargs:
888
+ Additional key word arguments passed along to the `clearml.Logger.report_single_value` or
889
+ `clearml.Logger.report_scalar` methods.
890
+ """
891
+ clearml_logger = self.task.get_logger()
892
+ for k, v in values.items():
893
+ if not isinstance(v, (int, float)):
894
+ logger.warning_once(
895
+ "Accelerator is attempting to log a value of "
896
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
897
+ "This invocation of ClearML logger's report_scalar() "
898
+ "is incorrect so we dropped this attribute."
899
+ )
900
+ continue
901
+ if step is None:
902
+ clearml_logger.report_single_value(name=k, value=v, **kwargs)
903
+ continue
904
+ title, series = ClearMLTracker._get_title_series(k)
905
+ clearml_logger.report_scalar(title=title, series=series, value=v, iteration=step, **kwargs)
906
+
907
+ @on_main_process
908
+ def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
909
+ """
910
+ Logs `images` to the current run.
911
+
912
+ Args:
913
+ values (`Dict[str, List[Union[np.ndarray, PIL.Image]]`):
914
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
915
+ step (`int`, *optional*):
916
+ The run step. If included, the log will be affiliated with this step.
917
+ kwargs:
918
+ Additional key word arguments passed along to the `clearml.Logger.report_image` method.
919
+ """
920
+ clearml_logger = self.task.get_logger()
921
+ for k, v in values.items():
922
+ title, series = ClearMLTracker._get_title_series(k)
923
+ clearml_logger.report_image(title=title, series=series, iteration=step, image=v, **kwargs)
924
+
925
+ @on_main_process
926
+ def log_table(
927
+ self,
928
+ table_name: str,
929
+ columns: list[str] = None,
930
+ data: list[list[Any]] = None,
931
+ dataframe: Any = None,
932
+ step: Optional[int] = None,
933
+ **kwargs,
934
+ ):
935
+ """
936
+ Log a Table to the task. Can be defined eitherwith `columns` and `data` or with `dataframe`.
937
+
938
+ Args:
939
+ table_name (`str`):
940
+ The name of the table
941
+ columns (list of `str`, *optional*):
942
+ The name of the columns on the table
943
+ data (List of List of Any data type, *optional*):
944
+ The data to be logged in the table. If `columns` is not specified, then the first entry in data will be
945
+ the name of the columns of the table
946
+ dataframe (Any data type, *optional*):
947
+ The data to be logged in the table
948
+ step (`int`, *optional*):
949
+ The run step. If included, the log will be affiliated with this step.
950
+ kwargs:
951
+ Additional key word arguments passed along to the `clearml.Logger.report_table` method.
952
+ """
953
+ to_report = dataframe
954
+ if dataframe is None:
955
+ if data is None:
956
+ raise ValueError(
957
+ "`ClearMLTracker.log_table` requires that `data` to be supplied if `dataframe` is `None`"
958
+ )
959
+ to_report = [columns] + data if columns else data
960
+ title, series = ClearMLTracker._get_title_series(table_name)
961
+ self.task.get_logger().report_table(title=title, series=series, table_plot=to_report, iteration=step, **kwargs)
962
+
963
+ @on_main_process
964
+ def finish(self):
965
+ """
966
+ Close the ClearML task. If the task was initialized externally (e.g. by manually calling `Task.init`), this
967
+ function is a noop
968
+ """
969
+ if self.task and not self._initialized_externally:
970
+ self.task.close()
971
+
972
+ @staticmethod
973
+ def _get_title_series(name):
974
+ for prefix in ["eval", "test", "train"]:
975
+ if name.startswith(prefix + "_"):
976
+ return name[len(prefix) + 1 :], prefix
977
+ return name, "train"
978
+
979
+
980
+ class DVCLiveTracker(GeneralTracker):
981
+ """
982
+ A `Tracker` class that supports `dvclive`. Should be initialized at the start of your script.
983
+
984
+ Args:
985
+ run_name (`str`, *optional*):
986
+ Ignored for dvclive. See `kwargs` instead.
987
+ kwargs:
988
+ Additional key word arguments passed along to [`dvclive.Live()`](https://dvc.org/doc/dvclive/live).
989
+
990
+ Example:
991
+
992
+ ```py
993
+ from accelerate import Accelerator
994
+
995
+ accelerator = Accelerator(log_with="dvclive")
996
+ accelerator.init_trackers(project_name="my_project", init_kwargs={"dvclive": {"dir": "my_directory"}})
997
+ ```
998
+ """
999
+
1000
+ name = "dvclive"
1001
+ requires_logging_directory = False
1002
+
1003
+ def __init__(self, run_name: Optional[str] = None, live: Optional[Any] = None, **kwargs):
1004
+ super().__init__()
1005
+ self.live = live
1006
+ self.init_kwargs = kwargs
1007
+
1008
+ @on_main_process
1009
+ def start(self):
1010
+ from dvclive import Live
1011
+
1012
+ self.live = self.live if self.live is not None else Live(**self.init_kwargs)
1013
+
1014
+ @property
1015
+ def tracker(self):
1016
+ return self.live
1017
+
1018
+ @on_main_process
1019
+ def store_init_configuration(self, values: dict):
1020
+ """
1021
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
1022
+ hyperparameters in a yaml file for future use.
1023
+
1024
+ Args:
1025
+ values (Dictionary `str` to `bool`, `str`, `float`, `int`, or a List or Dict of those types):
1026
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
1027
+ `str`, `float`, or `int`.
1028
+ """
1029
+ self.live.log_params(values)
1030
+
1031
+ @on_main_process
1032
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
1033
+ """
1034
+ Logs `values` to the current run.
1035
+
1036
+ Args:
1037
+ values (Dictionary `str` to `str`, `float`, or `int`):
1038
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
1039
+ step (`int`, *optional*):
1040
+ The run step. If included, the log will be affiliated with this step.
1041
+ kwargs:
1042
+ Additional key word arguments passed along to `dvclive.Live.log_metric()`.
1043
+ """
1044
+ from dvclive.plots import Metric
1045
+
1046
+ if step is not None:
1047
+ self.live.step = step
1048
+ for k, v in values.items():
1049
+ if Metric.could_log(v):
1050
+ self.live.log_metric(k, v, **kwargs)
1051
+ else:
1052
+ logger.warning_once(
1053
+ "Accelerator attempted to log a value of "
1054
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
1055
+ "This invocation of DVCLive's Live.log_metric() "
1056
+ "is incorrect so we dropped this attribute."
1057
+ )
1058
+ self.live.next_step()
1059
+
1060
+ @on_main_process
1061
+ def finish(self):
1062
+ """
1063
+ Closes `dvclive.Live()`.
1064
+ """
1065
+ self.live.end()
1066
+
1067
+
1068
+ class SwanLabTracker(GeneralTracker):
1069
+ """
1070
+ A `Tracker` class that supports `swanlab`. Should be initialized at the start of your script.
1071
+
1072
+ Args:
1073
+ run_name (`str`):
1074
+ The name of the experiment run.
1075
+ **kwargs (additional keyword arguments, *optional*):
1076
+ Additional key word arguments passed along to the `swanlab.init` method.
1077
+ """
1078
+
1079
+ name = "swanlab"
1080
+ requires_logging_directory = False
1081
+ main_process_only = False
1082
+
1083
+ def __init__(self, run_name: str, **kwargs):
1084
+ super().__init__()
1085
+ self.run_name = run_name
1086
+ self.init_kwargs = kwargs
1087
+
1088
+ @on_main_process
1089
+ def start(self):
1090
+ import swanlab
1091
+
1092
+ self.run = swanlab.init(project=self.run_name, **self.init_kwargs)
1093
+ swanlab.config["FRAMEWORK"] = "🤗Accelerate" # add accelerate logo in config
1094
+ logger.debug(f"Initialized SwanLab project {self.run_name}")
1095
+ logger.debug(
1096
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
1097
+ )
1098
+
1099
+ @property
1100
+ def tracker(self):
1101
+ return self.run
1102
+
1103
+ @on_main_process
1104
+ def store_init_configuration(self, values: dict):
1105
+ """
1106
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
1107
+
1108
+ Args:
1109
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
1110
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
1111
+ `str`, `float`, `int`, or `None`.
1112
+ """
1113
+ import swanlab
1114
+
1115
+ swanlab.config.update(values, allow_val_change=True)
1116
+ logger.debug("Stored initial configuration hyperparameters to SwanLab")
1117
+
1118
+ @on_main_process
1119
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
1120
+ """
1121
+ Logs `values` to the current run.
1122
+
1123
+ Args:
1124
+ data : Dict[str, DataType]
1125
+ Data must be a dict. The key must be a string with 0-9, a-z, A-Z, " ", "_", "-", "/". The value must be a
1126
+ `float`, `float convertible object`, `int` or `swanlab.data.BaseType`.
1127
+ step : int, optional
1128
+ The step number of the current data, if not provided, it will be automatically incremented.
1129
+ If step is duplicated, the data will be ignored.
1130
+ kwargs:
1131
+ Additional key word arguments passed along to the `swanlab.log` method. Likes:
1132
+ print_to_console : bool, optional
1133
+ Whether to print the data to the console, the default is False.
1134
+ """
1135
+ self.run.log(values, step=step, **kwargs)
1136
+ logger.debug("Successfully logged to SwanLab")
1137
+
1138
+ @on_main_process
1139
+ def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
1140
+ """
1141
+ Logs `images` to the current run.
1142
+
1143
+ Args:
1144
+ values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
1145
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
1146
+ step (`int`, *optional*):
1147
+ The run step. If included, the log will be affiliated with this step.
1148
+ kwargs:
1149
+ Additional key word arguments passed along to the `swanlab.log` method. Likes:
1150
+ print_to_console : bool, optional
1151
+ Whether to print the data to the console, the default is False.
1152
+ """
1153
+ import swanlab
1154
+
1155
+ for k, v in values.items():
1156
+ self.log({k: [swanlab.Image(image) for image in v]}, step=step, **kwargs)
1157
+ logger.debug("Successfully logged images to SwanLab")
1158
+
1159
+ @on_main_process
1160
+ def finish(self):
1161
+ """
1162
+ Closes `swanlab` writer
1163
+ """
1164
+ self.run.finish()
1165
+ logger.debug("SwanLab run closed")
1166
+
1167
+
1168
+ LOGGER_TYPE_TO_CLASS = {
1169
+ "aim": AimTracker,
1170
+ "comet_ml": CometMLTracker,
1171
+ "mlflow": MLflowTracker,
1172
+ "tensorboard": TensorBoardTracker,
1173
+ "wandb": WandBTracker,
1174
+ "clearml": ClearMLTracker,
1175
+ "dvclive": DVCLiveTracker,
1176
+ "swanlab": SwanLabTracker,
1177
+ }
1178
+
1179
+
1180
+ def filter_trackers(
1181
+ log_with: list[Union[str, LoggerType, GeneralTracker]],
1182
+ logging_dir: Union[str, os.PathLike] = None,
1183
+ ):
1184
+ """
1185
+ Takes in a list of potential tracker types and checks that:
1186
+ - The tracker wanted is available in that environment
1187
+ - Filters out repeats of tracker types
1188
+ - If `all` is in `log_with`, will return all trackers in the environment
1189
+ - If a tracker requires a `logging_dir`, ensures that `logging_dir` is not `None`
1190
+
1191
+ Args:
1192
+ log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*):
1193
+ A list of loggers to be setup for experiment tracking. Should be one or several of:
1194
+
1195
+ - `"all"`
1196
+ - `"tensorboard"`
1197
+ - `"wandb"`
1198
+ - `"comet_ml"`
1199
+ - `"mlflow"`
1200
+ - `"dvclive"`
1201
+ - `"swanlab"`
1202
+ If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can
1203
+ also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`.
1204
+ logging_dir (`str`, `os.PathLike`, *optional*):
1205
+ A path to a directory for storing logs of locally-compatible loggers.
1206
+ """
1207
+ loggers = []
1208
+ if log_with is not None:
1209
+ if not isinstance(log_with, (list, tuple)):
1210
+ log_with = [log_with]
1211
+ if "all" in log_with or LoggerType.ALL in log_with:
1212
+ loggers = [o for o in log_with if issubclass(type(o), GeneralTracker)] + get_available_trackers()
1213
+ else:
1214
+ for log_type in log_with:
1215
+ if log_type not in LoggerType and not issubclass(type(log_type), GeneralTracker):
1216
+ raise ValueError(f"Unsupported logging capability: {log_type}. Choose between {LoggerType.list()}")
1217
+ if issubclass(type(log_type), GeneralTracker):
1218
+ loggers.append(log_type)
1219
+ else:
1220
+ log_type = LoggerType(log_type)
1221
+ if log_type not in loggers:
1222
+ if log_type in get_available_trackers():
1223
+ tracker_init = LOGGER_TYPE_TO_CLASS[str(log_type)]
1224
+ if tracker_init.requires_logging_directory:
1225
+ if logging_dir is None:
1226
+ raise ValueError(
1227
+ f"Logging with `{log_type}` requires a `logging_dir` to be passed in."
1228
+ )
1229
+ loggers.append(log_type)
1230
+ else:
1231
+ logger.debug(f"Tried adding logger {log_type}, but package is unavailable in the system.")
1232
+
1233
+ return loggers
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014 Mats Julian Olsen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/METADATA ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: addict
3
+ Version: 2.4.0
4
+ Summary: Addict is a dictionary whose items can be set using both attribute and item syntax.
5
+ Home-page: https://github.com/mewwts/addict
6
+ Author: Mats Julian Olsen
7
+ Author-email: mats@plysjbyen.net
8
+ License: UNKNOWN
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 2.7
12
+ Classifier: Programming Language :: Python :: 3.6
13
+ Classifier: Programming Language :: Python :: 3.7
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+
21
+ Addict is a module that exposes a dictionary subclass that allows items to be set like attributes. Values are gettable and settable using both attribute and item syntax. For more info check out the README at 'github.com/mewwts/addict'.
22
+
23
+
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/RECORD ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ addict-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ addict-2.4.0.dist-info/LICENSE,sha256=ykiNM8US0LImFCCQr5DomuJmqQGik_if1kLf7JMeIsE,1085
3
+ addict-2.4.0.dist-info/METADATA,sha256=ZjIJZ5lvhfohHxIWp79fkh0TtBsN5duX84na3bxU6vQ,1028
4
+ addict-2.4.0.dist-info/RECORD,,
5
+ addict-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ addict-2.4.0.dist-info/WHEEL,sha256=EVRjI69F5qVjm_YgqcTXPnTAv3BfSUr0WVAHuSP3Xoo,92
7
+ addict-2.4.0.dist-info/top_level.txt,sha256=GGfQKsz1N-bSRYzNpyp8GY8uAEqh3SWaXRbAnBUKjHA,7
8
+ addict/__init__.py,sha256=xmlNiYYVoAD3_FfmgfOM2cc3wI17GSgsMBODbFRs_mY,233
9
+ addict/__pycache__/__init__.cpython-312.pyc,,
10
+ addict/__pycache__/addict.cpython-312.pyc,,
11
+ addict/addict.py,sha256=ScOfclaAM7ugyZoXOW2HHL9gCXt_XPe-i5bTLiY8ufU,4901
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/REQUESTED ADDED
File without changes
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.35.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python_embeded/Lib/site-packages/addict-2.4.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ addict
python_embeded/Lib/site-packages/addict/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .addict import Dict
2
+ from .addict import Dict as Addict
3
+
4
+
5
+ __title__ = 'addict'
6
+ __version__ = '2.4.0'
7
+ __author__ = 'Mats Julian Olsen'
8
+ __license__ = 'MIT'
9
+ __copyright__ = 'Copyright 2014-2020 Mats Julian Olsen'
10
+ __all__ = ['Dict']
python_embeded/Lib/site-packages/addict/addict.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+
4
+ class Dict(dict):
5
+
6
+ def __init__(__self, *args, **kwargs):
7
+ object.__setattr__(__self, '__parent', kwargs.pop('__parent', None))
8
+ object.__setattr__(__self, '__key', kwargs.pop('__key', None))
9
+ object.__setattr__(__self, '__frozen', False)
10
+ for arg in args:
11
+ if not arg:
12
+ continue
13
+ elif isinstance(arg, dict):
14
+ for key, val in arg.items():
15
+ __self[key] = __self._hook(val)
16
+ elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)):
17
+ __self[arg[0]] = __self._hook(arg[1])
18
+ else:
19
+ for key, val in iter(arg):
20
+ __self[key] = __self._hook(val)
21
+
22
+ for key, val in kwargs.items():
23
+ __self[key] = __self._hook(val)
24
+
25
+ def __setattr__(self, name, value):
26
+ if hasattr(self.__class__, name):
27
+ raise AttributeError("'Dict' object attribute "
28
+ "'{0}' is read-only".format(name))
29
+ else:
30
+ self[name] = value
31
+
32
+ def __setitem__(self, name, value):
33
+ isFrozen = (hasattr(self, '__frozen') and
34
+ object.__getattribute__(self, '__frozen'))
35
+ if isFrozen and name not in super(Dict, self).keys():
36
+ raise KeyError(name)
37
+ super(Dict, self).__setitem__(name, value)
38
+ try:
39
+ p = object.__getattribute__(self, '__parent')
40
+ key = object.__getattribute__(self, '__key')
41
+ except AttributeError:
42
+ p = None
43
+ key = None
44
+ if p is not None:
45
+ p[key] = self
46
+ object.__delattr__(self, '__parent')
47
+ object.__delattr__(self, '__key')
48
+
49
+ def __add__(self, other):
50
+ if not self.keys():
51
+ return other
52
+ else:
53
+ self_type = type(self).__name__
54
+ other_type = type(other).__name__
55
+ msg = "unsupported operand type(s) for +: '{}' and '{}'"
56
+ raise TypeError(msg.format(self_type, other_type))
57
+
58
+ @classmethod
59
+ def _hook(cls, item):
60
+ if isinstance(item, dict):
61
+ return cls(item)
62
+ elif isinstance(item, (list, tuple)):
63
+ return type(item)(cls._hook(elem) for elem in item)
64
+ return item
65
+
66
+ def __getattr__(self, item):
67
+ return self.__getitem__(item)
68
+
69
+ def __missing__(self, name):
70
+ if object.__getattribute__(self, '__frozen'):
71
+ raise KeyError(name)
72
+ return self.__class__(__parent=self, __key=name)
73
+
74
+ def __delattr__(self, name):
75
+ del self[name]
76
+
77
+ def to_dict(self):
78
+ base = {}
79
+ for key, value in self.items():
80
+ if isinstance(value, type(self)):
81
+ base[key] = value.to_dict()
82
+ elif isinstance(value, (list, tuple)):
83
+ base[key] = type(value)(
84
+ item.to_dict() if isinstance(item, type(self)) else
85
+ item for item in value)
86
+ else:
87
+ base[key] = value
88
+ return base
89
+
90
+ def copy(self):
91
+ return copy.copy(self)
92
+
93
+ def deepcopy(self):
94
+ return copy.deepcopy(self)
95
+
96
+ def __deepcopy__(self, memo):
97
+ other = self.__class__()
98
+ memo[id(self)] = other
99
+ for key, value in self.items():
100
+ other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo)
101
+ return other
102
+
103
+ def update(self, *args, **kwargs):
104
+ other = {}
105
+ if args:
106
+ if len(args) > 1:
107
+ raise TypeError()
108
+ other.update(args[0])
109
+ other.update(kwargs)
110
+ for k, v in other.items():
111
+ if ((k not in self) or
112
+ (not isinstance(self[k], dict)) or
113
+ (not isinstance(v, dict))):
114
+ self[k] = v
115
+ else:
116
+ self[k].update(v)
117
+
118
+ def __getnewargs__(self):
119
+ return tuple(self.items())
120
+
121
+ def __getstate__(self):
122
+ return self
123
+
124
+ def __setstate__(self, state):
125
+ self.update(state)
126
+
127
+ def __or__(self, other):
128
+ if not isinstance(other, (Dict, dict)):
129
+ return NotImplemented
130
+ new = Dict(self)
131
+ new.update(other)
132
+ return new
133
+
134
+ def __ror__(self, other):
135
+ if not isinstance(other, (Dict, dict)):
136
+ return NotImplemented
137
+ new = Dict(other)
138
+ new.update(self)
139
+ return new
140
+
141
+ def __ior__(self, other):
142
+ self.update(other)
143
+ return self
144
+
145
+ def setdefault(self, key, default=None):
146
+ if key in self:
147
+ return self[key]
148
+ else:
149
+ self[key] = default
150
+ return default
151
+
152
+ def freeze(self, shouldFreeze=True):
153
+ object.__setattr__(self, '__frozen', shouldFreeze)
154
+ for key, val in self.items():
155
+ if isinstance(val, Dict):
156
+ val.freeze(shouldFreeze)
157
+
158
+ def unfreeze(self):
159
+ self.freeze(False)
python_embeded/Lib/site-packages/adodbapi/__init__.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # nopycln: file # undecidable cases due to explicit re-exports https://github.com/hadialqattan/pycln/issues/205
2
+ """adodbapi - A python DB API 2.0 (PEP 249) interface to Microsoft ADO
3
+
4
+ Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole
5
+ * https://sourceforge.net/projects/adodbapi
6
+ """
7
+
8
+ import time
9
+
10
+ # Re-exports to keep backward compatibility with existing code
11
+ from .adodbapi import (
12
+ Connection as Connection,
13
+ Cursor as Cursor,
14
+ __version__,
15
+ connect as connect,
16
+ dateconverter,
17
+ )
18
+ from .apibase import (
19
+ BINARY as BINARY,
20
+ DATETIME as DATETIME,
21
+ NUMBER as NUMBER,
22
+ ROWID as ROWID,
23
+ STRING as STRING,
24
+ DatabaseError as DatabaseError,
25
+ DataError as DataError,
26
+ Error as Error,
27
+ FetchFailedError as FetchFailedError,
28
+ IntegrityError as IntegrityError,
29
+ InterfaceError as InterfaceError,
30
+ InternalError as InternalError,
31
+ NotSupportedError as NotSupportedError,
32
+ OperationalError as OperationalError,
33
+ ProgrammingError as ProgrammingError,
34
+ Warning as Warning,
35
+ apilevel as apilevel,
36
+ paramstyle as paramstyle,
37
+ threadsafety as threadsafety,
38
+ )
39
+
40
+
41
+ def Binary(aString):
42
+ """This function constructs an object capable of holding a binary (long) string value."""
43
+ return bytes(aString)
44
+
45
+
46
+ def Date(year, month, day):
47
+ "This function constructs an object holding a date value."
48
+ return dateconverter.Date(year, month, day)
49
+
50
+
51
+ def Time(hour, minute, second):
52
+ "This function constructs an object holding a time value."
53
+ return dateconverter.Time(hour, minute, second)
54
+
55
+
56
+ def Timestamp(year, month, day, hour, minute, second):
57
+ "This function constructs an object holding a time stamp value."
58
+ return dateconverter.Timestamp(year, month, day, hour, minute, second)
59
+
60
+
61
+ def DateFromTicks(ticks):
62
+ """This function constructs an object holding a date value from the given ticks value
63
+ (number of seconds since the epoch; see the documentation of the standard Python time module for details).
64
+ """
65
+ return Date(*time.gmtime(ticks)[:3])
66
+
67
+
68
+ def TimeFromTicks(ticks):
69
+ """This function constructs an object holding a time value from the given ticks value
70
+ (number of seconds since the epoch; see the documentation of the standard Python time module for details).
71
+ """
72
+ return Time(*time.gmtime(ticks)[3:6])
73
+
74
+
75
+ def TimestampFromTicks(ticks):
76
+ """This function constructs an object holding a time stamp value from the given
77
+ ticks value (number of seconds since the epoch;
78
+ see the documentation of the standard Python time module for details)."""
79
+ return Timestamp(*time.gmtime(ticks)[:6])
80
+
81
+
82
+ version = "adodbapi v" + __version__
python_embeded/Lib/site-packages/adodbapi/ado_consts.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ADO enumerated constants documented on MSDN:
2
+ # https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/ado-enumerated-constants
3
+ # TODO: Update to https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/ado-enumerated-constants
4
+
5
+ # IsolationLevelEnum
6
+ adXactUnspecified = -1
7
+ adXactBrowse = 0x100
8
+ adXactChaos = 0x10
9
+ adXactCursorStability = 0x1000
10
+ adXactIsolated = 0x100000
11
+ adXactReadCommitted = 0x1000
12
+ adXactReadUncommitted = 0x100
13
+ adXactRepeatableRead = 0x10000
14
+ adXactSerializable = 0x100000
15
+
16
+ # CursorLocationEnum
17
+ adUseClient = 3
18
+ adUseServer = 2
19
+
20
+ # CursorTypeEnum
21
+ adOpenDynamic = 2
22
+ adOpenForwardOnly = 0
23
+ adOpenKeyset = 1
24
+ adOpenStatic = 3
25
+ adOpenUnspecified = -1
26
+
27
+ # CommandTypeEnum
28
+ adCmdText = 1
29
+ adCmdStoredProc = 4
30
+ adSchemaTables = 20
31
+
32
+ # ParameterDirectionEnum
33
+ adParamInput = 1
34
+ adParamInputOutput = 3
35
+ adParamOutput = 2
36
+ adParamReturnValue = 4
37
+ adParamUnknown = 0
38
+ directions = {
39
+ 0: "Unknown",
40
+ 1: "Input",
41
+ 2: "Output",
42
+ 3: "InputOutput",
43
+ 4: "Return",
44
+ }
45
+
46
+
47
+ def ado_direction_name(ado_dir):
48
+ try:
49
+ return "adParam" + directions[ado_dir]
50
+ except:
51
+ return f"unknown direction ({ado_dir})"
52
+
53
+
54
+ # ObjectStateEnum
55
+ adStateClosed = 0
56
+ adStateOpen = 1
57
+ adStateConnecting = 2
58
+ adStateExecuting = 4
59
+ adStateFetching = 8
60
+
61
+ # FieldAttributeEnum
62
+ adFldMayBeNull = 0x40
63
+
64
+ # ConnectModeEnum
65
+ adModeUnknown = 0
66
+ adModeRead = 1
67
+ adModeWrite = 2
68
+ adModeReadWrite = 3
69
+ adModeShareDenyRead = 4
70
+ adModeShareDenyWrite = 8
71
+ adModeShareExclusive = 12
72
+ adModeShareDenyNone = 16
73
+ adModeRecursive = 0x400000
74
+
75
+ # XactAttributeEnum
76
+ adXactCommitRetaining = 131072
77
+ adXactAbortRetaining = 262144
78
+
79
+ ado_error_TIMEOUT = -2147217871
80
+
81
+ # DataTypeEnum - ADO Data types documented at:
82
+ # http://msdn2.microsoft.com/en-us/library/ms675318.aspx
83
+ # TODO: Update to https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/datatypeenum
84
+ adArray = 0x2000
85
+ adEmpty = 0x0
86
+ adBSTR = 0x8
87
+ adBigInt = 0x14
88
+ adBinary = 0x80
89
+ adBoolean = 0xB
90
+ adChapter = 0x88
91
+ adChar = 0x81
92
+ adCurrency = 0x6
93
+ adDBDate = 0x85
94
+ adDBTime = 0x86
95
+ adDBTimeStamp = 0x87
96
+ adDate = 0x7
97
+ adDecimal = 0xE
98
+ adDouble = 0x5
99
+ adError = 0xA
100
+ adFileTime = 0x40
101
+ adGUID = 0x48
102
+ adIDispatch = 0x9
103
+ adIUnknown = 0xD
104
+ adInteger = 0x3
105
+ adLongVarBinary = 0xCD
106
+ adLongVarChar = 0xC9
107
+ adLongVarWChar = 0xCB
108
+ adNumeric = 0x83
109
+ adPropVariant = 0x8A
110
+ adSingle = 0x4
111
+ adSmallInt = 0x2
112
+ adTinyInt = 0x10
113
+ adUnsignedBigInt = 0x15
114
+ adUnsignedInt = 0x13
115
+ adUnsignedSmallInt = 0x12
116
+ adUnsignedTinyInt = 0x11
117
+ adUserDefined = 0x84
118
+ adVarBinary = 0xCC
119
+ adVarChar = 0xC8
120
+ adVarNumeric = 0x8B
121
+ adVarWChar = 0xCA
122
+ adVariant = 0xC
123
+ adWChar = 0x82
124
+ # Additional constants used by introspection but not ADO itself
125
+ AUTO_FIELD_MARKER = -1000
126
+
127
+ adTypeNames = {
128
+ adBSTR: "adBSTR",
129
+ adBigInt: "adBigInt",
130
+ adBinary: "adBinary",
131
+ adBoolean: "adBoolean",
132
+ adChapter: "adChapter",
133
+ adChar: "adChar",
134
+ adCurrency: "adCurrency",
135
+ adDBDate: "adDBDate",
136
+ adDBTime: "adDBTime",
137
+ adDBTimeStamp: "adDBTimeStamp",
138
+ adDate: "adDate",
139
+ adDecimal: "adDecimal",
140
+ adDouble: "adDouble",
141
+ adEmpty: "adEmpty",
142
+ adError: "adError",
143
+ adFileTime: "adFileTime",
144
+ adGUID: "adGUID",
145
+ adIDispatch: "adIDispatch",
146
+ adIUnknown: "adIUnknown",
147
+ adInteger: "adInteger",
148
+ adLongVarBinary: "adLongVarBinary",
149
+ adLongVarChar: "adLongVarChar",
150
+ adLongVarWChar: "adLongVarWChar",
151
+ adNumeric: "adNumeric",
152
+ adPropVariant: "adPropVariant",
153
+ adSingle: "adSingle",
154
+ adSmallInt: "adSmallInt",
155
+ adTinyInt: "adTinyInt",
156
+ adUnsignedBigInt: "adUnsignedBigInt",
157
+ adUnsignedInt: "adUnsignedInt",
158
+ adUnsignedSmallInt: "adUnsignedSmallInt",
159
+ adUnsignedTinyInt: "adUnsignedTinyInt",
160
+ adUserDefined: "adUserDefined",
161
+ adVarBinary: "adVarBinary",
162
+ adVarChar: "adVarChar",
163
+ adVarNumeric: "adVarNumeric",
164
+ adVarWChar: "adVarWChar",
165
+ adVariant: "adVariant",
166
+ adWChar: "adWChar",
167
+ }
168
+
169
+
170
+ def ado_type_name(ado_type):
171
+ return adTypeNames.get(ado_type, f"unknown type ({ado_type})")
172
+
173
+
174
+ # here in decimal, sorted by value
175
+ # adEmpty 0 Specifies no value (DBTYPE_EMPTY).
176
+ # adSmallInt 2 Indicates a two-byte signed integer (DBTYPE_I2).
177
+ # adInteger 3 Indicates a four-byte signed integer (DBTYPE_I4).
178
+ # adSingle 4 Indicates a single-precision floating-point value (DBTYPE_R4).
179
+ # adDouble 5 Indicates a double-precision floating-point value (DBTYPE_R8).
180
+ # adCurrency 6 Indicates a currency value (DBTYPE_CY). Currency is a fixed-point number
181
+ # with four digits to the right of the decimal point. It is stored in an eight-byte signed integer scaled by 10,000.
182
+ # adDate 7 Indicates a date value (DBTYPE_DATE). A date is stored as a double, the whole part of which is
183
+ # the number of days since December 30, 1899, and the fractional part of which is the fraction of a day.
184
+ # adBSTR 8 Indicates a null-terminated character string (Unicode) (DBTYPE_BSTR).
185
+ # adIDispatch 9 Indicates a pointer to an IDispatch interface on a COM object (DBTYPE_IDISPATCH).
186
+ # adError 10 Indicates a 32-bit error code (DBTYPE_ERROR).
187
+ # adBoolean 11 Indicates a boolean value (DBTYPE_BOOL).
188
+ # adVariant 12 Indicates an Automation Variant (DBTYPE_VARIANT).
189
+ # adIUnknown 13 Indicates a pointer to an IUnknown interface on a COM object (DBTYPE_IUNKNOWN).
190
+ # adDecimal 14 Indicates an exact numeric value with a fixed precision and scale (DBTYPE_DECIMAL).
191
+ # adTinyInt 16 Indicates a one-byte signed integer (DBTYPE_I1).
192
+ # adUnsignedTinyInt 17 Indicates a one-byte unsigned integer (DBTYPE_UI1).
193
+ # adUnsignedSmallInt 18 Indicates a two-byte unsigned integer (DBTYPE_UI2).
194
+ # adUnsignedInt 19 Indicates a four-byte unsigned integer (DBTYPE_UI4).
195
+ # adBigInt 20 Indicates an eight-byte signed integer (DBTYPE_I8).
196
+ # adUnsignedBigInt 21 Indicates an eight-byte unsigned integer (DBTYPE_UI8).
197
+ # adFileTime 64 Indicates a 64-bit value representing the number of 100-nanosecond intervals since
198
+ # January 1, 1601 (DBTYPE_FILETIME).
199
+ # adGUID 72 Indicates a globally unique identifier (GUID) (DBTYPE_GUID).
200
+ # adBinary 128 Indicates a binary value (DBTYPE_BYTES).
201
+ # adChar 129 Indicates a string value (DBTYPE_STR).
202
+ # adWChar 130 Indicates a null-terminated Unicode character string (DBTYPE_WSTR).
203
+ # adNumeric 131 Indicates an exact numeric value with a fixed precision and scale (DBTYPE_NUMERIC).
204
+ # adUserDefined 132 Indicates a user-defined variable (DBTYPE_UDT).
205
+ # adUserDefined 132 Indicates a user-defined variable (DBTYPE_UDT).
206
+ # adDBDate 133 Indicates a date value (yyyymmdd) (DBTYPE_DBDATE).
207
+ # adDBTime 134 Indicates a time value (hhmmss) (DBTYPE_DBTIME).
208
+ # adDBTimeStamp 135 Indicates a date/time stamp (yyyymmddhhmmss plus a fraction in billionths) (DBTYPE_DBTIMESTAMP).
209
+ # adChapter 136 Indicates a four-byte chapter value that identifies rows in a child rowset (DBTYPE_HCHAPTER).
210
+ # adPropVariant 138 Indicates an Automation PROPVARIANT (DBTYPE_PROP_VARIANT).
211
+ # adVarNumeric 139 Indicates a numeric value (Parameter object only).
212
+ # adVarChar 200 Indicates a string value (Parameter object only).
213
+ # adLongVarChar 201 Indicates a long string value (Parameter object only).
214
+ # adVarWChar 202 Indicates a null-terminated Unicode character string (Parameter object only).
215
+ # adLongVarWChar 203 Indicates a long null-terminated Unicode string value (Parameter object only).
216
+ # adVarBinary 204 Indicates a binary value (Parameter object only).
217
+ # adLongVarBinary 205 Indicates a long binary value (Parameter object only).
218
+ # adArray (Does not apply to ADOX.) 0x2000 A flag value, always combined with another data type constant,
219
+ # that indicates an array of that other data type.
220
+
221
+ # Error codes to names
222
+ adoErrors = {
223
+ 0xE7B: "adErrBoundToCommand",
224
+ 0xE94: "adErrCannotComplete",
225
+ 0xEA4: "adErrCantChangeConnection",
226
+ 0xC94: "adErrCantChangeProvider",
227
+ 0xE8C: "adErrCantConvertvalue",
228
+ 0xE8D: "adErrCantCreate",
229
+ 0xEA3: "adErrCatalogNotSet",
230
+ 0xE8E: "adErrColumnNotOnThisRow",
231
+ 0xD5D: "adErrDataConversion",
232
+ 0xE89: "adErrDataOverflow",
233
+ 0xE9A: "adErrDelResOutOfScope",
234
+ 0xEA6: "adErrDenyNotSupported",
235
+ 0xEA7: "adErrDenyTypeNotSupported",
236
+ 0xCB3: "adErrFeatureNotAvailable",
237
+ 0xEA5: "adErrFieldsUpdateFailed",
238
+ 0xC93: "adErrIllegalOperation",
239
+ 0xCAE: "adErrInTransaction",
240
+ 0xE87: "adErrIntegrityViolation",
241
+ 0xBB9: "adErrInvalidArgument",
242
+ 0xE7D: "adErrInvalidConnection",
243
+ 0xE7C: "adErrInvalidParamInfo",
244
+ 0xE82: "adErrInvalidTransaction",
245
+ 0xE91: "adErrInvalidURL",
246
+ 0xCC1: "adErrItemNotFound",
247
+ 0xBCD: "adErrNoCurrentRecord",
248
+ 0xE83: "adErrNotExecuting",
249
+ 0xE7E: "adErrNotReentrant",
250
+ 0xE78: "adErrObjectClosed",
251
+ 0xD27: "adErrObjectInCollection",
252
+ 0xD5C: "adErrObjectNotSet",
253
+ 0xE79: "adErrObjectOpen",
254
+ 0xBBA: "adErrOpeningFile",
255
+ 0xE80: "adErrOperationCancelled",
256
+ 0xE96: "adErrOutOfSpace",
257
+ 0xE88: "adErrPermissionDenied",
258
+ 0xE9E: "adErrPropConflicting",
259
+ 0xE9B: "adErrPropInvalidColumn",
260
+ 0xE9C: "adErrPropInvalidOption",
261
+ 0xE9D: "adErrPropInvalidValue",
262
+ 0xE9F: "adErrPropNotAllSettable",
263
+ 0xEA0: "adErrPropNotSet",
264
+ 0xEA1: "adErrPropNotSettable",
265
+ 0xEA2: "adErrPropNotSupported",
266
+ 0xBB8: "adErrProviderFailed",
267
+ 0xE7A: "adErrProviderNotFound",
268
+ 0xBBB: "adErrReadFile",
269
+ 0xE93: "adErrResourceExists",
270
+ 0xE92: "adErrResourceLocked",
271
+ 0xE97: "adErrResourceOutOfScope",
272
+ 0xE8A: "adErrSchemaViolation",
273
+ 0xE8B: "adErrSignMismatch",
274
+ 0xE81: "adErrStillConnecting",
275
+ 0xE7F: "adErrStillExecuting",
276
+ 0xE90: "adErrTreePermissionDenied",
277
+ 0xE8F: "adErrURLDoesNotExist",
278
+ 0xE99: "adErrURLNamedRowDoesNotExist",
279
+ 0xE98: "adErrUnavailable",
280
+ 0xE84: "adErrUnsafeOperation",
281
+ 0xE95: "adErrVolumeNotFound",
282
+ 0xBBC: "adErrWriteFile",
283
+ }
python_embeded/Lib/site-packages/adodbapi/adodbapi.py ADDED
@@ -0,0 +1,1153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """adodbapi - A python DB API 2.0 (PEP 249) interface to Microsoft ADO
2
+
3
+ Copyright (C) 2002 Henrik Ekelund, versions 2.1 and later by Vernon Cole
4
+ * https://sourceforge.net/projects/pywin32
5
+ * https://github.com/mhammond/pywin32
6
+ * https://sourceforge.net/projects/adodbapi
7
+
8
+ This library is free software; you can redistribute it and/or
9
+ modify it under the terms of the GNU Lesser General Public
10
+ License as published by the Free Software Foundation; either
11
+ version 2.1 of the License, or (at your option) any later version.
12
+
13
+ This library is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ Lesser General Public License for more details.
17
+
18
+ You should have received a copy of the GNU Lesser General Public
19
+ License along with this library; if not, write to the Free Software
20
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
+
22
+ django adaptations and refactoring by Adam Vandenberg
23
+
24
+ DB-API 2.0 specification: https://peps.python.org/pep-0249/
25
+
26
+ This module source should run correctly in CPython versions 2.7 and later,
27
+ or CPython 3.4 or later.
28
+ """
29
+
30
+ __version__ = "2.6.2.0"
31
+ version = "adodbapi v" + __version__
32
+
33
+ import copy
34
+ import decimal
35
+ import os
36
+ import sys
37
+ import weakref
38
+
39
+ from . import ado_consts as adc, apibase as api, process_connect_string
40
+
41
+ try:
42
+ verbose = int(os.environ["ADODBAPI_VERBOSE"])
43
+ except:
44
+ verbose = False
45
+ if verbose:
46
+ print(version)
47
+
48
+ try:
49
+ import pythoncom
50
+ import pywintypes
51
+ from win32com.client import Dispatch
52
+ except ImportError:
53
+ import warnings
54
+
55
+ warnings.warn("pywin32 package required for adodbapi.", ImportWarning)
56
+
57
+
58
+ def getIndexedValue(obj, index):
59
+ return obj(index)
60
+
61
+
62
+ from collections.abc import Mapping
63
+
64
+
65
+ # ----------------- The .connect method -----------------
66
+ def make_COM_connecter():
67
+ try:
68
+ pythoncom.CoInitialize() # v2.1 Paj
69
+ c = Dispatch("ADODB.Connection") # connect _after_ CoInitialize v2.1.1 adamvan
70
+ except:
71
+ raise api.InterfaceError(
72
+ "Windows COM Error: Dispatch('ADODB.Connection') failed."
73
+ )
74
+ return c
75
+
76
+
77
+ def connect(*args, **kwargs): # --> a db-api connection object
78
+ """Connect to a database.
79
+
80
+ call using:
81
+ :connection_string -- An ADODB formatted connection string, see:
82
+ * https://www.connectionstrings.com
83
+ * https://www.codeguru.com/dotnet/whats-in-an-ado-connection-string/
84
+ * https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings
85
+ :timeout -- A command timeout value, in seconds (default 30 seconds)
86
+ """
87
+ co = Connection() # make an empty connection object
88
+
89
+ kwargs = process_connect_string.process(args, kwargs, True)
90
+
91
+ try: # connect to the database, using the connection information in kwargs
92
+ co.connect(kwargs)
93
+ return co
94
+ except Exception as e:
95
+ message = 'Error opening connection to "%s"' % co.connection_string
96
+ raise api.OperationalError(e, message)
97
+
98
+
99
+ # so you could use something like:
100
+ # myConnection.paramstyle = 'named'
101
+ # The programmer may also change the default.
102
+ # For example, if I were using django, I would say:
103
+ # import adodbapi as Database
104
+ # Database.adodbapi.paramstyle = 'format'
105
+
106
+ # ------- other module level defaults --------
107
+ defaultIsolationLevel = adc.adXactReadCommitted
108
+ # Set defaultIsolationLevel on module level before creating the connection.
109
+ # For example:
110
+ # import adodbapi, ado_consts
111
+ # adodbapi.adodbapi.defaultIsolationLevel=ado_consts.adXactBrowse"
112
+ #
113
+ # Set defaultCursorLocation on module level before creating the connection.
114
+ # It may be one of the "adUse..." consts.
115
+ defaultCursorLocation = adc.adUseClient # changed from adUseServer as of v 2.3.0
116
+
117
+ dateconverter = api.pythonDateTimeConverter() # default
118
+
119
+
120
+ def format_parameters(ADOparameters, show_value=False):
121
+ """Format a collection of ADO Command Parameters.
122
+
123
+ Used by error reporting in _execute_command.
124
+ """
125
+ try:
126
+ if show_value:
127
+ desc = [
128
+ 'Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %s'
129
+ % (
130
+ p.Name,
131
+ adc.directions[p.Direction],
132
+ adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
133
+ p.Size,
134
+ p.Value,
135
+ p.Precision,
136
+ p.NumericScale,
137
+ )
138
+ for p in ADOparameters
139
+ ]
140
+ else:
141
+ desc = [
142
+ "Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s"
143
+ % (
144
+ p.Name,
145
+ adc.directions[p.Direction],
146
+ adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
147
+ p.Size,
148
+ p.Precision,
149
+ p.NumericScale,
150
+ )
151
+ for p in ADOparameters
152
+ ]
153
+ return "[" + "\n".join(desc) + "]"
154
+ except:
155
+ return "[]"
156
+
157
+
158
+ def _configure_parameter(p, value, adotype, settings_known):
159
+ """Configure the given ADO Parameter 'p' with the Python 'value'."""
160
+
161
+ if adotype in api.adoBinaryTypes:
162
+ p.Size = len(value)
163
+ p.AppendChunk(value)
164
+
165
+ elif isinstance(value, str): # v2.1 Jevon
166
+ length = len(value)
167
+ if adotype in api.adoStringTypes: # v2.2.1 Cole
168
+ if settings_known:
169
+ length = min(length, p.Size) # v2.1 Cole limit data to defined size
170
+ p.Value = value[:length] # v2.1 Jevon & v2.1 Cole
171
+ else:
172
+ p.Value = value # don't limit if db column is numeric
173
+ if length > 0: # v2.1 Cole something does not like p.Size as Zero
174
+ p.Size = length # v2.1 Jevon
175
+
176
+ elif isinstance(value, decimal.Decimal):
177
+ p.Value = value
178
+ exponent = value.as_tuple()[2]
179
+ digit_count = len(value.as_tuple()[1])
180
+ p.Precision = digit_count
181
+ if exponent == 0:
182
+ p.NumericScale = 0
183
+ elif exponent < 0:
184
+ p.NumericScale = -exponent
185
+ if p.Precision < p.NumericScale:
186
+ p.Precision = p.NumericScale
187
+ else: # exponent > 0:
188
+ p.NumericScale = 0
189
+ p.Precision = digit_count + exponent
190
+
191
+ elif type(value) in dateconverter.types:
192
+ if settings_known and adotype in api.adoDateTimeTypes:
193
+ p.Value = dateconverter.COMDate(value)
194
+ else: # probably a string
195
+ # provide the date as a string in the format 'YYYY-MM-dd'
196
+ s = dateconverter.DateObjectToIsoFormatString(value)
197
+ p.Value = s
198
+ p.Size = len(s)
199
+
200
+ elif adotype == adc.adEmpty: # ADO will not let you specify a null column
201
+ p.Type = (
202
+ adc.adInteger
203
+ ) # so we will fake it to be an integer (just to have something)
204
+ p.Value = None # and pass in a Null *value*
205
+
206
+ # For any other type, set the value and let pythoncom do the right thing.
207
+ else:
208
+ p.Value = value
209
+
210
+
211
+ # # # # # ----- the Class that defines a connection ----- # # # # #
212
+ class Connection:
213
+ # include connection attributes as class attributes required by api definition.
214
+ Warning = api.Warning
215
+ Error = api.Error
216
+ InterfaceError = api.InterfaceError
217
+ DataError = api.DataError
218
+ DatabaseError = api.DatabaseError
219
+ OperationalError = api.OperationalError
220
+ IntegrityError = api.IntegrityError
221
+ InternalError = api.InternalError
222
+ NotSupportedError = api.NotSupportedError
223
+ ProgrammingError = api.ProgrammingError
224
+ FetchFailedError = api.FetchFailedError # (special for django)
225
+ # ...class attributes... (can be overridden by instance attributes)
226
+ verbose = api.verbose
227
+
228
+ @property
229
+ def dbapi(self): # a proposed db-api version 3 extension.
230
+ "Return a reference to the DBAPI module for this Connection."
231
+ return api
232
+
233
+ def __init__(self): # now define the instance attributes
234
+ self.connector = None
235
+ self.paramstyle = api.paramstyle
236
+ self.supportsTransactions = False
237
+ self.connection_string = ""
238
+ self.cursors = weakref.WeakValueDictionary[int, Cursor]()
239
+ self.dbms_name = ""
240
+ self.dbms_version = ""
241
+ self.errorhandler = None # use the standard error handler for this instance
242
+ self.transaction_level = 0 # 0 == Not in a transaction, at the top level
243
+ self._autocommit = False
244
+
245
+ def connect(self, kwargs, connection_maker=make_COM_connecter):
246
+ if verbose > 9:
247
+ print(f"kwargs={kwargs!r}")
248
+ try:
249
+ self.connection_string = (
250
+ kwargs["connection_string"] % kwargs
251
+ ) # insert keyword arguments
252
+ except Exception as e:
253
+ self._raiseConnectionError(
254
+ KeyError, "Python string format error in connection string->"
255
+ )
256
+ self.timeout = kwargs.get("timeout", 30)
257
+ self.mode = kwargs.get("mode", adc.adModeUnknown)
258
+ self.kwargs = kwargs
259
+ if verbose:
260
+ print('%s attempting: "%s"' % (version, self.connection_string))
261
+ self.connector = connection_maker()
262
+ self.connector.ConnectionTimeout = self.timeout
263
+ self.connector.ConnectionString = self.connection_string
264
+ self.connector.Mode = self.mode
265
+
266
+ try:
267
+ self.connector.Open() # Open the ADO connection
268
+ except api.Error:
269
+ self._raiseConnectionError(
270
+ api.DatabaseError,
271
+ "ADO error trying to Open=%s" % self.connection_string,
272
+ )
273
+
274
+ try: # Stefan Fuchs; support WINCCOLEDBProvider
275
+ if getIndexedValue(self.connector.Properties, "Transaction DDL").Value != 0:
276
+ self.supportsTransactions = True
277
+ except pywintypes.com_error:
278
+ pass # Stefan Fuchs
279
+ self.dbms_name = getIndexedValue(self.connector.Properties, "DBMS Name").Value
280
+ try: # Stefan Fuchs
281
+ self.dbms_version = getIndexedValue(
282
+ self.connector.Properties, "DBMS Version"
283
+ ).Value
284
+ except pywintypes.com_error:
285
+ pass # Stefan Fuchs
286
+ self.connector.CursorLocation = defaultCursorLocation # v2.1 Rose
287
+ if self.supportsTransactions:
288
+ self.connector.IsolationLevel = defaultIsolationLevel
289
+ self._autocommit = bool(kwargs.get("autocommit", False))
290
+ if not self._autocommit:
291
+ self.transaction_level = (
292
+ self.connector.BeginTrans()
293
+ ) # Disables autocommit & inits transaction_level
294
+ else:
295
+ self._autocommit = True
296
+ if "paramstyle" in kwargs:
297
+ self.paramstyle = kwargs["paramstyle"] # let setattr do the error checking
298
+ self.messages = []
299
+ if verbose:
300
+ print("adodbapi New connection at %X" % id(self))
301
+
302
+ def _raiseConnectionError(self, errorclass, errorvalue):
303
+ eh = self.errorhandler
304
+ if eh is None:
305
+ eh = api.standardErrorHandler
306
+ eh(self, None, errorclass, errorvalue)
307
+
308
+ def _closeAdoConnection(self): # all v2.1 Rose
309
+ """close the underlying ADO Connection object,
310
+ rolling it back first if it supports transactions."""
311
+ if self.connector is None:
312
+ return
313
+ if not self._autocommit:
314
+ if self.transaction_level:
315
+ try:
316
+ self.connector.RollbackTrans()
317
+ except:
318
+ pass
319
+ self.connector.Close()
320
+ if verbose:
321
+ print("adodbapi Closed connection at %X" % id(self))
322
+
323
+ def close(self):
324
+ """Close the connection now (rather than whenever __del__ is called).
325
+
326
+ The connection will be unusable from this point forward;
327
+ an Error (or subclass) exception will be raised if any operation is attempted with the connection.
328
+ The same applies to all cursor objects trying to use the connection.
329
+ """
330
+ for crsr in list(self.cursors.values())[
331
+ :
332
+ ]: # copy the list, then close each one
333
+ crsr.close(dont_tell_me=True) # close without back-link clearing
334
+ self.messages = []
335
+ try:
336
+ self._closeAdoConnection() # v2.1 Rose
337
+ except Exception as e:
338
+ self._raiseConnectionError(sys.exc_info()[0], sys.exc_info()[1])
339
+
340
+ self.connector = None # v2.4.2.2 fix subtle timeout bug
341
+ # per M.Hammond: "I expect the benefits of uninitializing are probably fairly small,
342
+ # so never uninitializing will probably not cause any problems."
343
+
344
+ def commit(self):
345
+ """Commit any pending transaction to the database.
346
+
347
+ Note that if the database supports an auto-commit feature,
348
+ this must be initially off. An interface method may be provided to turn it back on.
349
+ Database modules that do not support transactions should implement this method with void functionality.
350
+ """
351
+ self.messages = []
352
+ if not self.supportsTransactions:
353
+ return
354
+
355
+ try:
356
+ self.transaction_level = self.connector.CommitTrans()
357
+ if verbose > 1:
358
+ print("commit done on connection at %X" % id(self))
359
+ if not (
360
+ self._autocommit
361
+ or (self.connector.Attributes & adc.adXactAbortRetaining)
362
+ ):
363
+ # If attributes has adXactCommitRetaining it performs retaining commits that is,
364
+ # calling CommitTrans automatically starts a new transaction. Not all providers support this.
365
+ # If not, we will have to start a new transaction by this command:
366
+ self.transaction_level = self.connector.BeginTrans()
367
+ except Exception as e:
368
+ self._raiseConnectionError(api.ProgrammingError, e)
369
+
370
+ def _rollback(self):
371
+ """In case a database does provide transactions this method causes the the database to roll back to
372
+ the start of any pending transaction. Closing a connection without committing the changes first will
373
+ cause an implicit rollback to be performed.
374
+
375
+ If the database does not support the functionality required by the method, the interface should
376
+ throw an exception in case the method is used.
377
+ The preferred approach is to not implement the method and thus have Python generate
378
+ an AttributeError in case the method is requested. This allows the programmer to check for database
379
+ capabilities using the standard hasattr() function.
380
+
381
+ For some dynamically configured interfaces it may not be appropriate to require dynamically making
382
+ the method available. These interfaces should then raise a NotSupportedError to indicate the
383
+ non-ability to perform the roll back when the method is invoked.
384
+ """
385
+ self.messages = []
386
+ if (
387
+ self.transaction_level
388
+ ): # trying to roll back with no open transaction causes an error
389
+ try:
390
+ self.transaction_level = self.connector.RollbackTrans()
391
+ if verbose > 1:
392
+ print("rollback done on connection at %X" % id(self))
393
+ if not self._autocommit and not (
394
+ self.connector.Attributes & adc.adXactAbortRetaining
395
+ ):
396
+ # If attributes has adXactAbortRetaining it performs retaining aborts that is,
397
+ # calling RollbackTrans automatically starts a new transaction. Not all providers support this.
398
+ # If not, we will have to start a new transaction by this command:
399
+ if not self.transaction_level:
400
+ self.transaction_level = self.connector.BeginTrans()
401
+ except Exception as e:
402
+ self._raiseConnectionError(api.ProgrammingError, e)
403
+
404
+ def __setattr__(self, name, value):
405
+ if name == "autocommit": # extension: allow user to turn autocommit on or off
406
+ if self.supportsTransactions:
407
+ object.__setattr__(self, "_autocommit", bool(value))
408
+ try:
409
+ self._rollback() # must clear any outstanding transactions
410
+ except:
411
+ pass
412
+ return
413
+ elif name == "paramstyle":
414
+ if value not in api.accepted_paramstyles:
415
+ self._raiseConnectionError(
416
+ api.NotSupportedError,
417
+ f"paramstyle={value!r} not in:{api.accepted_paramstyles!r}",
418
+ )
419
+ elif name == "variantConversions":
420
+ # make a new copy -- no changes in the default, please
421
+ value = copy.copy(value)
422
+ object.__setattr__(self, name, value)
423
+
424
+ def __getattr__(self, item):
425
+ if (
426
+ item == "rollback"
427
+ ): # the rollback method only appears if the database supports transactions
428
+ if self.supportsTransactions:
429
+ return (
430
+ self._rollback
431
+ ) # return the rollback method so the caller can execute it.
432
+ else:
433
+ raise AttributeError("this data provider does not support Rollback")
434
+ elif item == "autocommit":
435
+ return self._autocommit
436
+ else:
437
+ raise AttributeError(
438
+ 'no such attribute in ADO connection object as="%s"' % item
439
+ )
440
+
441
+ def cursor(self):
442
+ "Return a new Cursor Object using the connection."
443
+ self.messages = []
444
+ c = Cursor(self)
445
+ return c
446
+
447
+ def _i_am_here(self, crsr):
448
+ "message from a new cursor proclaiming its existence"
449
+ oid = id(crsr)
450
+ self.cursors[oid] = crsr
451
+
452
+ def _i_am_closing(self, crsr):
453
+ "message from a cursor giving connection a chance to clean up"
454
+ try:
455
+ del self.cursors[id(crsr)]
456
+ except:
457
+ pass
458
+
459
+ def printADOerrors(self):
460
+ j = self.connector.Errors.Count
461
+ if j:
462
+ print("ADO Errors:(%i)" % j)
463
+ for e in self.connector.Errors:
464
+ print("Description: %s" % e.Description)
465
+ print("Error: %s %s " % (e.Number, adc.adoErrors.get(e.Number, "unknown")))
466
+ if e.Number == adc.ado_error_TIMEOUT:
467
+ print(
468
+ "Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)"
469
+ )
470
+ print("Source: %s" % e.Source)
471
+ print("NativeError: %s" % e.NativeError)
472
+ print("SQL State: %s" % e.SQLState)
473
+
474
+ def _suggest_error_class(self):
475
+ """Introspect the current ADO Errors and determine an appropriate error class.
476
+
477
+ Error.SQLState is a SQL-defined error condition, per the SQL specification:
478
+ https://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt
479
+
480
+ The 23000 class of errors are integrity errors.
481
+ Error 40002 is a transactional integrity error.
482
+ """
483
+ if self.connector is not None:
484
+ for e in self.connector.Errors:
485
+ state = str(e.SQLState)
486
+ if state.startswith("23") or state == "40002":
487
+ return api.IntegrityError
488
+ return api.DatabaseError
489
+
490
+ def __del__(self):
491
+ try:
492
+ self._closeAdoConnection() # v2.1 Rose
493
+ except:
494
+ pass
495
+ self.connector = None
496
+
497
+ def __enter__(self): # Connections are context managers
498
+ return self
499
+
500
+ def __exit__(self, exc_type, exc_val, exc_tb):
501
+ if exc_type:
502
+ self._rollback() # automatic rollback on errors
503
+ else:
504
+ self.commit()
505
+
506
+ def get_table_names(self):
507
+ schema = self.connector.OpenSchema(20) # constant = adSchemaTables
508
+
509
+ tables = []
510
+ while not schema.EOF:
511
+ name = getIndexedValue(schema.Fields, "TABLE_NAME").Value
512
+ tables.append(name)
513
+ schema.MoveNext()
514
+ del schema
515
+ return tables
516
+
517
+
518
+ # # # # # ----- the Class that defines a cursor ----- # # # # #
519
+ class Cursor:
520
+ ## ** api required attributes:
521
+ ## description...
522
+ ## This read-only attribute is a sequence of 7-item sequences.
523
+ ## Each of these sequences contains information describing one result column:
524
+ ## (name, type_code, display_size, internal_size, precision, scale, null_ok).
525
+ ## This attribute will be None for operations that do not return rows or if the
526
+ ## cursor has not had an operation invoked via the executeXXX() method yet.
527
+ ## The type_code can be interpreted by comparing it to the Type Objects specified in the section below.
528
+ ## rowcount...
529
+ ## This read-only attribute specifies the number of rows that the last executeXXX() produced
530
+ ## (for DQL statements like select) or affected (for DML statements like update or insert).
531
+ ## The attribute is -1 in case no executeXXX() has been performed on the cursor or
532
+ ## the rowcount of the last operation is not determinable by the interface.[7]
533
+ ## arraysize...
534
+ ## This read/write attribute specifies the number of rows to fetch at a time with fetchmany().
535
+ ## It defaults to 1 meaning to fetch a single row at a time.
536
+ ## Implementations must observe this value with respect to the fetchmany() method,
537
+ ## but are free to interact with the database a single row at a time.
538
+ ## It may also be used in the implementation of executemany().
539
+ ## ** extension attributes:
540
+ ## paramstyle...
541
+ ## allows the programmer to override the connection's default paramstyle
542
+ ## errorhandler...
543
+ ## allows the programmer to override the connection's default error handler
544
+
545
+ def __init__(self, connection):
546
+ self.command = None
547
+ self._ado_prepared = False
548
+ self.messages = []
549
+ self.connection = connection
550
+ self.paramstyle = connection.paramstyle # used for overriding the paramstyle
551
+ self._parameter_names = []
552
+ self.recordset_is_remote = False
553
+ self.rs = None # the ADO recordset for this cursor
554
+ self.converters = [] # conversion function for each column
555
+ self.columnNames = {} # names of columns {lowercase name : number,...}
556
+ self.numberOfColumns = 0
557
+ self._description = None
558
+ self.rowcount = -1
559
+ self.errorhandler = connection.errorhandler
560
+ self.arraysize = 1
561
+ connection._i_am_here(self)
562
+ if verbose:
563
+ print(
564
+ "%s New cursor at %X on conn %X"
565
+ % (version, id(self), id(self.connection))
566
+ )
567
+
568
+ def __iter__(self): # [2.1 Zamarev]
569
+ return iter(self.fetchone, None) # [2.1 Zamarev]
570
+
571
+ def prepare(self, operation):
572
+ self.command = operation
573
+ self._description = None
574
+ self._ado_prepared = "setup"
575
+
576
+ def __next__(self):
577
+ r = self.fetchone()
578
+ if r:
579
+ return r
580
+ raise StopIteration
581
+
582
+ def __enter__(self):
583
+ "Allow database cursors to be used with context managers."
584
+ return self
585
+
586
+ def __exit__(self, exc_type, exc_val, exc_tb):
587
+ "Allow database cursors to be used with context managers."
588
+ self.close()
589
+
590
+ def _raiseCursorError(self, errorclass, errorvalue):
591
+ eh = self.errorhandler
592
+ if eh is None:
593
+ eh = api.standardErrorHandler
594
+ eh(self.connection, self, errorclass, errorvalue)
595
+
596
+ def build_column_info(self, recordset):
597
+ self.converters = [] # conversion function for each column
598
+ self.columnNames = {} # names of columns {lowercase name : number,...}
599
+ self._description = None
600
+
601
+ # if EOF and BOF are true at the same time, there are no records in the recordset
602
+ if (recordset is None) or (recordset.State == adc.adStateClosed):
603
+ self.rs = None
604
+ self.numberOfColumns = 0
605
+ return
606
+ self.rs = recordset # v2.1.1 bkline
607
+ self.recordset_format = api.RS_WIN_32
608
+ self.numberOfColumns = recordset.Fields.Count
609
+ try:
610
+ varCon = self.connection.variantConversions
611
+ except AttributeError:
612
+ varCon = api.variantConversions
613
+ for i in range(self.numberOfColumns):
614
+ f = getIndexedValue(self.rs.Fields, i)
615
+ try:
616
+ self.converters.append(
617
+ varCon[f.Type]
618
+ ) # conversion function for this column
619
+ except KeyError:
620
+ self._raiseCursorError(
621
+ api.InternalError, "Data column of Unknown ADO type=%s" % f.Type
622
+ )
623
+ self.columnNames[f.Name.lower()] = i # columnNames lookup
624
+
625
+ def _makeDescriptionFromRS(self):
626
+ # Abort if closed or no recordset.
627
+ if self.rs is None:
628
+ self._description = None
629
+ return
630
+ desc = []
631
+ for i in range(self.numberOfColumns):
632
+ f = getIndexedValue(self.rs.Fields, i)
633
+ if self.rs.EOF or self.rs.BOF:
634
+ display_size = None
635
+ else:
636
+ # TODO: Is this the correct defintion according to the DB API 2 Spec ?
637
+ display_size = f.ActualSize
638
+ null_ok = bool(f.Attributes & adc.adFldMayBeNull) # v2.1 Cole
639
+ desc.append(
640
+ (
641
+ f.Name,
642
+ f.Type,
643
+ display_size,
644
+ f.DefinedSize,
645
+ f.Precision,
646
+ f.NumericScale,
647
+ null_ok,
648
+ )
649
+ )
650
+ self._description = desc
651
+
652
+ def get_description(self):
653
+ if not self._description:
654
+ self._makeDescriptionFromRS()
655
+ return self._description
656
+
657
+ def __getattr__(self, item):
658
+ if item == "description":
659
+ return self.get_description()
660
+ object.__getattribute__(
661
+ self, item
662
+ ) # may get here on Remote attribute calls for existing attributes
663
+
664
+ def format_description(self, d):
665
+ """Format db_api description tuple for printing."""
666
+ if self.description is None:
667
+ self._makeDescriptionFromRS()
668
+ if isinstance(d, int):
669
+ d = self.description[d]
670
+ desc = (
671
+ "Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s"
672
+ % (
673
+ d[0],
674
+ adc.adTypeNames.get(d[1], str(d[1]) + " (unknown type)"),
675
+ d[2],
676
+ d[3],
677
+ d[4],
678
+ d[5],
679
+ d[6],
680
+ )
681
+ )
682
+ return desc
683
+
684
+ def close(self, dont_tell_me=False):
685
+ """Close the cursor now (rather than whenever __del__ is called).
686
+ The cursor will be unusable from this point forward; an Error (or subclass)
687
+ exception will be raised if any operation is attempted with the cursor.
688
+ """
689
+ if self.connection is None:
690
+ return
691
+ self.messages = []
692
+ if (
693
+ self.rs and self.rs.State != adc.adStateClosed
694
+ ): # rs exists and is open #v2.1 Rose
695
+ self.rs.Close() # v2.1 Rose
696
+ self.rs = None # let go of the recordset so ADO will let it be disposed #v2.1 Rose
697
+ if not dont_tell_me:
698
+ self.connection._i_am_closing(
699
+ self
700
+ ) # take me off the connection's cursors list
701
+ self.connection = (
702
+ None # this will make all future method calls on me throw an exception
703
+ )
704
+ if verbose:
705
+ print("adodbapi Closed cursor at %X" % id(self))
706
+
707
+ def __del__(self):
708
+ try:
709
+ self.close()
710
+ except:
711
+ pass
712
+
713
+ def _new_command(self, command_type=adc.adCmdText):
714
+ self.cmd = None
715
+ self.messages = []
716
+
717
+ if self.connection is None:
718
+ self._raiseCursorError(api.InterfaceError, None)
719
+ return
720
+ try:
721
+ self.cmd = Dispatch("ADODB.Command")
722
+ self.cmd.ActiveConnection = self.connection.connector
723
+ self.cmd.CommandTimeout = self.connection.timeout
724
+ self.cmd.CommandType = command_type
725
+ self.cmd.CommandText = self.commandText
726
+ self.cmd.Prepared = bool(self._ado_prepared)
727
+ except:
728
+ self._raiseCursorError(
729
+ api.DatabaseError,
730
+ f"Error creating new ADODB.Command object for {self.commandText!r}",
731
+ )
732
+
733
+ def _execute_command(self):
734
+ # Stored procedures may have an integer return value
735
+ self.return_value = None
736
+ recordset = None
737
+ count = -1 # default value
738
+ if verbose:
739
+ print('Executing command="%s"' % self.commandText)
740
+ try:
741
+ # ----- the actual SQL is executed here ---
742
+ recordset, count = self.cmd.Execute()
743
+ # ----- ------------------------------- ---
744
+ except Exception as e:
745
+ _message = ""
746
+ if hasattr(e, "args"):
747
+ _message += str(e.args) + "\n"
748
+ _message += "Command:\n%s\nParameters:\n%s" % (
749
+ self.commandText,
750
+ format_parameters(self.cmd.Parameters, True),
751
+ )
752
+ klass = self.connection._suggest_error_class()
753
+ self._raiseCursorError(klass, _message)
754
+ try:
755
+ self.rowcount = recordset.RecordCount
756
+ except:
757
+ self.rowcount = count
758
+ self.build_column_info(recordset)
759
+
760
+ # The ADO documentation hints that obtaining the recordcount may be timeconsuming
761
+ # "If the Recordset object does not support approximate positioning, this property
762
+ # may be a significant drain on resources # [ekelund]
763
+ # Therefore, COM will not return rowcount for server-side cursors. [Cole]
764
+ # Client-side cursors (the default since v2.8) will force a static
765
+ # cursor, and rowcount will then be set accurately [Cole]
766
+
767
+ def get_rowcount(self):
768
+ return self.rowcount
769
+
770
+ def get_returned_parameters(self):
771
+ """with some providers, returned parameters and the .return_value are not available until
772
+ after the last recordset has been read. In that case, you must coll nextset() until it
773
+ returns None, then call this method to get your returned information."""
774
+
775
+ # store procedures may return altered parameters, including an added "return value" item
776
+ retLst = []
777
+ for p in tuple(self.cmd.Parameters):
778
+ if verbose > 2:
779
+ print(
780
+ 'Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s",'
781
+ " Precision: %s, NumericScale: %s"
782
+ % (
783
+ p.Name,
784
+ adc.directions[p.Direction],
785
+ adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
786
+ p.Size,
787
+ p.Value,
788
+ p.Precision,
789
+ p.NumericScale,
790
+ )
791
+ )
792
+ pyObject = api.convert_to_python(p.Value, api.variantConversions[p.Type])
793
+ if p.Direction == adc.adParamReturnValue:
794
+ self.returnValue = (
795
+ pyObject # also load the undocumented attribute (Vernon's Error!)
796
+ )
797
+ self.return_value = pyObject
798
+ else:
799
+ retLst.append(pyObject)
800
+ return retLst # return the parameter list to the caller
801
+
802
+ def callproc(self, procname, parameters=None):
803
+ """Call a stored database procedure with the given name.
804
+ The sequence of parameters must contain one entry for each
805
+ argument that the sproc expects. The result of the
806
+ call is returned as modified copy of the input
807
+ sequence. Input parameters are left untouched, output and
808
+ input/output parameters replaced with possibly new values.
809
+
810
+ The sproc may also provide a result set as output,
811
+ which is available through the standard .fetch*() methods.
812
+ Extension: A "return_value" property may be set on the
813
+ cursor if the sproc defines an integer return value.
814
+ """
815
+ self._parameter_names = []
816
+ self.commandText = procname
817
+ self._new_command(command_type=adc.adCmdStoredProc)
818
+ self._buildADOparameterList(parameters, sproc=True)
819
+ if verbose > 2:
820
+ print(
821
+ "Calling Stored Proc with Params=",
822
+ format_parameters(self.cmd.Parameters, True),
823
+ )
824
+ self._execute_command()
825
+ return self.get_returned_parameters()
826
+
827
+ def _reformat_operation(self, operation, parameters):
828
+ if self.paramstyle in ("format", "pyformat"): # convert %s to ?
829
+ operation, self._parameter_names = api.changeFormatToQmark(operation)
830
+ elif self.paramstyle == "named" or (
831
+ self.paramstyle == "dynamic" and isinstance(parameters, Mapping)
832
+ ):
833
+ operation, self._parameter_names = api.changeNamedToQmark(
834
+ operation
835
+ ) # convert :name to ?
836
+ return operation
837
+
838
+ def _buildADOparameterList(self, parameters, sproc=False):
839
+ self.parameters = parameters
840
+ if parameters is None:
841
+ parameters = []
842
+
843
+ # Note: ADO does not preserve the parameter list, even if "Prepared" is True, so we must build every time.
844
+ parameters_known = False
845
+ if sproc: # needed only if we are calling a stored procedure
846
+ try: # attempt to use ADO's parameter list
847
+ self.cmd.Parameters.Refresh()
848
+ if verbose > 2:
849
+ print(
850
+ "ADO detected Params=",
851
+ format_parameters(self.cmd.Parameters, True),
852
+ )
853
+ print(f"Program Parameters={parameters!r}")
854
+ parameters_known = True
855
+ except api.Error:
856
+ if verbose:
857
+ print("ADO Parameter Refresh failed")
858
+ pass
859
+ else:
860
+ if len(parameters) != self.cmd.Parameters.Count - 1:
861
+ raise api.ProgrammingError(
862
+ "You must supply %d parameters for this stored procedure"
863
+ % (self.cmd.Parameters.Count - 1)
864
+ )
865
+ if sproc or parameters != []:
866
+ i = 0
867
+ if parameters_known: # use ado parameter list
868
+ if self._parameter_names: # named parameters
869
+ for i, pm_name in enumerate(self._parameter_names):
870
+ p = getIndexedValue(self.cmd.Parameters, i)
871
+ try:
872
+ _configure_parameter(
873
+ p, parameters[pm_name], p.Type, parameters_known
874
+ )
875
+ except Exception as e:
876
+ _message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format(
877
+ p.Name,
878
+ adc.ado_type_name(p.Type),
879
+ p.Value,
880
+ parameters[pm_name],
881
+ )
882
+ self._raiseCursorError(
883
+ api.DataError, f"{_message}->{e.args!r}"
884
+ )
885
+ else: # regular sequence of parameters
886
+ for value in parameters:
887
+ p = getIndexedValue(self.cmd.Parameters, i)
888
+ if (
889
+ p.Direction == adc.adParamReturnValue
890
+ ): # this is an extra parameter added by ADO
891
+ i += 1 # skip the extra
892
+ p = getIndexedValue(self.cmd.Parameters, i)
893
+ try:
894
+ _configure_parameter(p, value, p.Type, parameters_known)
895
+ except Exception as e:
896
+ _message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format(
897
+ p.Name,
898
+ adc.ado_type_name(p.Type),
899
+ p.Value,
900
+ value,
901
+ )
902
+ self._raiseCursorError(
903
+ api.DataError, f"{_message}->{e.args!r}"
904
+ )
905
+ i += 1
906
+ else: # -- build own parameter list
907
+ # we expect a dictionary of parameters, this is the list of expected names
908
+ if self._parameter_names:
909
+ for parm_name in self._parameter_names:
910
+ elem = parameters[parm_name]
911
+ adotype = api.pyTypeToADOType(elem)
912
+ p = self.cmd.CreateParameter(
913
+ parm_name, adotype, adc.adParamInput
914
+ )
915
+ _configure_parameter(p, elem, adotype, parameters_known)
916
+ try:
917
+ self.cmd.Parameters.Append(p)
918
+ except Exception as e:
919
+ _message = (
920
+ "Error Building Parameter {}: {}, {} <- {!r}\n".format(
921
+ p.Name,
922
+ adc.ado_type_name(p.Type),
923
+ p.Value,
924
+ elem,
925
+ )
926
+ )
927
+ self._raiseCursorError(
928
+ api.DataError, f"{_message}->{e.args!r}"
929
+ )
930
+ else: # expecting the usual sequence of parameters
931
+ if sproc:
932
+ p = self.cmd.CreateParameter(
933
+ "@RETURN_VALUE", adc.adInteger, adc.adParamReturnValue
934
+ )
935
+ self.cmd.Parameters.Append(p)
936
+
937
+ for elem in parameters:
938
+ name = "p%i" % i
939
+ adotype = api.pyTypeToADOType(elem)
940
+ p = self.cmd.CreateParameter(
941
+ name, adotype, adc.adParamInput
942
+ ) # Name, Type, Direction, Size, Value
943
+ _configure_parameter(p, elem, adotype, parameters_known)
944
+ try:
945
+ self.cmd.Parameters.Append(p)
946
+ except Exception as e:
947
+ _message = (
948
+ "Error Building Parameter {}: {}, {} <- {!r}\n".format(
949
+ p.Name,
950
+ adc.ado_type_name(p.Type),
951
+ p.Value,
952
+ elem,
953
+ )
954
+ )
955
+ self._raiseCursorError(
956
+ api.DataError, f"{_message}->{e.args!r}"
957
+ )
958
+ i += 1
959
+ if self._ado_prepared == "setup":
960
+ self._ado_prepared = (
961
+ True # parameters will be "known" by ADO next loop
962
+ )
963
+
964
+ def execute(self, operation, parameters=None):
965
+ """Prepare and execute a database operation (query or command).
966
+
967
+ Parameters may be provided as sequence or mapping and will be bound to variables in the operation.
968
+ Variables are specified in a database-specific notation
969
+ (see the module's paramstyle attribute for details). [5]
970
+ A reference to the operation will be retained by the cursor.
971
+ If the same operation object is passed in again, then the cursor
972
+ can optimize its behavior. This is most effective for algorithms
973
+ where the same operation is used, but different parameters are bound to it (many times).
974
+
975
+ For maximum efficiency when reusing an operation, it is best to use
976
+ the setinputsizes() method to specify the parameter types and sizes ahead of time.
977
+ It is legal for a parameter to not match the predefined information;
978
+ the implementation should compensate, possibly with a loss of efficiency.
979
+
980
+ The parameters may also be specified as list of tuples to e.g. insert multiple rows in
981
+ a single operation, but this kind of usage is depreciated: executemany() should be used instead.
982
+
983
+ Return value is not defined.
984
+
985
+ [5] The module will use the __getitem__ method of the parameters object to map either positions
986
+ (integers) or names (strings) to parameter values. This allows for both sequences and mappings
987
+ to be used as input.
988
+ The term "bound" refers to the process of binding an input value to a database execution buffer.
989
+ In practical terms, this means that the input value is directly used as a value in the operation.
990
+ The client should not be required to "escape" the value so that it can be used -- the value
991
+ should be equal to the actual database value."""
992
+ if (
993
+ self.command is not operation
994
+ or self._ado_prepared == "setup"
995
+ or not hasattr(self, "commandText")
996
+ ):
997
+ if self.command is not operation:
998
+ self._ado_prepared = False
999
+ self.command = operation
1000
+ self._parameter_names = []
1001
+ self.commandText = (
1002
+ operation
1003
+ if (self.paramstyle == "qmark" or not parameters)
1004
+ else self._reformat_operation(operation, parameters)
1005
+ )
1006
+ self._new_command()
1007
+ self._buildADOparameterList(parameters)
1008
+ if verbose > 3:
1009
+ print("Params=", format_parameters(self.cmd.Parameters, True))
1010
+ self._execute_command()
1011
+
1012
+ def executemany(self, operation, seq_of_parameters):
1013
+ """Prepare a database operation (query or command)
1014
+ and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
1015
+
1016
+ Return values are not defined.
1017
+ """
1018
+ self.messages = list()
1019
+ total_recordcount = 0
1020
+
1021
+ self.prepare(operation)
1022
+ for params in seq_of_parameters:
1023
+ self.execute(self.command, params)
1024
+ if self.rowcount == -1:
1025
+ total_recordcount = -1
1026
+ if total_recordcount != -1:
1027
+ total_recordcount += self.rowcount
1028
+ self.rowcount = total_recordcount
1029
+
1030
+ def _fetch(self, limit=None):
1031
+ """Fetch rows from the current recordset.
1032
+
1033
+ limit -- Number of rows to fetch, or None (default) to fetch all rows.
1034
+ """
1035
+ if self.connection is None or self.rs is None:
1036
+ self._raiseCursorError(
1037
+ api.FetchFailedError, "fetch() on closed connection or empty query set"
1038
+ )
1039
+ return
1040
+
1041
+ if self.rs.State == adc.adStateClosed or self.rs.BOF or self.rs.EOF:
1042
+ return list()
1043
+ if limit: # limit number of rows retrieved
1044
+ ado_results = self.rs.GetRows(limit)
1045
+ else: # get all rows
1046
+ ado_results = self.rs.GetRows()
1047
+ if (
1048
+ self.recordset_format == api.RS_ARRAY
1049
+ ): # result of GetRows is a two-dimension array
1050
+ length = (
1051
+ len(ado_results) // self.numberOfColumns
1052
+ ) # length of first dimension
1053
+ else: # pywin32
1054
+ length = len(ado_results[0]) # result of GetRows is tuples in a tuple
1055
+ fetchObject = api.SQLrows(
1056
+ ado_results, length, self
1057
+ ) # new object to hold the results of the fetch
1058
+ return fetchObject
1059
+
1060
+ def fetchone(self):
1061
+ """Fetch the next row of a query result set, returning a single sequence,
1062
+ or None when no more data is available.
1063
+
1064
+ An Error (or subclass) exception is raised if the previous call to executeXXX()
1065
+ did not produce any result set or no call was issued yet.
1066
+ """
1067
+ self.messages = []
1068
+ result = self._fetch(1)
1069
+ if result: # return record (not list of records)
1070
+ return result[0]
1071
+ return None
1072
+
1073
+ def fetchmany(self, size=None):
1074
+ """Fetch the next set of rows of a query result, returning a list of tuples. An empty sequence is returned when no more rows are available.
1075
+
1076
+ The number of rows to fetch per call is specified by the parameter.
1077
+ If it is not given, the cursor's arraysize determines the number of rows to be fetched.
1078
+ The method should try to fetch as many rows as indicated by the size parameter.
1079
+ If this is not possible due to the specified number of rows not being available,
1080
+ fewer rows may be returned.
1081
+
1082
+ An Error (or subclass) exception is raised if the previous call to executeXXX()
1083
+ did not produce any result set or no call was issued yet.
1084
+
1085
+ Note there are performance considerations involved with the size parameter.
1086
+ For optimal performance, it is usually best to use the arraysize attribute.
1087
+ If the size parameter is used, then it is best for it to retain the same value from
1088
+ one fetchmany() call to the next.
1089
+ """
1090
+ self.messages = []
1091
+ if size is None:
1092
+ size = self.arraysize
1093
+ return self._fetch(size)
1094
+
1095
+ def fetchall(self):
1096
+ """Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples).
1097
+
1098
+ Note that the cursor's arraysize attribute
1099
+ can affect the performance of this operation.
1100
+ An Error (or subclass) exception is raised if the previous call to executeXXX()
1101
+ did not produce any result set or no call was issued yet.
1102
+ """
1103
+ self.messages = []
1104
+ return self._fetch()
1105
+
1106
+ def nextset(self):
1107
+ """Skip to the next available recordset, discarding any remaining rows from the current recordset.
1108
+
1109
+ If there are no more sets, the method returns None. Otherwise, it returns a true
1110
+ value and subsequent calls to the fetch methods will return rows from the next result set.
1111
+
1112
+ An Error (or subclass) exception is raised if the previous call to executeXXX()
1113
+ did not produce any result set or no call was issued yet.
1114
+ """
1115
+ self.messages = []
1116
+ if self.connection is None or self.rs is None:
1117
+ self._raiseCursorError(
1118
+ api.OperationalError,
1119
+ ("nextset() on closed connection or empty query set"),
1120
+ )
1121
+ return None
1122
+
1123
+ try: # [begin 2.1 ekelund]
1124
+ rsTuple = self.rs.NextRecordset() #
1125
+ except pywintypes.com_error as exc: # return appropriate error
1126
+ self._raiseCursorError(api.NotSupportedError, exc.args) # [end 2.1 ekelund]
1127
+ recordset = rsTuple[0]
1128
+ if recordset is None:
1129
+ return None
1130
+ self.build_column_info(recordset)
1131
+ return True
1132
+
1133
+ def setinputsizes(self, sizes):
1134
+ pass
1135
+
1136
+ def setoutputsize(self, size, column=None):
1137
+ pass
1138
+
1139
+ def _last_query(self): # let the programmer see what query we actually used
1140
+ try:
1141
+ if self.parameters is None:
1142
+ ret = self.commandText
1143
+ else:
1144
+ ret = f"{self.commandText},parameters={self.parameters!r}"
1145
+ except:
1146
+ ret = None
1147
+ return ret
1148
+
1149
+ query = property(_last_query, None, None, "returns the last query executed")
1150
+
1151
+
1152
+ if __name__ == "__main__":
1153
+ raise api.ProgrammingError(version + " cannot be run as a main program.")
python_embeded/Lib/site-packages/adodbapi/apibase.py ADDED
@@ -0,0 +1,723 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """adodbapi.apibase - A python DB API 2.0 (PEP 249) interface to Microsoft ADO
2
+
3
+ Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole
4
+ * https://sourceforge.net/projects/pywin32
5
+ * https://sourceforge.net/projects/adodbapi
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime
11
+ import decimal
12
+ import numbers
13
+ import sys
14
+ import time
15
+ from collections.abc import Callable, Iterable, Mapping
16
+
17
+ # noinspection PyUnresolvedReferences
18
+ from . import ado_consts as adc
19
+
20
+ verbose = False # debugging flag
21
+
22
+
23
+ # ------- Error handlers ------
24
+ def standardErrorHandler(connection, cursor, errorclass, errorvalue):
25
+ err = (errorclass, errorvalue)
26
+ try:
27
+ connection.messages.append(err)
28
+ except:
29
+ pass
30
+ if cursor is not None:
31
+ try:
32
+ cursor.messages.append(err)
33
+ except:
34
+ pass
35
+ raise errorclass(errorvalue)
36
+
37
+
38
+ class Error(Exception):
39
+ pass # Exception that is the base class of all other error
40
+ # exceptions. You can use this to catch all errors with one
41
+ # single 'except' statement. Warnings are not considered
42
+ # errors and thus should not use this class as base. It must
43
+ # be a subclass of the Python StandardError (defined in the
44
+ # module exceptions).
45
+
46
+
47
+ class Warning(Exception):
48
+ pass
49
+
50
+
51
+ class InterfaceError(Error):
52
+ pass
53
+
54
+
55
+ class DatabaseError(Error):
56
+ pass
57
+
58
+
59
+ class InternalError(DatabaseError):
60
+ pass
61
+
62
+
63
+ class OperationalError(DatabaseError):
64
+ pass
65
+
66
+
67
+ class ProgrammingError(DatabaseError):
68
+ pass
69
+
70
+
71
+ class IntegrityError(DatabaseError):
72
+ pass
73
+
74
+
75
+ class DataError(DatabaseError):
76
+ pass
77
+
78
+
79
+ class NotSupportedError(DatabaseError):
80
+ pass
81
+
82
+
83
+ class FetchFailedError(OperationalError):
84
+ """
85
+ Error is used by RawStoredProcedureQuerySet to determine when a fetch
86
+ failed due to a connection being closed or there is no record set
87
+ returned. (Non-standard, added especially for django)
88
+ """
89
+
90
+ pass
91
+
92
+
93
+ # # # # # ----- Type Objects and Constructors ----- # # # # #
94
+ # Many databases need to have the input in a particular format for binding to an operation's input parameters.
95
+ # For example, if an input is destined for a DATE column, then it must be bound to the database in a particular
96
+ # string format. Similar problems exist for "Row ID" columns or large binary items (e.g. blobs or RAW columns).
97
+ # This presents problems for Python since the parameters to the executeXXX() method are untyped.
98
+ # When the database module sees a Python string object, it doesn't know if it should be bound as a simple CHAR
99
+ # column, as a raw BINARY item, or as a DATE.
100
+ #
101
+ # To overcome this problem, a module must provide the constructors defined below to create objects that can
102
+ # hold special values. When passed to the cursor methods, the module can then detect the proper type of
103
+ # the input parameter and bind it accordingly.
104
+
105
+ # A Cursor Object's description attribute returns information about each of the result columns of a query.
106
+ # The type_code must compare equal to one of Type Objects defined below. Type Objects may be equal to more than
107
+ # one type code (e.g. DATETIME could be equal to the type codes for date, time and timestamp columns;
108
+ # see the Implementation Hints below for details).
109
+
110
+ # SQL NULL values are represented by the Python None singleton on input and output.
111
+
112
+ # Note: Usage of Unix ticks for database interfacing can cause troubles because of the limited date range they cover.
113
+
114
+
115
+ # def Date(year,month,day):
116
+ # "This function constructs an object holding a date value. "
117
+ # return dateconverter.date(year,month,day) #dateconverter.Date(year,month,day)
118
+ #
119
+ # def Time(hour,minute,second):
120
+ # "This function constructs an object holding a time value. "
121
+ # return dateconverter.time(hour, minute, second) # dateconverter.Time(hour,minute,second)
122
+ #
123
+ # def Timestamp(year,month,day,hour,minute,second):
124
+ # "This function constructs an object holding a time stamp value. "
125
+ # return dateconverter.datetime(year,month,day,hour,minute,second)
126
+ #
127
+ # def DateFromTicks(ticks):
128
+ # """This function constructs an object holding a date value from the given ticks value
129
+ # (number of seconds since the epoch; see the documentation of the standard Python time module for details). """
130
+ # return Date(*time.gmtime(ticks)[:3])
131
+ #
132
+ # def TimeFromTicks(ticks):
133
+ # """This function constructs an object holding a time value from the given ticks value
134
+ # (number of seconds since the epoch; see the documentation of the standard Python time module for details). """
135
+ # return Time(*time.gmtime(ticks)[3:6])
136
+ #
137
+ # def TimestampFromTicks(ticks):
138
+ # """This function constructs an object holding a time stamp value from the given
139
+ # ticks value (number of seconds since the epoch;
140
+ # see the documentation of the standard Python time module for details). """
141
+ # return Timestamp(*time.gmtime(ticks)[:6])
142
+ #
143
+ # def Binary(aString):
144
+ # """This function constructs an object capable of holding a binary (long) string value. """
145
+ # b = bytes(aString)
146
+ # return b
147
+ # ----- Time converters ----------------------------------------------
148
+ class TimeConverter: # this is a generic time converter skeleton
149
+ def __init__(self): # the details will be filled in by instances
150
+ self._ordinal_1899_12_31 = datetime.date(1899, 12, 31).toordinal() - 1
151
+ # Use cls.types to compare if an input parameter is a datetime
152
+ self.types = {
153
+ # Dynamically get the types as the methods may be overriden
154
+ type(self.Date(2000, 1, 1)),
155
+ type(self.Time(12, 1, 1)),
156
+ type(self.Timestamp(2000, 1, 1, 12, 1, 1)),
157
+ datetime.datetime,
158
+ datetime.time,
159
+ datetime.date,
160
+ }
161
+
162
+ def COMDate(self, obj):
163
+ """Returns a ComDate from a date-time"""
164
+ try: # most likely a datetime
165
+ tt = obj.timetuple()
166
+
167
+ try:
168
+ ms = obj.microsecond
169
+ except:
170
+ ms = 0
171
+ return self.ComDateFromTuple(tt, ms)
172
+ except: # might be a tuple
173
+ try:
174
+ return self.ComDateFromTuple(obj)
175
+ except:
176
+ raise ValueError(f'Cannot convert "{obj!r}" to COMdate.')
177
+
178
+ def ComDateFromTuple(self, t, microseconds=0):
179
+ d = datetime.date(t[0], t[1], t[2])
180
+ integerPart = d.toordinal() - self._ordinal_1899_12_31
181
+ ms = (t[3] * 3600 + t[4] * 60 + t[5]) * 1000000 + microseconds
182
+ fractPart = float(ms) / 86400000000.0
183
+ return integerPart + fractPart
184
+
185
+ def DateObjectFromCOMDate(self, comDate):
186
+ "Returns an object of the wanted type from a ComDate"
187
+ raise NotImplementedError # "Abstract class"
188
+
189
+ def Date(self, year, month, day):
190
+ "This function constructs an object holding a date value."
191
+ raise NotImplementedError # "Abstract class"
192
+
193
+ def Time(self, hour, minute, second):
194
+ "This function constructs an object holding a time value."
195
+ raise NotImplementedError # "Abstract class"
196
+
197
+ def Timestamp(self, year, month, day, hour, minute, second):
198
+ "This function constructs an object holding a time stamp value."
199
+ raise NotImplementedError # "Abstract class"
200
+ # all purpose date to ISO format converter
201
+
202
+ def DateObjectToIsoFormatString(self, obj):
203
+ "This function should return a string in the format 'YYYY-MM-dd HH:MM:SS:ms' (ms optional)"
204
+ try: # most likely, a datetime.datetime
205
+ s = obj.isoformat(" ")
206
+ except (TypeError, AttributeError):
207
+ if isinstance(obj, datetime.date):
208
+ s = obj.isoformat() + " 00:00:00" # return exact midnight
209
+ else:
210
+ try: # but may be time.struct_time
211
+ s = time.strftime("%Y-%m-%d %H:%M:%S", obj)
212
+ except:
213
+ raise ValueError(f'Cannot convert "{obj!r}" to isoformat')
214
+ return s
215
+
216
+
217
+ class pythonDateTimeConverter(TimeConverter): # standard since Python 2.3
218
+ def __init__(self):
219
+ TimeConverter.__init__(self)
220
+
221
+ def DateObjectFromCOMDate(self, comDate):
222
+ if isinstance(comDate, datetime.datetime):
223
+ odn = comDate.toordinal()
224
+ tim = comDate.time()
225
+ new = datetime.datetime.combine(datetime.datetime.fromordinal(odn), tim)
226
+ return new
227
+ # return comDate.replace(tzinfo=None) # make non aware
228
+ else:
229
+ fComDate = float(comDate) # ComDate is number of days since 1899-12-31
230
+ integerPart = int(fComDate)
231
+ floatpart = fComDate - integerPart
232
+ ##if floatpart == 0.0:
233
+ ## return datetime.date.fromordinal(integerPart + self._ordinal_1899_12_31)
234
+ dte = datetime.datetime.fromordinal(
235
+ integerPart + self._ordinal_1899_12_31
236
+ ) + datetime.timedelta(milliseconds=floatpart * 86400000)
237
+ # millisecondsperday=86400000 # 24*60*60*1000
238
+ return dte
239
+
240
+ def Date(self, year, month, day):
241
+ return datetime.date(year, month, day)
242
+
243
+ def Time(self, hour, minute, second):
244
+ return datetime.time(hour, minute, second)
245
+
246
+ def Timestamp(self, year, month, day, hour, minute, second):
247
+ return datetime.datetime(year, month, day, hour, minute, second)
248
+
249
+
250
+ class pythonTimeConverter(TimeConverter): # the old, ?nix type date and time
251
+ def __init__(self): # caution: this Class gets confised by timezones and DST
252
+ TimeConverter.__init__(self)
253
+ self.types.add(time.struct_time)
254
+
255
+ def DateObjectFromCOMDate(self, comDate):
256
+ "Returns ticks since 1970"
257
+ if isinstance(comDate, datetime.datetime):
258
+ return comDate.timetuple()
259
+ else:
260
+ fcomDate = float(comDate)
261
+ secondsperday = 86400 # 24*60*60
262
+ # ComDate is number of days since 1899-12-31, gmtime epoch is 1970-1-1 = 25569 days
263
+ t = time.gmtime(secondsperday * (fcomDate - 25569.0))
264
+ return t # year,month,day,hour,minute,second,weekday,julianday,daylightsaving=t
265
+
266
+ def Date(self, year, month, day):
267
+ return self.Timestamp(year, month, day, 0, 0, 0)
268
+
269
+ def Time(self, hour, minute, second):
270
+ return time.gmtime((hour * 60 + minute) * 60 + second)
271
+
272
+ def Timestamp(self, year, month, day, hour, minute, second):
273
+ return time.localtime(
274
+ time.mktime((year, month, day, hour, minute, second, 0, 0, -1))
275
+ )
276
+
277
+
278
+ base_dateconverter = pythonDateTimeConverter()
279
+
280
+ # ------ DB API required module attributes ---------------------
281
+ threadsafety = 1 # TODO -- find out whether this module is actually BETTER than 1.
282
+
283
+ apilevel = "2.0" # String constant stating the supported DB API level.
284
+
285
+ paramstyle = "qmark" # the default parameter style
286
+
287
+ # ------ control for an extension which may become part of DB API 3.0 ---
288
+ accepted_paramstyles = ("qmark", "named", "format", "pyformat", "dynamic")
289
+
290
+ # ------------------------------------------------------------------------------------------
291
+ # define similar types for generic conversion routines
292
+ adoIntegerTypes = (
293
+ adc.adInteger,
294
+ adc.adSmallInt,
295
+ adc.adTinyInt,
296
+ adc.adUnsignedInt,
297
+ adc.adUnsignedSmallInt,
298
+ adc.adUnsignedTinyInt,
299
+ adc.adBoolean,
300
+ adc.adError,
301
+ ) # max 32 bits
302
+ adoRowIdTypes = (adc.adChapter,) # v2.1 Rose
303
+ adoLongTypes = (adc.adBigInt, adc.adFileTime, adc.adUnsignedBigInt)
304
+ adoExactNumericTypes = (
305
+ adc.adDecimal,
306
+ adc.adNumeric,
307
+ adc.adVarNumeric,
308
+ adc.adCurrency,
309
+ ) # v2.3 Cole
310
+ adoApproximateNumericTypes = (adc.adDouble, adc.adSingle) # v2.1 Cole
311
+ adoStringTypes = (
312
+ adc.adBSTR,
313
+ adc.adChar,
314
+ adc.adLongVarChar,
315
+ adc.adLongVarWChar,
316
+ adc.adVarChar,
317
+ adc.adVarWChar,
318
+ adc.adWChar,
319
+ )
320
+ adoBinaryTypes = (adc.adBinary, adc.adLongVarBinary, adc.adVarBinary)
321
+ adoDateTimeTypes = (adc.adDBTime, adc.adDBTimeStamp, adc.adDate, adc.adDBDate)
322
+ adoRemainingTypes = (
323
+ adc.adEmpty,
324
+ adc.adIDispatch,
325
+ adc.adIUnknown,
326
+ adc.adPropVariant,
327
+ adc.adArray,
328
+ adc.adUserDefined,
329
+ adc.adVariant,
330
+ adc.adGUID,
331
+ )
332
+
333
+
334
+ # this class is a trick to determine whether a type is a member of a related group of types. see PEP notes
335
+ class DBAPITypeObject:
336
+ def __init__(self, valuesTuple):
337
+ self.values = frozenset(valuesTuple)
338
+
339
+ def __eq__(self, other):
340
+ return other in self.values
341
+
342
+ def __ne__(self, other):
343
+ return other not in self.values
344
+
345
+
346
+ """This type object is used to describe columns in a database that are string-based (e.g. CHAR). """
347
+ STRING = DBAPITypeObject(adoStringTypes)
348
+
349
+ """This type object is used to describe (long) binary columns in a database (e.g. LONG, RAW, BLOBs). """
350
+ BINARY = DBAPITypeObject(adoBinaryTypes)
351
+
352
+ """This type object is used to describe numeric columns in a database. """
353
+ NUMBER = DBAPITypeObject(
354
+ adoIntegerTypes + adoLongTypes + adoExactNumericTypes + adoApproximateNumericTypes
355
+ )
356
+
357
+ """This type object is used to describe date/time columns in a database. """
358
+
359
+ DATETIME = DBAPITypeObject(adoDateTimeTypes)
360
+ """This type object is used to describe the "Row ID" column in a database. """
361
+ ROWID = DBAPITypeObject(adoRowIdTypes)
362
+
363
+ OTHER = DBAPITypeObject(adoRemainingTypes)
364
+
365
+ # ------- utilities for translating python data types to ADO data types ---------------------------------
366
+ typeMap = {
367
+ memoryview: adc.adVarBinary,
368
+ float: adc.adDouble,
369
+ type(None): adc.adEmpty,
370
+ str: adc.adBSTR,
371
+ bool: adc.adBoolean, # v2.1 Cole
372
+ decimal.Decimal: adc.adDecimal,
373
+ int: adc.adBigInt,
374
+ bytes: adc.adVarBinary,
375
+ }
376
+
377
+
378
+ def pyTypeToADOType(d):
379
+ tp = type(d)
380
+ try:
381
+ return typeMap[tp]
382
+ except KeyError: # The type was not defined in the pre-computed Type table
383
+ from . import dateconverter
384
+
385
+ # maybe it is one of our supported Date/Time types
386
+ if tp in dateconverter.types:
387
+ return adc.adDate
388
+ # otherwise, attempt to discern the type by probing the data object itself -- to handle duck typing
389
+ if isinstance(d, str):
390
+ return adc.adBSTR
391
+ if isinstance(d, numbers.Integral):
392
+ return adc.adBigInt
393
+ if isinstance(d, numbers.Real):
394
+ return adc.adDouble
395
+ raise DataError(f'cannot convert "{d!r}" (type={tp}) to ADO')
396
+
397
+
398
+ # # # # # # # # # # # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
399
+ # functions to convert database values to Python objects
400
+ # ------------------------------------------------------------------------
401
+ # variant type : function converting variant to Python value
402
+ def variantConvertDate(v):
403
+ from . import dateconverter # this function only called when adodbapi is running
404
+
405
+ return dateconverter.DateObjectFromCOMDate(v)
406
+
407
+
408
+ def cvtString(variant): # use to get old action of adodbapi v1 if desired
409
+ return str(variant)
410
+
411
+
412
+ def cvtDecimal(variant): # better name
413
+ return _convertNumberWithCulture(variant, decimal.Decimal)
414
+
415
+
416
+ def cvtNumeric(variant): # older name - don't break old code
417
+ return cvtDecimal(variant)
418
+
419
+
420
+ def cvtFloat(variant):
421
+ return _convertNumberWithCulture(variant, float)
422
+
423
+
424
+ def _convertNumberWithCulture(variant, f):
425
+ try:
426
+ return f(variant)
427
+ except (ValueError, TypeError, decimal.InvalidOperation):
428
+ try:
429
+ europeVsUS = str(variant).replace(",", ".")
430
+ return f(europeVsUS)
431
+ except (ValueError, TypeError, decimal.InvalidOperation):
432
+ pass
433
+
434
+
435
+ def cvtInt(variant):
436
+ return int(variant)
437
+
438
+
439
+ def cvtLong(variant): # only important in old versions where long and int differ
440
+ return int(variant)
441
+
442
+
443
+ def cvtBuffer(variant):
444
+ return bytes(variant)
445
+
446
+
447
+ def cvtUnicode(variant):
448
+ return str(variant)
449
+
450
+
451
+ def identity(x):
452
+ return x
453
+
454
+
455
+ def cvtUnusual(variant):
456
+ if verbose > 1:
457
+ sys.stderr.write(f"Conversion called for Unusual data={variant!r}\n")
458
+ return variant # cannot find conversion function -- just give the data to the user
459
+
460
+
461
+ def convert_to_python(variant, func): # convert DB value into Python value
462
+ if variant is None:
463
+ return None
464
+ return func(variant) # call the appropriate conversion function
465
+
466
+
467
+ class MultiMap(dict[int, Callable[[object], object]]):
468
+ # builds a dictionary from {(iterable,of,keys) : function}
469
+ """A dictionary of ado.type : function
470
+ -- but you can set multiple items by passing an iterable of keys"""
471
+
472
+ # useful for defining conversion functions for groups of similar data types.
473
+ def __init__(self, aDict: Mapping[Iterable[int] | int, Callable[[object], object]]):
474
+ for k, v in aDict.items():
475
+ self[k] = v # we must call __setitem__
476
+
477
+ def __setitem__(
478
+ self, adoType: Iterable[int] | int, cvtFn: Callable[[object], object]
479
+ ):
480
+ "set a single item, or a whole iterable of items"
481
+ if isinstance(adoType, Iterable):
482
+ # user passed us an iterable, set them individually
483
+ for type in adoType:
484
+ dict.__setitem__(self, type, cvtFn)
485
+ else:
486
+ dict.__setitem__(self, adoType, cvtFn)
487
+
488
+
489
+ # initialize variantConversions dictionary used to convert SQL to Python
490
+ # this is the dictionary of default conversion functions, built by the class above.
491
+ # this becomes a class attribute for the Connection, and that attribute is used
492
+ # to build the list of column conversion functions for the Cursor
493
+ variantConversions = MultiMap(
494
+ {
495
+ adoDateTimeTypes: variantConvertDate,
496
+ adoApproximateNumericTypes: cvtFloat,
497
+ adoExactNumericTypes: cvtDecimal, # use to force decimal rather than unicode
498
+ adoLongTypes: cvtLong,
499
+ adoIntegerTypes: cvtInt,
500
+ adoRowIdTypes: cvtInt,
501
+ adoStringTypes: identity,
502
+ adoBinaryTypes: cvtBuffer,
503
+ adoRemainingTypes: cvtUnusual,
504
+ }
505
+ )
506
+
507
+ # # # # # classes to emulate the result of cursor.fetchxxx() as a sequence of sequences # # # # #
508
+ # "an ENUM of how my low level records are laid out"
509
+ RS_WIN_32, RS_ARRAY, RS_REMOTE = list(range(1, 4))
510
+
511
+
512
+ class SQLrow: # a single database row
513
+ # class to emulate a sequence, so that a column may be retrieved by either number or name
514
+ def __init__(self, rows, index): # "rows" is an _SQLrows object, index is which row
515
+ self.rows = rows # parent 'fetch' container object
516
+ self.index = index # my row number within parent
517
+
518
+ def __getattr__(self, name): # used for row.columnName type of value access
519
+ try:
520
+ return self._getValue(self.rows.columnNames[name.lower()])
521
+ except KeyError:
522
+ raise AttributeError('Unknown column name "{}"'.format(name))
523
+
524
+ def _getValue(self, key): # key must be an integer
525
+ if (
526
+ self.rows.recordset_format == RS_ARRAY
527
+ ): # retrieve from two-dimensional array
528
+ v = self.rows.ado_results[key, self.index]
529
+ elif self.rows.recordset_format == RS_REMOTE:
530
+ v = self.rows.ado_results[self.index][key]
531
+ else: # pywin32 - retrieve from tuple of tuples
532
+ v = self.rows.ado_results[key][self.index]
533
+ if self.rows.converters is NotImplemented:
534
+ return v
535
+ return convert_to_python(v, self.rows.converters[key])
536
+
537
+ def __len__(self):
538
+ return self.rows.numberOfColumns
539
+
540
+ def __getitem__(self, key): # used for row[key] type of value access
541
+ if isinstance(key, int): # normal row[1] designation
542
+ try:
543
+ return self._getValue(key)
544
+ except IndexError:
545
+ raise
546
+ if isinstance(key, slice):
547
+ indices = key.indices(self.rows.numberOfColumns)
548
+ vl = [self._getValue(i) for i in range(*indices)]
549
+ return tuple(vl)
550
+ try:
551
+ return self._getValue(
552
+ self.rows.columnNames[key.lower()]
553
+ ) # extension row[columnName] designation
554
+ except (KeyError, TypeError):
555
+ er, st, tr = sys.exc_info()
556
+ raise er(f'No such key as "{key!r}" in {self!r}').with_traceback(tr)
557
+
558
+ def __iter__(self):
559
+ return iter(self.__next__())
560
+
561
+ def __next__(self):
562
+ for n in range(self.rows.numberOfColumns):
563
+ yield self._getValue(n)
564
+
565
+ def __repr__(self): # create a human readable representation
566
+ taglist = sorted(list(self.rows.columnNames.items()), key=lambda x: x[1])
567
+ s = "<SQLrow={"
568
+ for name, i in taglist:
569
+ s += f"{name}:{self._getValue(i)!r}, "
570
+ return s[:-2] + "}>"
571
+
572
+ def __str__(self): # create a pretty human readable representation
573
+ return str(
574
+ tuple(str(self._getValue(i)) for i in range(self.rows.numberOfColumns))
575
+ )
576
+
577
+ # TO-DO implement pickling an SQLrow directly
578
+ # def __getstate__(self): return self.__dict__
579
+ # def __setstate__(self, d): self.__dict__.update(d)
580
+ # which basically tell pickle to treat your class just like a normal one,
581
+ # taking self.__dict__ as representing the whole of the instance state,
582
+ # despite the existence of the __getattr__.
583
+ # # # #
584
+
585
+
586
+ class SQLrows:
587
+ # class to emulate a sequence for multiple rows using a container object
588
+ def __init__(self, ado_results, numberOfRows, cursor):
589
+ self.ado_results = ado_results # raw result of SQL get
590
+ try:
591
+ self.recordset_format = cursor.recordset_format
592
+ self.numberOfColumns = cursor.numberOfColumns
593
+ self.converters = cursor.converters
594
+ self.columnNames = cursor.columnNames
595
+ except AttributeError:
596
+ self.recordset_format = RS_ARRAY
597
+ self.numberOfColumns = 0
598
+ self.converters = []
599
+ self.columnNames = {}
600
+ self.numberOfRows = numberOfRows
601
+
602
+ def __len__(self):
603
+ return self.numberOfRows
604
+
605
+ def __getitem__(self, item): # used for row or row,column access
606
+ if not self.ado_results:
607
+ return []
608
+ if isinstance(item, slice): # will return a list of row objects
609
+ indices = item.indices(self.numberOfRows)
610
+ return [SQLrow(self, k) for k in range(*indices)]
611
+ elif isinstance(item, tuple) and len(item) == 2:
612
+ # d = some_rowsObject[i,j] will return a datum from a two-dimension address
613
+ i, j = item
614
+ if not isinstance(j, int):
615
+ try:
616
+ j = self.columnNames[j.lower()] # convert named column to numeric
617
+ except KeyError:
618
+ raise KeyError(f"adodbapi: no such column name as {j!r}")
619
+ if self.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
620
+ v = self.ado_results[j, i]
621
+ elif self.recordset_format == RS_REMOTE:
622
+ v = self.ado_results[i][j]
623
+ else: # pywin32 - retrieve from tuple of tuples
624
+ v = self.ado_results[j][i]
625
+ if self.converters is NotImplemented:
626
+ return v
627
+ return convert_to_python(v, self.converters[j])
628
+ else:
629
+ row = SQLrow(self, item) # new row descriptor
630
+ return row
631
+
632
+ def __iter__(self):
633
+ return iter(self.__next__())
634
+
635
+ def __next__(self):
636
+ for n in range(self.numberOfRows):
637
+ row = SQLrow(self, n)
638
+ yield row
639
+ # # # # #
640
+
641
+ # # # # # functions to re-format SQL requests to other paramstyle requirements # # # # # # # # # #
642
+
643
+
644
+ def changeNamedToQmark(
645
+ op,
646
+ ): # convert from 'named' paramstyle to ADO required '?'mark parameters
647
+ outOp = ""
648
+ outparms = []
649
+ chunks = op.split(
650
+ "'"
651
+ ) # quote all literals -- odd numbered list results are literals.
652
+ inQuotes = False
653
+ for chunk in chunks:
654
+ if inQuotes: # this is inside a quote
655
+ if chunk == "": # double apostrophe to quote one apostrophe
656
+ outOp = outOp[:-1] # so take one away
657
+ else:
658
+ outOp += "'" + chunk + "'" # else pass the quoted string as is.
659
+ else: # is SQL code -- look for a :namedParameter
660
+ while chunk: # some SQL string remains
661
+ sp = chunk.split(":", 1)
662
+ outOp += sp[0] # concat the part up to the :
663
+ s = ""
664
+ try:
665
+ chunk = sp[1]
666
+ except IndexError:
667
+ chunk = None
668
+ if chunk: # there was a parameter - parse it out
669
+ i = 0
670
+ c = chunk[0]
671
+ while c.isalnum() or c == "_":
672
+ i += 1
673
+ try:
674
+ c = chunk[i]
675
+ except IndexError:
676
+ break
677
+ s = chunk[:i]
678
+ chunk = chunk[i:]
679
+ if s:
680
+ outparms.append(s) # list the parameters in order
681
+ outOp += "?" # put in the Qmark
682
+ inQuotes = not inQuotes
683
+ return outOp, outparms
684
+
685
+
686
+ def changeFormatToQmark(
687
+ op,
688
+ ): # convert from 'format' paramstyle to ADO required '?'mark parameters
689
+ outOp = ""
690
+ outparams = []
691
+ chunks = op.split(
692
+ "'"
693
+ ) # quote all literals -- odd numbered list results are literals.
694
+ inQuotes = False
695
+ for chunk in chunks:
696
+ if inQuotes:
697
+ if (
698
+ outOp != "" and chunk == ""
699
+ ): # he used a double apostrophe to quote one apostrophe
700
+ outOp = outOp[:-1] # so take one away
701
+ else:
702
+ outOp += "'" + chunk + "'" # else pass the quoted string as is.
703
+ else: # is SQL code -- look for a %s parameter
704
+ if "%(" in chunk: # ugh! pyformat!
705
+ while chunk: # some SQL string remains
706
+ sp = chunk.split("%(", 1)
707
+ outOp += sp[0] # concat the part up to the %
708
+ if len(sp) > 1:
709
+ try:
710
+ s, chunk = sp[1].split(")s", 1) # find the ')s'
711
+ except ValueError:
712
+ raise ProgrammingError(
713
+ 'Pyformat SQL has incorrect format near "%s"' % chunk
714
+ )
715
+ outparams.append(s)
716
+ outOp += "?" # put in the Qmark
717
+ else:
718
+ chunk = None
719
+ else: # proper '%s' format
720
+ sp = chunk.split("%s") # make each %s
721
+ outOp += "?".join(sp) # into ?
722
+ inQuotes = not inQuotes # every other chunk is a quoted string
723
+ return outOp, outparams
python_embeded/Lib/site-packages/adodbapi/is64bit.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """is64bit.Python() --> boolean value of detected Python word size. is64bit.os() --> os build version"""
2
+
3
+ import sys
4
+
5
+
6
+ def Python():
7
+ return sys.maxsize > 2147483647
8
+
9
+
10
+ def os():
11
+ import platform
12
+
13
+ pm = platform.machine()
14
+ if pm != ".." and pm.endswith("64"): # recent 64 bit Python
15
+ return True
16
+ else:
17
+ import os
18
+
19
+ if "PROCESSOR_ARCHITEW6432" in os.environ:
20
+ return True # 32 bit program running on 64 bit Windows
21
+ try:
22
+ return os.environ["PROCESSOR_ARCHITECTURE"].endswith(
23
+ "64"
24
+ ) # 64 bit Windows 64 bit program
25
+ except (IndexError, KeyError):
26
+ pass # not Windows
27
+ try:
28
+ return "64" in platform.architecture()[0] # this often works in Linux
29
+ except:
30
+ return False # is an older version of Python, assume also an older os (best we can guess)
31
+
32
+
33
+ if __name__ == "__main__":
34
+ print("is64bit.Python() =", Python(), "is64bit.os() =", os())
python_embeded/Lib/site-packages/adodbapi/license.txt ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 2.1, February 1999
3
+
4
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
5
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ [This is the first released version of the Lesser GPL. It also counts
10
+ as the successor of the GNU Library Public License, version 2, hence
11
+ the version number 2.1.]
12
+
13
+ Preamble
14
+
15
+ The licenses for most software are designed to take away your
16
+ freedom to share and change it. By contrast, the GNU General Public
17
+ Licenses are intended to guarantee your freedom to share and change
18
+ free software--to make sure the software is free for all its users.
19
+
20
+ This license, the Lesser General Public License, applies to some
21
+ specially designated software packages--typically libraries--of the
22
+ Free Software Foundation and other authors who decide to use it. You
23
+ can use it too, but we suggest you first think carefully about whether
24
+ this license or the ordinary General Public License is the better
25
+ strategy to use in any particular case, based on the explanations below.
26
+
27
+ When we speak of free software, we are referring to freedom of use,
28
+ not price. Our General Public Licenses are designed to make sure that
29
+ you have the freedom to distribute copies of free software (and charge
30
+ for this service if you wish); that you receive source code or can get
31
+ it if you want it; that you can change the software and use pieces of
32
+ it in new free programs; and that you are informed that you can do
33
+ these things.
34
+
35
+ To protect your rights, we need to make restrictions that forbid
36
+ distributors to deny you these rights or to ask you to surrender these
37
+ rights. These restrictions translate to certain responsibilities for
38
+ you if you distribute copies of the library or if you modify it.
39
+
40
+ For example, if you distribute copies of the library, whether gratis
41
+ or for a fee, you must give the recipients all the rights that we gave
42
+ you. You must make sure that they, too, receive or can get the source
43
+ code. If you link other code with the library, you must provide
44
+ complete object files to the recipients, so that they can relink them
45
+ with the library after making changes to the library and recompiling
46
+ it. And you must show them these terms so they know their rights.
47
+
48
+ We protect your rights with a two-step method: (1) we copyright the
49
+ library, and (2) we offer you this license, which gives you legal
50
+ permission to copy, distribute and/or modify the library.
51
+
52
+ To protect each distributor, we want to make it very clear that
53
+ there is no warranty for the free library. Also, if the library is
54
+ modified by someone else and passed on, the recipients should know
55
+ that what they have is not the original version, so that the original
56
+ author's reputation will not be affected by problems that might be
57
+ introduced by others.
58
+
59
+
60
+
61
+ Finally, software patents pose a constant threat to the existence of
62
+ any free program. We wish to make sure that a company cannot
63
+ effectively restrict the users of a free program by obtaining a
64
+ restrictive license from a patent holder. Therefore, we insist that
65
+ any patent license obtained for a version of the library must be
66
+ consistent with the full freedom of use specified in this license.
67
+
68
+ Most GNU software, including some libraries, is covered by the
69
+ ordinary GNU General Public License. This license, the GNU Lesser
70
+ General Public License, applies to certain designated libraries, and
71
+ is quite different from the ordinary General Public License. We use
72
+ this license for certain libraries in order to permit linking those
73
+ libraries into non-free programs.
74
+
75
+ When a program is linked with a library, whether statically or using
76
+ a shared library, the combination of the two is legally speaking a
77
+ combined work, a derivative of the original library. The ordinary
78
+ General Public License therefore permits such linking only if the
79
+ entire combination fits its criteria of freedom. The Lesser General
80
+ Public License permits more lax criteria for linking other code with
81
+ the library.
82
+
83
+ We call this license the "Lesser" General Public License because it
84
+ does Less to protect the user's freedom than the ordinary General
85
+ Public License. It also provides other free software developers Less
86
+ of an advantage over competing non-free programs. These disadvantages
87
+ are the reason we use the ordinary General Public License for many
88
+ libraries. However, the Lesser license provides advantages in certain
89
+ special circumstances.
90
+
91
+ For example, on rare occasions, there may be a special need to
92
+ encourage the widest possible use of a certain library, so that it becomes
93
+ a de-facto standard. To achieve this, non-free programs must be
94
+ allowed to use the library. A more frequent case is that a free
95
+ library does the same job as widely used non-free libraries. In this
96
+ case, there is little to gain by limiting the free library to free
97
+ software only, so we use the Lesser General Public License.
98
+
99
+ In other cases, permission to use a particular library in non-free
100
+ programs enables a greater number of people to use a large body of
101
+ free software. For example, permission to use the GNU C Library in
102
+ non-free programs enables many more people to use the whole GNU
103
+ operating system, as well as its variant, the GNU/Linux operating
104
+ system.
105
+
106
+ Although the Lesser General Public License is Less protective of the
107
+ users' freedom, it does ensure that the user of a program that is
108
+ linked with the Library has the freedom and the wherewithal to run
109
+ that program using a modified version of the Library.
110
+
111
+ The precise terms and conditions for copying, distribution and
112
+ modification follow. Pay close attention to the difference between a
113
+ "work based on the library" and a "work that uses the library". The
114
+ former contains code derived from the library, whereas the latter must
115
+ be combined with the library in order to run.
116
+
117
+
118
+
119
+ GNU LESSER GENERAL PUBLIC LICENSE
120
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
121
+
122
+ 0. This License Agreement applies to any software library or other
123
+ program which contains a notice placed by the copyright holder or
124
+ other authorized party saying it may be distributed under the terms of
125
+ this Lesser General Public License (also called "this License").
126
+ Each licensee is addressed as "you".
127
+
128
+ A "library" means a collection of software functions and/or data
129
+ prepared so as to be conveniently linked with application programs
130
+ (which use some of those functions and data) to form executables.
131
+
132
+ The "Library", below, refers to any such software library or work
133
+ which has been distributed under these terms. A "work based on the
134
+ Library" means either the Library or any derivative work under
135
+ copyright law: that is to say, a work containing the Library or a
136
+ portion of it, either verbatim or with modifications and/or translated
137
+ straightforwardly into another language. (Hereinafter, translation is
138
+ included without limitation in the term "modification".)
139
+
140
+ "Source code" for a work means the preferred form of the work for
141
+ making modifications to it. For a library, complete source code means
142
+ all the source code for all modules it contains, plus any associated
143
+ interface definition files, plus the scripts used to control compilation
144
+ and installation of the library.
145
+
146
+ Activities other than copying, distribution and modification are not
147
+ covered by this License; they are outside its scope. The act of
148
+ running a program using the Library is not restricted, and output from
149
+ such a program is covered only if its contents constitute a work based
150
+ on the Library (independent of the use of the Library in a tool for
151
+ writing it). Whether that is true depends on what the Library does
152
+ and what the program that uses the Library does.
153
+
154
+ 1. You may copy and distribute verbatim copies of the Library's
155
+ complete source code as you receive it, in any medium, provided that
156
+ you conspicuously and appropriately publish on each copy an
157
+ appropriate copyright notice and disclaimer of warranty; keep intact
158
+ all the notices that refer to this License and to the absence of any
159
+ warranty; and distribute a copy of this License along with the
160
+ Library.
161
+ You may charge a fee for the physical act of transferring a copy,
162
+ and you may at your option offer warranty protection in exchange for a
163
+ fee.
164
+
165
+ 2. You may modify your copy or copies of the Library or any portion
166
+ of it, thus forming a work based on the Library, and copy and
167
+ distribute such modifications or work under the terms of Section 1
168
+ above, provided that you also meet all of these conditions:
169
+
170
+ a) The modified work must itself be a software library.
171
+
172
+ b) You must cause the files modified to carry prominent notices
173
+ stating that you changed the files and the date of any change.
174
+
175
+ c) You must cause the whole of the work to be licensed at no
176
+ charge to all third parties under the terms of this License.
177
+
178
+ d) If a facility in the modified Library refers to a function or a
179
+ table of data to be supplied by an application program that uses
180
+ the facility, other than as an argument passed when the facility
181
+ is invoked, then you must make a good faith effort to ensure that,
182
+ in the event an application does not supply such function or
183
+ table, the facility still operates, and performs whatever part of
184
+ its purpose remains meaningful.
185
+
186
+ (For example, a function in a library to compute square roots has
187
+ a purpose that is entirely well-defined independent of the
188
+ application. Therefore, Subsection 2d requires that any
189
+ application-supplied function or table used by this function must
190
+ be optional: if the application does not supply it, the square
191
+ root function must still compute square roots.)
192
+
193
+ These requirements apply to the modified work as a whole. If
194
+ identifiable sections of that work are not derived from the Library,
195
+ and can be reasonably considered independent and separate works in
196
+ themselves, then this License, and its terms, do not apply to those
197
+ sections when you distribute them as separate works. But when you
198
+ distribute the same sections as part of a whole which is a work based
199
+ on the Library, the distribution of the whole must be on the terms of
200
+ this License, whose permissions for other licensees extend to the
201
+ entire whole, and thus to each and every part regardless of who wrote
202
+ it.
203
+
204
+ Thus, it is not the intent of this section to claim rights or contest
205
+ your rights to work written entirely by you; rather, the intent is to
206
+ exercise the right to control the distribution of derivative or
207
+ collective works based on the Library.
208
+
209
+ In addition, mere aggregation of another work not based on the Library
210
+ with the Library (or with a work based on the Library) on a volume of
211
+ a storage or distribution medium does not bring the other work under
212
+ the scope of this License.
213
+
214
+ 3. You may opt to apply the terms of the ordinary GNU General Public
215
+ License instead of this License to a given copy of the Library. To do
216
+ this, you must alter all the notices that refer to this License, so
217
+ that they refer to the ordinary GNU General Public License, version 2,
218
+ instead of to this License. (If a newer version than version 2 of the
219
+ ordinary GNU General Public License has appeared, then you can specify
220
+ that version instead if you wish.) Do not make any other change in
221
+ these notices.
222
+
223
+ Once this change is made in a given copy, it is irreversible for
224
+ that copy, so the ordinary GNU General Public License applies to all
225
+ subsequent copies and derivative works made from that copy.
226
+
227
+ This option is useful when you wish to copy part of the code of
228
+ the Library into a program that is not a library.
229
+
230
+ 4. You may copy and distribute the Library (or a portion or
231
+ derivative of it, under Section 2) in object code or executable form
232
+ under the terms of Sections 1 and 2 above provided that you accompany
233
+ it with the complete corresponding machine-readable source code, which
234
+ must be distributed under the terms of Sections 1 and 2 above on a
235
+ medium customarily used for software interchange.
236
+
237
+ If distribution of object code is made by offering access to copy
238
+ from a designated place, then offering equivalent access to copy the
239
+ source code from the same place satisfies the requirement to
240
+ distribute the source code, even though third parties are not
241
+ compelled to copy the source along with the object code.
242
+
243
+ 5. A program that contains no derivative of any portion of the
244
+ Library, but is designed to work with the Library by being compiled or
245
+ linked with it, is called a "work that uses the Library". Such a
246
+ work, in isolation, is not a derivative work of the Library, and
247
+ therefore falls outside the scope of this License.
248
+
249
+ However, linking a "work that uses the Library" with the Library
250
+ creates an executable that is a derivative of the Library (because it
251
+ contains portions of the Library), rather than a "work that uses the
252
+ library". The executable is therefore covered by this License.
253
+ Section 6 states terms for distribution of such executables.
254
+
255
+ When a "work that uses the Library" uses material from a header file
256
+ that is part of the Library, the object code for the work may be a
257
+ derivative work of the Library even though the source code is not.
258
+ Whether this is true is especially significant if the work can be
259
+ linked without the Library, or if the work is itself a library. The
260
+ threshold for this to be true is not precisely defined by law.
261
+
262
+ If such an object file uses only numerical parameters, data
263
+ structure layouts and accessors, and small macros and small inline
264
+ functions (ten lines or less in length), then the use of the object
265
+ file is unrestricted, regardless of whether it is legally a derivative
266
+ work. (Executables containing this object code plus portions of the
267
+ Library will still fall under Section 6.)
268
+
269
+ Otherwise, if the work is a derivative of the Library, you may
270
+ distribute the object code for the work under the terms of Section 6.
271
+ Any executables containing that work also fall under Section 6,
272
+ whether or not they are linked directly with the Library itself.
273
+
274
+ 6. As an exception to the Sections above, you may also combine or
275
+ link a "work that uses the Library" with the Library to produce a
276
+ work containing portions of the Library, and distribute that work
277
+ under terms of your choice, provided that the terms permit
278
+ modification of the work for the customer's own use and reverse
279
+ engineering for debugging such modifications.
280
+
281
+ You must give prominent notice with each copy of the work that the
282
+ Library is used in it and that the Library and its use are covered by
283
+ this License. You must supply a copy of this License. If the work
284
+ during execution displays copyright notices, you must include the
285
+ copyright notice for the Library among them, as well as a reference
286
+ directing the user to the copy of this License. Also, you must do one
287
+ of these things:
288
+
289
+ a) Accompany the work with the complete corresponding
290
+ machine-readable source code for the Library including whatever
291
+ changes were used in the work (which must be distributed under
292
+ Sections 1 and 2 above); and, if the work is an executable linked
293
+ with the Library, with the complete machine-readable "work that
294
+ uses the Library", as object code and/or source code, so that the
295
+ user can modify the Library and then relink to produce a modified
296
+ executable containing the modified Library. (It is understood
297
+ that the user who changes the contents of definitions files in the
298
+ Library will not necessarily be able to recompile the application
299
+ to use the modified definitions.)
300
+
301
+ b) Use a suitable shared library mechanism for linking with the
302
+ Library. A suitable mechanism is one that (1) uses at run time a
303
+ copy of the library already present on the user's computer system,
304
+ rather than copying library functions into the executable, and (2)
305
+ will operate properly with a modified version of the library, if
306
+ the user installs one, as long as the modified version is
307
+ interface-compatible with the version that the work was made with.
308
+
309
+ c) Accompany the work with a written offer, valid for at
310
+ least three years, to give the same user the materials
311
+ specified in Subsection 6a, above, for a charge no more
312
+ than the cost of performing this distribution.
313
+
314
+ d) If distribution of the work is made by offering access to copy
315
+ from a designated place, offer equivalent access to copy the above
316
+ specified materials from the same place.
317
+
318
+ e) Verify that the user has already received a copy of these
319
+ materials or that you have already sent this user a copy.
320
+
321
+ For an executable, the required form of the "work that uses the
322
+ Library" must include any data and utility programs needed for
323
+ reproducing the executable from it. However, as a special exception,
324
+ the materials to be distributed need not include anything that is
325
+ normally distributed (in either source or binary form) with the major
326
+ components (compiler, kernel, and so on) of the operating system on
327
+ which the executable runs, unless that component itself accompanies
328
+ the executable.
329
+
330
+ It may happen that this requirement contradicts the license
331
+ restrictions of other proprietary libraries that do not normally
332
+ accompany the operating system. Such a contradiction means you cannot
333
+ use both them and the Library together in an executable that you
334
+ distribute.
335
+
336
+ 7. You may place library facilities that are a work based on the
337
+ Library side-by-side in a single library together with other library
338
+ facilities not covered by this License, and distribute such a combined
339
+ library, provided that the separate distribution of the work based on
340
+ the Library and of the other library facilities is otherwise
341
+ permitted, and provided that you do these two things:
342
+
343
+ a) Accompany the combined library with a copy of the same work
344
+ based on the Library, uncombined with any other library
345
+ facilities. This must be distributed under the terms of the
346
+ Sections above.
347
+
348
+ b) Give prominent notice with the combined library of the fact
349
+ that part of it is a work based on the Library, and explaining
350
+ where to find the accompanying uncombined form of the same work.
351
+
352
+ 8. You may not copy, modify, sublicense, link with, or distribute
353
+ the Library except as expressly provided under this License. Any
354
+ attempt otherwise to copy, modify, sublicense, link with, or
355
+ distribute the Library is void, and will automatically terminate your
356
+ rights under this License. However, parties who have received copies,
357
+ or rights, from you under this License will not have their licenses
358
+ terminated so long as such parties remain in full compliance.
359
+
360
+ 9. You are not required to accept this License, since you have not
361
+ signed it. However, nothing else grants you permission to modify or
362
+ distribute the Library or its derivative works. These actions are
363
+ prohibited by law if you do not accept this License. Therefore, by
364
+ modifying or distributing the Library (or any work based on the
365
+ Library), you indicate your acceptance of this License to do so, and
366
+ all its terms and conditions for copying, distributing or modifying
367
+ the Library or works based on it.
368
+
369
+ 10. Each time you redistribute the Library (or any work based on the
370
+ Library), the recipient automatically receives a license from the
371
+ original licensor to copy, distribute, link with or modify the Library
372
+ subject to these terms and conditions. You may not impose any further
373
+ restrictions on the recipients' exercise of the rights granted herein.
374
+ You are not responsible for enforcing compliance by third parties with
375
+ this License.
376
+
377
+ 11. If, as a consequence of a court judgment or allegation of patent
378
+ infringement or for any other reason (not limited to patent issues),
379
+ conditions are imposed on you (whether by court order, agreement or
380
+ otherwise) that contradict the conditions of this License, they do not
381
+ excuse you from the conditions of this License. If you cannot
382
+ distribute so as to satisfy simultaneously your obligations under this
383
+ License and any other pertinent obligations, then as a consequence you
384
+ may not distribute the Library at all. For example, if a patent
385
+ license would not permit royalty-free redistribution of the Library by
386
+ all those who receive copies directly or indirectly through you, then
387
+ the only way you could satisfy both it and this License would be to
388
+ refrain entirely from distribution of the Library.
389
+
390
+ If any portion of this section is held invalid or unenforceable under any
391
+ particular circumstance, the balance of the section is intended to apply,
392
+ and the section as a whole is intended to apply in other circumstances.
393
+
394
+ It is not the purpose of this section to induce you to infringe any
395
+ patents or other property right claims or to contest validity of any
396
+ such claims; this section has the sole purpose of protecting the
397
+ integrity of the free software distribution system which is
398
+ implemented by public license practices. Many people have made
399
+ generous contributions to the wide range of software distributed
400
+ through that system in reliance on consistent application of that
401
+ system; it is up to the author/donor to decide if he or she is willing
402
+ to distribute software through any other system and a licensee cannot
403
+ impose that choice.
404
+
405
+ This section is intended to make thoroughly clear what is believed to
406
+ be a consequence of the rest of this License.
407
+
408
+ 12. If the distribution and/or use of the Library is restricted in
409
+ certain countries either by patents or by copyrighted interfaces, the
410
+ original copyright holder who places the Library under this License may add
411
+ an explicit geographical distribution limitation excluding those countries,
412
+ so that distribution is permitted only in or among countries not thus
413
+ excluded. In such case, this License incorporates the limitation as if
414
+ written in the body of this License.
415
+
416
+ 13. The Free Software Foundation may publish revised and/or new
417
+ versions of the Lesser General Public License from time to time.
418
+ Such new versions will be similar in spirit to the present version,
419
+ but may differ in detail to address new problems or concerns.
420
+
421
+ Each version is given a distinguishing version number. If the Library
422
+ specifies a version number of this License which applies to it and
423
+ "any later version", you have the option of following the terms and
424
+ conditions either of that version or of any later version published by
425
+ the Free Software Foundation. If the Library does not specify a
426
+ license version number, you may choose any version ever published by
427
+ the Free Software Foundation.
428
+
429
+ 14. If you wish to incorporate parts of the Library into other free
430
+ programs whose distribution conditions are incompatible with these,
431
+ write to the author to ask for permission. For software which is
432
+ copyrighted by the Free Software Foundation, write to the Free
433
+ Software Foundation; we sometimes make exceptions for this. Our
434
+ decision will be guided by the two goals of preserving the free status
435
+ of all derivatives of our free software and of promoting the sharing
436
+ and reuse of software generally.
437
+
438
+ NO WARRANTY
439
+
440
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
441
+ WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
442
+ EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
443
+ OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
444
+ KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
445
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
446
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
447
+ LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
448
+ THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
449
+
450
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
451
+ WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
452
+ AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
453
+ FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
454
+ CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
455
+ LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
456
+ RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
457
+ FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
458
+ SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
459
+ DAMAGES.
460
+
461
+ END OF TERMS AND CONDITIONS
462
+
463
+ How to Apply These Terms to Your New Libraries
464
+
465
+ If you develop a new library, and you want it to be of the greatest
466
+ possible use to the public, we recommend making it free software that
467
+ everyone can redistribute and change. You can do so by permitting
468
+ redistribution under these terms (or, alternatively, under the terms of the
469
+ ordinary General Public License).
470
+
471
+ To apply these terms, attach the following notices to the library. It is
472
+ safest to attach them to the start of each source file to most effectively
473
+ convey the exclusion of warranty; and each file should have at least the
474
+ "copyright" line and a pointer to where the full notice is found.
475
+
476
+ <one line to give the library's name and a brief idea of what it does.>
477
+ Copyright (C) <year> <name of author>
478
+
479
+ This library is free software; you can redistribute it and/or
480
+ modify it under the terms of the GNU Lesser General Public
481
+ License as published by the Free Software Foundation; either
482
+ version 2.1 of the License, or (at your option) any later version.
483
+
484
+ This library is distributed in the hope that it will be useful,
485
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
486
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
487
+ Lesser General Public License for more details.
488
+
489
+ You should have received a copy of the GNU Lesser General Public
490
+ License along with this library; if not, write to the Free Software
491
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
492
+
493
+ Also add information on how to contact you by electronic and paper mail.
494
+
495
+ You should also get your employer (if you work as a programmer) or your
496
+ school, if any, to sign a "copyright disclaimer" for the library, if
497
+ necessary. Here is a sample; alter the names:
498
+
499
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
500
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
501
+
502
+ <signature of Ty Coon>, 1 April 1990
503
+ Ty Coon, President of Vice
504
+
505
+ That's all there is to it!
python_embeded/Lib/site-packages/adodbapi/process_connect_string.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """a clumsy attempt at a macro language to let the programmer execute code on the server (ex: determine 64bit)"""
2
+
3
+ from . import is64bit
4
+
5
+
6
+ def macro_call(macro_name, args, kwargs):
7
+ """allow the programmer to perform limited processing on the server by passing macro names and args
8
+
9
+ :new_key - the key name the macro will create
10
+ :args[0] - macro name
11
+ :args[1:] - any arguments
12
+ :code - the value of the keyword item
13
+ :kwargs - the connection keyword dictionary. ??key has been removed
14
+ --> the value to put in for kwargs['name'] = value
15
+ """
16
+ if isinstance(args, (str, str)):
17
+ args = [
18
+ args
19
+ ] # the user forgot to pass a sequence, so make a string into args[0]
20
+ new_key = args[0]
21
+ try:
22
+ if macro_name == "is64bit":
23
+ if is64bit.Python(): # if on 64 bit Python
24
+ return new_key, args[1] # return first argument
25
+ else:
26
+ try:
27
+ return new_key, args[2] # else return second argument (if defined)
28
+ except IndexError:
29
+ return new_key, "" # else return blank
30
+
31
+ elif (
32
+ macro_name == "getuser"
33
+ ): # get the name of the user the server is logged in under
34
+ if not new_key in kwargs:
35
+ import getpass
36
+
37
+ return new_key, getpass.getuser()
38
+
39
+ elif macro_name == "getnode": # get the name of the computer running the server
40
+ import platform
41
+
42
+ try:
43
+ return new_key, args[1] % platform.node()
44
+ except IndexError:
45
+ return new_key, platform.node()
46
+
47
+ elif macro_name == "getenv": # expand the server's environment variable args[1]
48
+ import os
49
+
50
+ try:
51
+ dflt = args[2] # if not found, default from args[2]
52
+ except IndexError: # or blank
53
+ dflt = ""
54
+ return new_key, os.environ.get(args[1], dflt)
55
+
56
+ elif macro_name == "auto_security":
57
+ if (
58
+ not "user" in kwargs or not kwargs["user"]
59
+ ): # missing, blank, or Null username
60
+ return new_key, "Integrated Security=SSPI"
61
+ return new_key, "User ID=%(user)s; Password=%(password)s" % kwargs
62
+
63
+ elif (
64
+ macro_name == "find_temp_test_path"
65
+ ): # helper function for testing ado operation -- undocumented
66
+ import os
67
+ import tempfile
68
+
69
+ return new_key, os.path.join(
70
+ tempfile.gettempdir(), "adodbapi_test", args[1]
71
+ )
72
+
73
+ raise ValueError(f"Unknown connect string macro={macro_name}")
74
+ except:
75
+ raise ValueError(f"Error in macro processing {macro_name} {args!r}")
76
+
77
+
78
+ def process(
79
+ args, kwargs, expand_macros=False
80
+ ): # --> connection string with keyword arguments processed.
81
+ """attempts to inject arguments into a connection string using Python "%" operator for strings
82
+
83
+ co: adodbapi connection object
84
+ args: positional parameters from the .connect() call
85
+ kvargs: keyword arguments from the .connect() call
86
+ """
87
+ try:
88
+ dsn = args[0]
89
+ except IndexError:
90
+ dsn = None
91
+ # as a convenience the first argument may be django settings
92
+ if isinstance(dsn, dict):
93
+ kwargs.update(dsn)
94
+ # the connection string is passed to the connection as part of the keyword dictionary
95
+ elif dsn:
96
+ kwargs["connection_string"] = dsn
97
+ try:
98
+ a1 = args[1]
99
+ except IndexError:
100
+ a1 = None
101
+ # historically, the second positional argument might be a timeout value
102
+ if isinstance(a1, int):
103
+ kwargs["timeout"] = a1
104
+ # if the second positional argument is a string, then it is user
105
+ elif isinstance(a1, str):
106
+ kwargs["user"] = a1
107
+ # if the second positional argument is a dictionary, use it as keyword arguments, too
108
+ elif isinstance(a1, dict):
109
+ kwargs.update(a1)
110
+ try:
111
+ kwargs["password"] = args[2] # the third positional argument is password
112
+ kwargs["host"] = args[3] # the fourth positional argument is host name
113
+ kwargs["database"] = args[4] # the fifth positional argument is database name
114
+ except IndexError:
115
+ pass
116
+
117
+ # make sure connection string is defined somehow
118
+ if not "connection_string" in kwargs:
119
+ try: # perhaps 'dsn' was defined
120
+ kwargs["connection_string"] = kwargs["dsn"]
121
+ except KeyError:
122
+ try: # as a last effort, use the "host" keyword
123
+ kwargs["connection_string"] = kwargs["host"]
124
+ except KeyError:
125
+ raise TypeError("Must define 'connection_string' for ado connections")
126
+ if expand_macros:
127
+ for kwarg in list(kwargs.keys()):
128
+ if kwarg.startswith("macro_"): # If a key defines a macro
129
+ macro_name = kwarg[6:] # name without the "macro_"
130
+ macro_code = kwargs.pop(
131
+ kwarg
132
+ ) # we remove the macro_key and get the code to execute
133
+ new_key, rslt = macro_call(
134
+ macro_name, macro_code, kwargs
135
+ ) # run the code in the local context
136
+ kwargs[new_key] = rslt # put the result back in the keywords dict
137
+ return kwargs
python_embeded/Lib/site-packages/adodbapi/readme.txt ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Project
2
+ -------
3
+ adodbapi
4
+
5
+ A Python DB-API 2.0 (PEP-249) module that makes it easy to use Microsoft ADO
6
+ for connecting with databases and other data sources using CPython.
7
+
8
+ Home page: <https://sourceforge.net/projects/adodbapi>
9
+
10
+ Features:
11
+ * 100% DB-API 2.0 (PEP-249) compliant (including most extensions and recommendations).
12
+ * Includes pyunit testcases that describe how to use the module.
13
+ * Fully implemented in Python. -- runs in current versions of Python 3
14
+ * Licensed under the LGPL license, which means that it can be used freely even in commercial programs subject to certain restrictions.
15
+ * The user can choose between paramstyles: 'qmark' 'named' 'format' 'pyformat' 'dynamic'
16
+ * Supports data retrieval by column name e.g.:
17
+ for row in myCurser.execute("select name,age from students"):
18
+ print("Student", row.name, "is", row.age, "years old.")
19
+ * Supports user-definable system-to-Python data conversion functions (selected by ADO data type, or by column)
20
+
21
+ Prerequisites:
22
+ * C Python 3.6 or higher
23
+ and pywin32 (Mark Hammond's python for windows extensions.)
24
+
25
+ Installation:
26
+ * (C-Python on Windows): Install pywin32 (`python -m pip install pywin32`) which includes adodbapi.
27
+ * (IronPython on Windows): Download adodbapi from https://sourceforge.net/projects/adodbapi/ . Unpack the zip.
28
+
29
+ NOTE: ...........
30
+ If you do not like the new default operation of returning Numeric columns as decimal.Decimal,
31
+ you can select other options by the user defined conversion feature.
32
+ Try:
33
+ adodbapi.apibase.variantConversions[adodbapi.ado_consts.adNumeric] = adodbapi.apibase.cvtString
34
+ or:
35
+ adodbapi.apibase.variantConversions[adodbapi.ado_consts.adNumeric] = adodbapi.apibase.cvtFloat
36
+ or:
37
+ adodbapi.apibase.variantConversions[adodbapi.ado_consts.adNumeric] = write_your_own_conversion_function
38
+ ............
39
+ notes for 2.6.2:
40
+ The definitive source has been moved to https://github.com/mhammond/pywin32/tree/main/adodbapi.
41
+ Remote has proven too hard to configure and test with Pyro4. I am moving it to unsupported status
42
+ until I can change to a different connection method.
43
+ what's new in version 2.6
44
+ A cursor.prepare() method and support for prepared SQL statements.
45
+ Lots of refactoring, especially of the Remote and Server modules (still to be treated as Beta code).
46
+ The quick start document 'quick_reference.odt' will export as a nice-looking pdf.
47
+ Added paramstyles 'pyformat' and 'dynamic'. If your 'paramstyle' is 'named' you _must_ pass a dictionary of
48
+ parameters to your .execute() method. If your 'paramstyle' is 'format' 'pyformat' or 'dynamic', you _may_
49
+ pass a dictionary of parameters -- provided your SQL operation string is formatted correctly.
50
+
51
+ what's new in version 2.5
52
+ Remote module: (works on Linux!) allows a Windows computer to serve ADO databases via PyRO
53
+ Server module: PyRO server for ADO. Run using a command like= C:>python -m adodbapi.server
54
+ (server has simple connection string macros: is64bit, getuser, sql_provider, auto_security)
55
+ Brief documentation included. See adodbapi/examples folder adodbapi.rtf
56
+ New connection method conn.get_table_names() --> list of names of tables in database
57
+
58
+ Vastly refactored. Data conversion things have been moved to the new adodbapi.apibase module.
59
+ Many former module-level attributes are now class attributes. (Should be more thread-safe)
60
+ Connection objects are now context managers for transactions and will commit or rollback.
61
+ Cursor objects are context managers and will automatically close themselves.
62
+ Autocommit can be switched on and off.
63
+ Keyword and positional arguments on the connect() method work as documented in PEP 249.
64
+ Keyword arguments from the connect call can be formatted into the connection string.
65
+ New keyword arguments defined, such as: autocommit, paramstyle, remote_proxy, remote_port.
66
+ *** Breaking change: variantConversion lookups are simplified: the following will raise KeyError:
67
+ oldconverter=adodbapi.variantConversions[adodbapi.adoStringTypes]
68
+ Refactor as: oldconverter=adodbapi.variantConversions[adodbapi.adoStringTypes[0]]
69
+
70
+ License
71
+ -------
72
+ LGPL, see https://opensource.org/license/lgpl-2-1
73
+
74
+ Documentation
75
+ -------------
76
+
77
+ Look at:
78
+ - `adodbapi/quick_reference.md`
79
+ - https://wiki.python.org/moin/DatabaseProgramming#The_DB-API
80
+ - read the examples in adodbapi/examples
81
+ - and the test cases in `adodbapi/test directory`
82
+
83
+ Mailing lists
84
+ -------------
85
+ The adodbapi mailing lists have been deactivated. Submit comments to the
86
+ pywin32 mailing lists.
87
+ -- the bug tracker on sourceforge.net/projects/adodbapi may be checked, (infrequently).
88
+ -- please use: https://github.com/mhammond/pywin32/issues
python_embeded/Lib/site-packages/adodbapi/schema_table.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """call using an open ADO connection --> list of table names"""
2
+
3
+ from . import adodbapi
4
+
5
+
6
+ def names(connection_object):
7
+ ado = connection_object.adoConn
8
+ schema = ado.OpenSchema(20) # constant = adSchemaTables
9
+
10
+ tables = []
11
+ while not schema.EOF:
12
+ name = adodbapi.getIndexedValue(schema.Fields, "TABLE_NAME").Value
13
+ tables.append(name)
14
+ schema.MoveNext()
15
+ del schema
16
+ return tables
python_embeded/Lib/site-packages/adodbapi/setup.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """adodbapi -- a pure Python PEP 249 DB-API package using Microsoft ADO
2
+
3
+ Adodbapi can be run on CPython 3.5 and later.
4
+ """
5
+
6
+ NAME = "adodbapi"
7
+ MAINTAINER = "Vernon Cole"
8
+ MAINTAINER_EMAIL = "vernondcole@gmail.com"
9
+ DESCRIPTION = (
10
+ """A pure Python package implementing PEP 249 DB-API using Microsoft ADO."""
11
+ )
12
+ URL = "https://sourceforge.net/projects/adodbapi"
13
+ LICENSE = "LGPL"
14
+ CLASSIFIERS = [
15
+ "Development Status :: 5 - Production/Stable",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
18
+ "Operating System :: Microsoft :: Windows",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: SQL",
23
+ "Topic :: Software Development",
24
+ "Topic :: Software Development :: Libraries :: Python Modules",
25
+ "Topic :: Database",
26
+ ]
27
+ AUTHOR = "Henrik Ekelund, Vernon Cole, et.al."
28
+ AUTHOR_EMAIL = "vernondcole@gmail.com"
29
+ PLATFORMS = ["Windows", "Linux"]
30
+
31
+ VERSION = None # in case searching for version fails
32
+ a = open("adodbapi.py") # find the version string in the source code
33
+ for line in a:
34
+ if "__version__" in line:
35
+ VERSION = line.split("'")[1] # pyright: ignore[reportConstantRedefinition]
36
+ print('adodbapi version="%s"' % VERSION)
37
+ break
38
+ a.close()
39
+
40
+
41
+ def setup_package():
42
+ from setuptools import setup
43
+ from setuptools.command.build_py import build_py
44
+
45
+ setup(
46
+ cmdclass={"build_py": build_py},
47
+ name=NAME,
48
+ maintainer=MAINTAINER,
49
+ maintainer_email=MAINTAINER_EMAIL,
50
+ description=DESCRIPTION,
51
+ url=URL,
52
+ keywords="database ado odbc dbapi db-api Microsoft SQL",
53
+ ## download_url=DOWNLOAD_URL,
54
+ long_description=open("README.txt").read(),
55
+ license=LICENSE,
56
+ classifiers=CLASSIFIERS,
57
+ author=AUTHOR,
58
+ author_email=AUTHOR_EMAIL,
59
+ platforms=PLATFORMS,
60
+ version=VERSION,
61
+ package_dir={"adodbapi": ""},
62
+ packages=["adodbapi"],
63
+ )
64
+ return
65
+
66
+
67
+ if __name__ == "__main__":
68
+ setup_package()