jasonfan commited on
Commit
ad9e351
·
verified ·
1 Parent(s): c2ad5f5

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. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/INSTALLER +1 -0
  2. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/LICENCE +49 -0
  3. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/METADATA +1594 -0
  4. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/RECORD +75 -0
  5. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/REQUESTED +0 -0
  6. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/WHEEL +5 -0
  7. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/entry_points.txt +2 -0
  8. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/top_level.txt +1 -0
  9. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_main.py +9 -0
  10. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_monitor.py +95 -0
  11. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm.py +9 -0
  12. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm_gui.py +9 -0
  13. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm_notebook.py +9 -0
  14. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm_pandas.py +24 -0
  15. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_utils.py +11 -0
  16. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/asyncio.py +93 -0
  17. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/auto.py +40 -0
  18. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/autonotebook.py +29 -0
  19. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/cli.py +324 -0
  20. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/completion.sh +19 -0
  21. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/__init__.py +92 -0
  22. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/bells.py +26 -0
  23. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/concurrent.py +105 -0
  24. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/discord.py +156 -0
  25. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/itertools.py +35 -0
  26. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/logging.py +126 -0
  27. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/slack.py +120 -0
  28. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/telegram.py +153 -0
  29. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/utils_worker.py +38 -0
  30. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/dask.py +44 -0
  31. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/gui.py +179 -0
  32. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/keras.py +122 -0
  33. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/notebook.py +317 -0
  34. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/rich.py +151 -0
  35. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/std.py +1524 -0
  36. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/tk.py +196 -0
  37. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/tqdm.1 +314 -0
  38. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/utils.py +399 -0
  39. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/version.py +9 -0
  40. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/__init__.py +967 -0
  41. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/activations.py +324 -0
  42. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/activations_tf.py +147 -0
  43. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/audio_utils.py +1224 -0
  44. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/cache_utils.py +1516 -0
  45. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/__init__.py +27 -0
  46. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/add_fast_image_processor.py +530 -0
  47. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/add_new_model_like.py +783 -0
  48. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/chat.py +753 -0
  49. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/convert.py +165 -0
  50. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/download.py +56 -0
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/LICENCE ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `tqdm` is a product of collaborative work.
2
+ Unless otherwise stated, all authors (see commit logs) retain copyright
3
+ for their respective work, and release the work under the MIT licence
4
+ (text below).
5
+
6
+ Exceptions or notable authors are listed below
7
+ in reverse chronological order:
8
+
9
+ * files: *
10
+ MPL-2.0 2015-2024 (c) Casper da Costa-Luis
11
+ [casperdcl](https://github.com/casperdcl).
12
+ * files: tqdm/_tqdm.py
13
+ MIT 2016 (c) [PR #96] on behalf of Google Inc.
14
+ * files: tqdm/_tqdm.py README.rst .gitignore
15
+ MIT 2013 (c) Noam Yorav-Raphael, original author.
16
+
17
+ [PR #96]: https://github.com/tqdm/tqdm/pull/96
18
+
19
+
20
+ Mozilla Public Licence (MPL) v. 2.0 - Exhibit A
21
+ -----------------------------------------------
22
+
23
+ This Source Code Form is subject to the terms of the
24
+ Mozilla Public License, v. 2.0.
25
+ If a copy of the MPL was not distributed with this project,
26
+ You can obtain one at https://mozilla.org/MPL/2.0/.
27
+
28
+
29
+ MIT License (MIT)
30
+ -----------------
31
+
32
+ Copyright (c) 2013 noamraph
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
35
+ this software and associated documentation files (the "Software"), to deal in
36
+ the Software without restriction, including without limitation the rights to
37
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
38
+ the Software, and to permit persons to whom the Software is furnished to do so,
39
+ subject to the following conditions:
40
+
41
+ The above copyright notice and this permission notice shall be included in all
42
+ copies or substantial portions of the Software.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
46
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
47
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
48
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
49
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/METADATA ADDED
@@ -0,0 +1,1594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: tqdm
3
+ Version: 4.67.1
4
+ Summary: Fast, Extensible Progress Meter
5
+ Maintainer-email: tqdm developers <devs@tqdm.ml>
6
+ License: MPL-2.0 AND MIT
7
+ Project-URL: homepage, https://tqdm.github.io
8
+ Project-URL: repository, https://github.com/tqdm/tqdm
9
+ Project-URL: changelog, https://tqdm.github.io/releases
10
+ Project-URL: wiki, https://github.com/tqdm/tqdm/wiki
11
+ Keywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,time
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Environment :: Console
14
+ Classifier: Environment :: MacOS X
15
+ Classifier: Environment :: Other Environment
16
+ Classifier: Environment :: Win32 (MS Windows)
17
+ Classifier: Environment :: X11 Applications
18
+ Classifier: Framework :: IPython
19
+ Classifier: Framework :: Jupyter
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Intended Audience :: Education
22
+ Classifier: Intended Audience :: End Users/Desktop
23
+ Classifier: Intended Audience :: Other Audience
24
+ Classifier: Intended Audience :: System Administrators
25
+ Classifier: License :: OSI Approved :: MIT License
26
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
27
+ Classifier: Operating System :: MacOS
28
+ Classifier: Operating System :: MacOS :: MacOS X
29
+ Classifier: Operating System :: Microsoft
30
+ Classifier: Operating System :: Microsoft :: MS-DOS
31
+ Classifier: Operating System :: Microsoft :: Windows
32
+ Classifier: Operating System :: POSIX
33
+ Classifier: Operating System :: POSIX :: BSD
34
+ Classifier: Operating System :: POSIX :: BSD :: FreeBSD
35
+ Classifier: Operating System :: POSIX :: Linux
36
+ Classifier: Operating System :: POSIX :: SunOS/Solaris
37
+ Classifier: Operating System :: Unix
38
+ Classifier: Programming Language :: Python
39
+ Classifier: Programming Language :: Python :: 3
40
+ Classifier: Programming Language :: Python :: 3.7
41
+ Classifier: Programming Language :: Python :: 3.8
42
+ Classifier: Programming Language :: Python :: 3.9
43
+ Classifier: Programming Language :: Python :: 3.10
44
+ Classifier: Programming Language :: Python :: 3.11
45
+ Classifier: Programming Language :: Python :: 3.12
46
+ Classifier: Programming Language :: Python :: 3 :: Only
47
+ Classifier: Programming Language :: Python :: Implementation
48
+ Classifier: Programming Language :: Python :: Implementation :: IronPython
49
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
50
+ Classifier: Programming Language :: Unix Shell
51
+ Classifier: Topic :: Desktop Environment
52
+ Classifier: Topic :: Education :: Computer Aided Instruction (CAI)
53
+ Classifier: Topic :: Education :: Testing
54
+ Classifier: Topic :: Office/Business
55
+ Classifier: Topic :: Other/Nonlisted Topic
56
+ Classifier: Topic :: Software Development :: Build Tools
57
+ Classifier: Topic :: Software Development :: Libraries
58
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
59
+ Classifier: Topic :: Software Development :: Pre-processors
60
+ Classifier: Topic :: Software Development :: User Interfaces
61
+ Classifier: Topic :: System :: Installation/Setup
62
+ Classifier: Topic :: System :: Logging
63
+ Classifier: Topic :: System :: Monitoring
64
+ Classifier: Topic :: System :: Shells
65
+ Classifier: Topic :: Terminals
66
+ Classifier: Topic :: Utilities
67
+ Requires-Python: >=3.7
68
+ Description-Content-Type: text/x-rst
69
+ License-File: LICENCE
70
+ Requires-Dist: colorama; platform_system == "Windows"
71
+ Provides-Extra: dev
72
+ Requires-Dist: pytest>=6; extra == "dev"
73
+ Requires-Dist: pytest-cov; extra == "dev"
74
+ Requires-Dist: pytest-timeout; extra == "dev"
75
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
76
+ Requires-Dist: nbval; extra == "dev"
77
+ Provides-Extra: discord
78
+ Requires-Dist: requests; extra == "discord"
79
+ Provides-Extra: slack
80
+ Requires-Dist: slack-sdk; extra == "slack"
81
+ Provides-Extra: telegram
82
+ Requires-Dist: requests; extra == "telegram"
83
+ Provides-Extra: notebook
84
+ Requires-Dist: ipywidgets>=6; extra == "notebook"
85
+
86
+ |Logo|
87
+
88
+ tqdm
89
+ ====
90
+
91
+ |Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
92
+
93
+ |Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
94
+
95
+ |LICENCE| |OpenHub-Status| |binder-demo| |awesome-python|
96
+
97
+ ``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"
98
+ and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
99
+
100
+ Instantly make your loops show a smart progress meter - just wrap any
101
+ iterable with ``tqdm(iterable)``, and you're done!
102
+
103
+ .. code:: python
104
+
105
+ from tqdm import tqdm
106
+ for i in tqdm(range(10000)):
107
+ ...
108
+
109
+ ``76%|████████████████████████        | 7568/10000 [00:33<00:10, 229.00it/s]``
110
+
111
+ ``trange(N)`` can be also used as a convenient shortcut for
112
+ ``tqdm(range(N))``.
113
+
114
+ |Screenshot|
115
+ |Video| |Slides| |Merch|
116
+
117
+ It can also be executed as a module with pipes:
118
+
119
+ .. code:: sh
120
+
121
+ $ seq 9999999 | tqdm --bytes | wc -l
122
+ 75.2MB [00:00, 217MB/s]
123
+ 9999999
124
+
125
+ $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
126
+ > backup.tgz
127
+ 32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
128
+
129
+ Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and is
130
+ unit tested against performance regression.
131
+ By comparison, the well-established
132
+ `ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ has
133
+ an 800ns/iter overhead.
134
+
135
+ In addition to its low overhead, ``tqdm`` uses smart algorithms to predict
136
+ the remaining time and to skip unnecessary iteration displays, which allows
137
+ for a negligible overhead in most cases.
138
+
139
+ ``tqdm`` works on any platform
140
+ (Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),
141
+ in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
142
+
143
+ ``tqdm`` does not require any dependencies (not even ``curses``!), just
144
+ Python and an environment supporting ``carriage return \r`` and
145
+ ``line feed \n`` control characters.
146
+
147
+ ------------------------------------------
148
+
149
+ .. contents:: Table of contents
150
+ :backlinks: top
151
+ :local:
152
+
153
+
154
+ Installation
155
+ ------------
156
+
157
+ Latest PyPI stable release
158
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
159
+
160
+ |Versions| |PyPI-Downloads| |Libraries-Dependents|
161
+
162
+ .. code:: sh
163
+
164
+ pip install tqdm
165
+
166
+ Latest development release on GitHub
167
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168
+
169
+ |GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
170
+
171
+ Pull and install pre-release ``devel`` branch:
172
+
173
+ .. code:: sh
174
+
175
+ pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
176
+
177
+ Latest Conda release
178
+ ~~~~~~~~~~~~~~~~~~~~
179
+
180
+ |Conda-Forge-Status|
181
+
182
+ .. code:: sh
183
+
184
+ conda install -c conda-forge tqdm
185
+
186
+ Latest Snapcraft release
187
+ ~~~~~~~~~~~~~~~~~~~~~~~~
188
+
189
+ |Snapcraft|
190
+
191
+ There are 3 channels to choose from:
192
+
193
+ .. code:: sh
194
+
195
+ snap install tqdm # implies --stable, i.e. latest tagged release
196
+ snap install tqdm --candidate # master branch
197
+ snap install tqdm --edge # devel branch
198
+
199
+ Note that ``snap`` binaries are purely for CLI use (not ``import``-able), and
200
+ automatically set up ``bash`` tab-completion.
201
+
202
+ Latest Docker release
203
+ ~~~~~~~~~~~~~~~~~~~~~
204
+
205
+ |Docker|
206
+
207
+ .. code:: sh
208
+
209
+ docker pull tqdm/tqdm
210
+ docker run -i --rm tqdm/tqdm --help
211
+
212
+ Other
213
+ ~~~~~
214
+
215
+ There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
216
+
217
+ |Repology|
218
+
219
+ .. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg
220
+ :target: https://repology.org/project/python:tqdm/versions
221
+
222
+ Changelog
223
+ ---------
224
+
225
+ The list of all changes is available either on GitHub's Releases:
226
+ |GitHub-Status|, on the
227
+ `wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the
228
+ `website <https://tqdm.github.io/releases>`__.
229
+
230
+
231
+ Usage
232
+ -----
233
+
234
+ ``tqdm`` is very versatile and can be used in a number of ways.
235
+ The three main ones are given below.
236
+
237
+ Iterable-based
238
+ ~~~~~~~~~~~~~~
239
+
240
+ Wrap ``tqdm()`` around any iterable:
241
+
242
+ .. code:: python
243
+
244
+ from tqdm import tqdm
245
+ from time import sleep
246
+
247
+ text = ""
248
+ for char in tqdm(["a", "b", "c", "d"]):
249
+ sleep(0.25)
250
+ text = text + char
251
+
252
+ ``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
253
+
254
+ .. code:: python
255
+
256
+ from tqdm import trange
257
+
258
+ for i in trange(100):
259
+ sleep(0.01)
260
+
261
+ Instantiation outside of the loop allows for manual control over ``tqdm()``:
262
+
263
+ .. code:: python
264
+
265
+ pbar = tqdm(["a", "b", "c", "d"])
266
+ for char in pbar:
267
+ sleep(0.25)
268
+ pbar.set_description("Processing %s" % char)
269
+
270
+ Manual
271
+ ~~~~~~
272
+
273
+ Manual control of ``tqdm()`` updates using a ``with`` statement:
274
+
275
+ .. code:: python
276
+
277
+ with tqdm(total=100) as pbar:
278
+ for i in range(10):
279
+ sleep(0.1)
280
+ pbar.update(10)
281
+
282
+ If the optional variable ``total`` (or an iterable with ``len()``) is
283
+ provided, predictive stats are displayed.
284
+
285
+ ``with`` is also optional (you can just assign ``tqdm()`` to a variable,
286
+ but in this case don't forget to ``del`` or ``close()`` at the end:
287
+
288
+ .. code:: python
289
+
290
+ pbar = tqdm(total=100)
291
+ for i in range(10):
292
+ sleep(0.1)
293
+ pbar.update(10)
294
+ pbar.close()
295
+
296
+ Module
297
+ ~~~~~~
298
+
299
+ Perhaps the most wonderful use of ``tqdm`` is in a script or on the command
300
+ line. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will pass
301
+ through all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
302
+
303
+ The example below demonstrate counting the number of lines in all Python files
304
+ in the current directory, with timing information included.
305
+
306
+ .. code:: sh
307
+
308
+ $ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
309
+ 857365
310
+
311
+ real 0m3.458s
312
+ user 0m0.274s
313
+ sys 0m3.325s
314
+
315
+ $ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
316
+ 857366it [00:03, 246471.31it/s]
317
+ 857365
318
+
319
+ real 0m3.585s
320
+ user 0m0.862s
321
+ sys 0m3.358s
322
+
323
+ Note that the usual arguments for ``tqdm`` can also be specified.
324
+
325
+ .. code:: sh
326
+
327
+ $ find . -name '*.py' -type f -exec cat \{} \; |
328
+ tqdm --unit loc --unit_scale --total 857366 >> /dev/null
329
+ 100%|███████████████████████��█████████| 857K/857K [00:04<00:00, 246Kloc/s]
330
+
331
+ Backing up a large directory?
332
+
333
+ .. code:: sh
334
+
335
+ $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
336
+ > backup.tgz
337
+ 44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
338
+
339
+ This can be beautified further:
340
+
341
+ .. code:: sh
342
+
343
+ $ BYTES=$(du -sb docs/ | cut -f1)
344
+ $ tar -cf - docs/ \
345
+ | tqdm --bytes --total "$BYTES" --desc Processing | gzip \
346
+ | tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \
347
+ > ~/backup.tgz
348
+ Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s]
349
+ Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
350
+
351
+ Or done on a file level using 7-zip:
352
+
353
+ .. code:: sh
354
+
355
+ $ 7z a -bd -r backup.7z docs/ | grep Compressing \
356
+ | tqdm --total $(find docs/ -type f | wc -l) --unit files \
357
+ | grep -v Compressing
358
+ 100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
359
+
360
+ Pre-existing CLI programs already outputting basic progress information will
361
+ benefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
362
+
363
+ .. code:: sh
364
+
365
+ $ seq 3 0.1 5 | tqdm --total 5 --update_to --null
366
+ 100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s]
367
+ $ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations
368
+ 55it [00:00, 90006.52it/s]
369
+
370
+ FAQ and Known Issues
371
+ --------------------
372
+
373
+ |GitHub-Issues|
374
+
375
+ The most common issues relate to excessive output on multiple lines, instead
376
+ of a neat one-line progress bar.
377
+
378
+ - Consoles in general: require support for carriage return (``CR``, ``\r``).
379
+
380
+ * Some cloud logging consoles which don't support ``\r`` properly
381
+ (`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__,
382
+ `K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from
383
+ ``export TQDM_POSITION=-1``.
384
+
385
+ - Nested progress bars:
386
+
387
+ * Consoles in general: require support for moving cursors up to the
388
+ previous line. For example,
389
+ `IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__,
390
+ `ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and
391
+ `PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also
392
+ `here <https://github.com/tqdm/tqdm/issues/208>`__,
393
+ `here <https://github.com/tqdm/tqdm/issues/307>`__, and
394
+ `here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__)
395
+ lack full support.
396
+ * Windows: additionally may require the Python module ``colorama``
397
+ to ensure nested bars stay within their respective lines.
398
+
399
+ - Unicode:
400
+
401
+ * Environments which report that they support unicode will have solid smooth
402
+ progressbars. The fallback is an ``ascii``-only bar.
403
+ * Windows consoles often only partially support unicode and thus
404
+ `often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__
405
+ (also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to
406
+ either normal-width unicode characters being incorrectly displayed as
407
+ "wide", or some unicode characters not rendering.
408
+
409
+ - Wrapping generators:
410
+
411
+ * Generator wrapper functions tend to hide the length of iterables.
412
+ ``tqdm`` does not.
413
+ * Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or
414
+ ``tqdm(enumerate(x), total=len(x), ...)``.
415
+ The same applies to ``numpy.ndenumerate``.
416
+ * Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even
417
+ ``zip(tqdm(a), tqdm(b))``.
418
+ * The same applies to ``itertools``.
419
+ * Some useful convenience functions can be found under ``tqdm.contrib``.
420
+
421
+ - `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__:
422
+ use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
423
+
424
+ - Overriding defaults via environment variables:
425
+ e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam.
426
+ This override logic is handled by the ``tqdm.utils.envwrap`` decorator
427
+ (useful independent of ``tqdm``).
428
+
429
+ If you come across any other difficulties, browse and file |GitHub-Issues|.
430
+
431
+ Documentation
432
+ -------------
433
+
434
+ |Py-Versions| |README-Hits| (Since 19 May 2016)
435
+
436
+ .. code:: python
437
+
438
+ class tqdm():
439
+ """
440
+ Decorate an iterable object, returning an iterator which acts exactly
441
+ like the original iterable, but prints a dynamically updating
442
+ progressbar every time a value is requested.
443
+ """
444
+
445
+ @envwrap("TQDM_") # override defaults via env vars
446
+ def __init__(self, iterable=None, desc=None, total=None, leave=True,
447
+ file=None, ncols=None, mininterval=0.1,
448
+ maxinterval=10.0, miniters=None, ascii=None, disable=False,
449
+ unit='it', unit_scale=False, dynamic_ncols=False,
450
+ smoothing=0.3, bar_format=None, initial=0, position=None,
451
+ postfix=None, unit_divisor=1000, write_bytes=False,
452
+ lock_args=None, nrows=None, colour=None, delay=0):
453
+
454
+ Parameters
455
+ ~~~~~~~~~~
456
+
457
+ * iterable : iterable, optional
458
+ Iterable to decorate with a progressbar.
459
+ Leave blank to manually manage the updates.
460
+ * desc : str, optional
461
+ Prefix for the progressbar.
462
+ * total : int or float, optional
463
+ The number of expected iterations. If unspecified,
464
+ len(iterable) is used if possible. If float("inf") or as a last
465
+ resort, only basic progress statistics are displayed
466
+ (no ETA, no progressbar).
467
+ If ``gui`` is True and this parameter needs subsequent updating,
468
+ specify an initial arbitrary large positive number,
469
+ e.g. 9e9.
470
+ * leave : bool, optional
471
+ If [default: True], keeps all traces of the progressbar
472
+ upon termination of iteration.
473
+ If ``None``, will leave only if ``position`` is ``0``.
474
+ * file : ``io.TextIOWrapper`` or ``io.StringIO``, optional
475
+ Specifies where to output the progress messages
476
+ (default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()``
477
+ methods. For encoding, see ``write_bytes``.
478
+ * ncols : int, optional
479
+ The width of the entire output message. If specified,
480
+ dynamically resizes the progressbar to stay within this bound.
481
+ If unspecified, attempts to use environment width. The
482
+ fallback is a meter width of 10 and no limit for the counter and
483
+ statistics. If 0, will not print any meter (only stats).
484
+ * mininterval : float, optional
485
+ Minimum progress display update interval [default: 0.1] seconds.
486
+ * maxinterval : float, optional
487
+ Maximum progress display update interval [default: 10] seconds.
488
+ Automatically adjusts ``miniters`` to correspond to ``mininterval``
489
+ after long display update lag. Only works if ``dynamic_miniters``
490
+ or monitor thread is enabled.
491
+ * miniters : int or float, optional
492
+ Minimum progress display update interval, in iterations.
493
+ If 0 and ``dynamic_miniters``, will automatically adjust to equal
494
+ ``mininterval`` (more CPU efficient, good for tight loops).
495
+ If > 0, will skip display of specified number of iterations.
496
+ Tweak this and ``mininterval`` to get very efficient loops.
497
+ If your progress is erratic with both fast and slow iterations
498
+ (network, skipping items, etc) you should set miniters=1.
499
+ * ascii : bool or str, optional
500
+ If unspecified or False, use unicode (smooth blocks) to fill
501
+ the meter. The fallback is to use ASCII characters " 123456789#".
502
+ * disable : bool, optional
503
+ Whether to disable the entire progressbar wrapper
504
+ [default: False]. If set to None, disable on non-TTY.
505
+ * unit : str, optional
506
+ String that will be used to define the unit of each iteration
507
+ [default: it].
508
+ * unit_scale : bool or int or float, optional
509
+ If 1 or True, the number of iterations will be reduced/scaled
510
+ automatically and a metric prefix following the
511
+ International System of Units standard will be added
512
+ (kilo, mega, etc.) [default: False]. If any other non-zero
513
+ number, will scale ``total`` and ``n``.
514
+ * dynamic_ncols : bool, optional
515
+ If set, constantly alters ``ncols`` and ``nrows`` to the
516
+ environment (allowing for window resizes) [default: False].
517
+ * smoothing : float, optional
518
+ Exponential moving average smoothing factor for speed estimates
519
+ (ignored in GUI mode). Ranges from 0 (average speed) to 1
520
+ (current/instantaneous speed) [default: 0.3].
521
+ * bar_format : str, optional
522
+ Specify a custom bar string formatting. May impact performance.
523
+ [default: '{l_bar}{bar}{r_bar}'], where
524
+ l_bar='{desc}: {percentage:3.0f}%|' and
525
+ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
526
+ '{rate_fmt}{postfix}]'
527
+ Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
528
+ percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
529
+ rate, rate_fmt, rate_noinv, rate_noinv_fmt,
530
+ rate_inv, rate_inv_fmt, postfix, unit_divisor,
531
+ remaining, remaining_s, eta.
532
+ Note that a trailing ": " is automatically removed after {desc}
533
+ if the latter is empty.
534
+ * initial : int or float, optional
535
+ The initial counter value. Useful when restarting a progress
536
+ bar [default: 0]. If using float, consider specifying ``{n:.3f}``
537
+ or similar in ``bar_format``, or specifying ``unit_scale``.
538
+ * position : int, optional
539
+ Specify the line offset to print this bar (starting from 0)
540
+ Automatic if unspecified.
541
+ Useful to manage multiple bars at once (eg, from threads).
542
+ * postfix : dict or ``*``, optional
543
+ Specify additional stats to display at the end of the bar.
544
+ Calls ``set_postfix(**postfix)`` if possible (dict).
545
+ * unit_divisor : float, optional
546
+ [default: 1000], ignored unless ``unit_scale`` is True.
547
+ * write_bytes : bool, optional
548
+ Whether to write bytes. If (default: False) will write unicode.
549
+ * lock_args : tuple, optional
550
+ Passed to ``refresh`` for intermediate output
551
+ (initialisation, iterating, and updating).
552
+ * nrows : int, optional
553
+ The screen height. If specified, hides nested bars outside this
554
+ bound. If unspecified, attempts to use environment height.
555
+ The fallback is 20.
556
+ * colour : str, optional
557
+ Bar colour (e.g. 'green', '#00ff00').
558
+ * delay : float, optional
559
+ Don't display until [default: 0] seconds have elapsed.
560
+
561
+ Extra CLI Options
562
+ ~~~~~~~~~~~~~~~~~
563
+
564
+ * delim : chr, optional
565
+ Delimiting character [default: '\n']. Use '\0' for null.
566
+ N.B.: on Windows systems, Python converts '\n' to '\r\n'.
567
+ * buf_size : int, optional
568
+ String buffer size in bytes [default: 256]
569
+ used when ``delim`` is specified.
570
+ * bytes : bool, optional
571
+ If true, will count bytes, ignore ``delim``, and default
572
+ ``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.
573
+ * tee : bool, optional
574
+ If true, passes ``stdin`` to both ``stderr`` and ``stdout``.
575
+ * update : bool, optional
576
+ If true, will treat input as newly elapsed iterations,
577
+ i.e. numbers to pass to ``update()``. Note that this is slow
578
+ (~2e5 it/s) since every input must be decoded as a number.
579
+ * update_to : bool, optional
580
+ If true, will treat input as total elapsed iterations,
581
+ i.e. numbers to assign to ``self.n``. Note that this is slow
582
+ (~2e5 it/s) since every input must be decoded as a number.
583
+ * null : bool, optional
584
+ If true, will discard input (no stdout).
585
+ * manpath : str, optional
586
+ Directory in which to install tqdm man pages.
587
+ * comppath : str, optional
588
+ Directory in which to place tqdm completion.
589
+ * log : str, optional
590
+ CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
591
+
592
+ Returns
593
+ ~~~~~~~
594
+
595
+ * out : decorated iterator.
596
+
597
+ .. code:: python
598
+
599
+ class tqdm():
600
+ def update(self, n=1):
601
+ """
602
+ Manually update the progress bar, useful for streams
603
+ such as reading files.
604
+ E.g.:
605
+ >>> t = tqdm(total=filesize) # Initialise
606
+ >>> for current_buffer in stream:
607
+ ... ...
608
+ ... t.update(len(current_buffer))
609
+ >>> t.close()
610
+ The last line is highly recommended, but possibly not necessary if
611
+ ``t.update()`` will be called in such a way that ``filesize`` will be
612
+ exactly reached and printed.
613
+
614
+ Parameters
615
+ ----------
616
+ n : int or float, optional
617
+ Increment to add to the internal counter of iterations
618
+ [default: 1]. If using float, consider specifying ``{n:.3f}``
619
+ or similar in ``bar_format``, or specifying ``unit_scale``.
620
+
621
+ Returns
622
+ -------
623
+ out : bool or None
624
+ True if a ``display()`` was triggered.
625
+ """
626
+
627
+ def close(self):
628
+ """Cleanup and (if leave=False) close the progressbar."""
629
+
630
+ def clear(self, nomove=False):
631
+ """Clear current bar display."""
632
+
633
+ def refresh(self):
634
+ """
635
+ Force refresh the display of this bar.
636
+
637
+ Parameters
638
+ ----------
639
+ nolock : bool, optional
640
+ If ``True``, does not lock.
641
+ If [default: ``False``]: calls ``acquire()`` on internal lock.
642
+ lock_args : tuple, optional
643
+ Passed to internal lock's ``acquire()``.
644
+ If specified, will only ``display()`` if ``acquire()`` returns ``True``.
645
+ """
646
+
647
+ def unpause(self):
648
+ """Restart tqdm timer from last print time."""
649
+
650
+ def reset(self, total=None):
651
+ """
652
+ Resets to 0 iterations for repeated use.
653
+
654
+ Consider combining with ``leave=True``.
655
+
656
+ Parameters
657
+ ----------
658
+ total : int or float, optional. Total to use for the new bar.
659
+ """
660
+
661
+ def set_description(self, desc=None, refresh=True):
662
+ """
663
+ Set/modify description of the progress bar.
664
+
665
+ Parameters
666
+ ----------
667
+ desc : str, optional
668
+ refresh : bool, optional
669
+ Forces refresh [default: True].
670
+ """
671
+
672
+ def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs):
673
+ """
674
+ Set/modify postfix (additional stats)
675
+ with automatic formatting based on datatype.
676
+
677
+ Parameters
678
+ ----------
679
+ ordered_dict : dict or OrderedDict, optional
680
+ refresh : bool, optional
681
+ Forces refresh [default: True].
682
+ kwargs : dict, optional
683
+ """
684
+
685
+ @classmethod
686
+ def write(cls, s, file=sys.stdout, end="\n"):
687
+ """Print a message via tqdm (without overlap with bars)."""
688
+
689
+ @property
690
+ def format_dict(self):
691
+ """Public API for read-only member access."""
692
+
693
+ def display(self, msg=None, pos=None):
694
+ """
695
+ Use ``self.sp`` to display ``msg`` in the specified ``pos``.
696
+
697
+ Consider overloading this function when inheriting to use e.g.:
698
+ ``self.some_frontend(**self.format_dict)`` instead of ``self.sp``.
699
+
700
+ Parameters
701
+ ----------
702
+ msg : str, optional. What to display (default: ``repr(self)``).
703
+ pos : int, optional. Position to ``moveto``
704
+ (default: ``abs(self.pos)``).
705
+ """
706
+
707
+ @classmethod
708
+ @contextmanager
709
+ def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
710
+ """
711
+ stream : file-like object.
712
+ method : str, "read" or "write". The result of ``read()`` and
713
+ the first argument of ``write()`` should have a ``len()``.
714
+
715
+ >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
716
+ ... while True:
717
+ ... chunk = fobj.read(chunk_size)
718
+ ... if not chunk:
719
+ ... break
720
+ """
721
+
722
+ @classmethod
723
+ def pandas(cls, *targs, **tqdm_kwargs):
724
+ """Registers the current `tqdm` class with `pandas`."""
725
+
726
+ def trange(*args, **tqdm_kwargs):
727
+ """Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
728
+
729
+ Convenience Functions
730
+ ~~~~~~~~~~~~~~~~~~~~~
731
+
732
+ .. code:: python
733
+
734
+ def tqdm.contrib.tenumerate(iterable, start=0, total=None,
735
+ tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs):
736
+ """Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
737
+
738
+ def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs):
739
+ """Equivalent of builtin `zip`."""
740
+
741
+ def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs):
742
+ """Equivalent of builtin `map`."""
743
+
744
+ Submodules
745
+ ~~~~~~~~~~
746
+
747
+ .. code:: python
748
+
749
+ class tqdm.notebook.tqdm(tqdm.tqdm):
750
+ """IPython/Jupyter Notebook widget."""
751
+
752
+ class tqdm.auto.tqdm(tqdm.tqdm):
753
+ """Automatically chooses beween `tqdm.notebook` and `tqdm.tqdm`."""
754
+
755
+ class tqdm.asyncio.tqdm(tqdm.tqdm):
756
+ """Asynchronous version."""
757
+ @classmethod
758
+ def as_completed(cls, fs, *, loop=None, timeout=None, total=None,
759
+ **tqdm_kwargs):
760
+ """Wrapper for `asyncio.as_completed`."""
761
+
762
+ class tqdm.gui.tqdm(tqdm.tqdm):
763
+ """Matplotlib GUI version."""
764
+
765
+ class tqdm.tk.tqdm(tqdm.tqdm):
766
+ """Tkinter GUI version."""
767
+
768
+ class tqdm.rich.tqdm(tqdm.tqdm):
769
+ """`rich.progress` version."""
770
+
771
+ class tqdm.keras.TqdmCallback(keras.callbacks.Callback):
772
+ """Keras callback for epoch and batch progress."""
773
+
774
+ class tqdm.dask.TqdmCallback(dask.callbacks.Callback):
775
+ """Dask callback for task progress."""
776
+
777
+
778
+ ``contrib``
779
+ +++++++++++
780
+
781
+ The ``tqdm.contrib`` package also contains experimental modules:
782
+
783
+ - ``tqdm.contrib.itertools``: Thin wrappers around ``itertools``
784
+ - ``tqdm.contrib.concurrent``: Thin wrappers around ``concurrent.futures``
785
+ - ``tqdm.contrib.slack``: Posts to `Slack <https://slack.com>`__ bots
786
+ - ``tqdm.contrib.discord``: Posts to `Discord <https://discord.com>`__ bots
787
+ - ``tqdm.contrib.telegram``: Posts to `Telegram <https://telegram.org>`__ bots
788
+ - ``tqdm.contrib.bells``: Automagically enables all optional features
789
+
790
+ * ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
791
+
792
+ Examples and Advanced Usage
793
+ ---------------------------
794
+
795
+ - See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
796
+ folder;
797
+ - import the module and run ``help()``;
798
+ - consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
799
+
800
+ * this has an
801
+ `excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__
802
+ on how to make a **great** progressbar;
803
+
804
+ - check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or
805
+ - run the |binder-demo|.
806
+
807
+ Description and additional stats
808
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
809
+
810
+ Custom information can be displayed and updated dynamically on ``tqdm`` bars
811
+ with the ``desc`` and ``postfix`` arguments:
812
+
813
+ .. code:: python
814
+
815
+ from tqdm import tqdm, trange
816
+ from random import random, randint
817
+ from time import sleep
818
+
819
+ with trange(10) as t:
820
+ for i in t:
821
+ # Description will be displayed on the left
822
+ t.set_description('GEN %i' % i)
823
+ # Postfix will be displayed on the right,
824
+ # formatted automatically based on argument's datatype
825
+ t.set_postfix(loss=random(), gen=randint(1,999), str='h',
826
+ lst=[1, 2])
827
+ sleep(0.1)
828
+
829
+ with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}",
830
+ postfix=["Batch", {"value": 0}]) as t:
831
+ for i in range(10):
832
+ sleep(0.1)
833
+ t.postfix[1]["value"] = i / 2
834
+ t.update()
835
+
836
+ Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
837
+
838
+ - ``postfix`` also needs to be passed as an initial argument in a compatible
839
+ format, and
840
+ - ``postfix`` will be auto-converted to a string if it is a ``dict``-like
841
+ object. To prevent this behaviour, insert an extra item into the dictionary
842
+ where the key is not a string.
843
+
844
+ Additional ``bar_format`` parameters may also be defined by overriding
845
+ ``format_dict``, and the bar itself may be modified using ``ascii``:
846
+
847
+ .. code:: python
848
+
849
+ from tqdm import tqdm
850
+ class TqdmExtraFormat(tqdm):
851
+ """Provides a `total_time` format parameter"""
852
+ @property
853
+ def format_dict(self):
854
+ d = super().format_dict
855
+ total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
856
+ d.update(total_time=self.format_interval(total_time) + " in total")
857
+ return d
858
+
859
+ for i in TqdmExtraFormat(
860
+ range(9), ascii=" .oO0",
861
+ bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"):
862
+ if i == 4:
863
+ break
864
+
865
+ .. code::
866
+
867
+ 00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
868
+
869
+ Note that ``{bar}`` also supports a format specifier ``[width][type]``.
870
+
871
+ - ``width``
872
+
873
+ * unspecified (default): automatic to fill ``ncols``
874
+ * ``int >= 0``: fixed width overriding ``ncols`` logic
875
+ * ``int < 0``: subtract from the automatic default
876
+
877
+ - ``type``
878
+
879
+ * ``a``: ascii (``ascii=True`` override)
880
+ * ``u``: unicode (``ascii=False`` override)
881
+ * ``b``: blank (``ascii=" "`` override)
882
+
883
+ This means a fixed bar with right-justified text may be created by using:
884
+ ``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
885
+
886
+ Nested progress bars
887
+ ~~~~~~~~~~~~~~~~~~~~
888
+
889
+ ``tqdm`` supports nested progress bars. Here's an example:
890
+
891
+ .. code:: python
892
+
893
+ from tqdm.auto import trange
894
+ from time import sleep
895
+
896
+ for i in trange(4, desc='1st loop'):
897
+ for j in trange(5, desc='2nd loop'):
898
+ for k in trange(50, desc='3rd loop', leave=False):
899
+ sleep(0.01)
900
+
901
+ For manual control over positioning (e.g. for multi-processing use),
902
+ you may specify ``position=n`` where ``n=0`` for the outermost bar,
903
+ ``n=1`` for the next, and so on.
904
+ However, it's best to check if ``tqdm`` can work without manual ``position``
905
+ first.
906
+
907
+ .. code:: python
908
+
909
+ from time import sleep
910
+ from tqdm import trange, tqdm
911
+ from multiprocessing import Pool, RLock, freeze_support
912
+
913
+ L = list(range(9))
914
+
915
+ def progresser(n):
916
+ interval = 0.001 / (n + 2)
917
+ total = 5000
918
+ text = f"#{n}, est. {interval * total:<04.2}s"
919
+ for _ in trange(total, desc=text, position=n):
920
+ sleep(interval)
921
+
922
+ if __name__ == '__main__':
923
+ freeze_support() # for Windows support
924
+ tqdm.set_lock(RLock()) # for managing output contention
925
+ p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),))
926
+ p.map(progresser, L)
927
+
928
+ Note that in Python 3, ``tqdm.write`` is thread-safe:
929
+
930
+ .. code:: python
931
+
932
+ from time import sleep
933
+ from tqdm import tqdm, trange
934
+ from concurrent.futures import ThreadPoolExecutor
935
+
936
+ L = list(range(9))
937
+
938
+ def progresser(n):
939
+ interval = 0.001 / (n + 2)
940
+ total = 5000
941
+ text = f"#{n}, est. {interval * total:<04.2}s"
942
+ for _ in trange(total, desc=text):
943
+ sleep(interval)
944
+ if n == 6:
945
+ tqdm.write("n == 6 completed.")
946
+ tqdm.write("`tqdm.write()` is thread-safe in py3!")
947
+
948
+ if __name__ == '__main__':
949
+ with ThreadPoolExecutor() as p:
950
+ p.map(progresser, L)
951
+
952
+ Hooks and callbacks
953
+ ~~~~~~~~~~~~~~~~~~~
954
+
955
+ ``tqdm`` can easily support callbacks/hooks and manual updates.
956
+ Here's an example with ``urllib``:
957
+
958
+ **``urllib.urlretrieve`` documentation**
959
+
960
+ | [...]
961
+ | If present, the hook function will be called once
962
+ | on establishment of the network connection and once after each block read
963
+ | thereafter. The hook will be passed three arguments; a count of blocks
964
+ | transferred so far, a block size in bytes, and the total size of the file.
965
+ | [...]
966
+
967
+ .. code:: python
968
+
969
+ import urllib, os
970
+ from tqdm import tqdm
971
+ urllib = getattr(urllib, 'request', urllib)
972
+
973
+ class TqdmUpTo(tqdm):
974
+ """Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
975
+ def update_to(self, b=1, bsize=1, tsize=None):
976
+ """
977
+ b : int, optional
978
+ Number of blocks transferred so far [default: 1].
979
+ bsize : int, optional
980
+ Size of each block (in tqdm units) [default: 1].
981
+ tsize : int, optional
982
+ Total size (in tqdm units). If [default: None] remains unchanged.
983
+ """
984
+ if tsize is not None:
985
+ self.total = tsize
986
+ return self.update(b * bsize - self.n) # also sets self.n = b * bsize
987
+
988
+ eg_link = "https://caspersci.uk.to/matryoshka.zip"
989
+ with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
990
+ desc=eg_link.split('/')[-1]) as t: # all optional kwargs
991
+ urllib.urlretrieve(eg_link, filename=os.devnull,
992
+ reporthook=t.update_to, data=None)
993
+ t.total = t.n
994
+
995
+ Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.
996
+ Functional alternative in
997
+ `examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
998
+
999
+ It is recommend to use ``miniters=1`` whenever there is potentially
1000
+ large differences in iteration speed (e.g. downloading a file over
1001
+ a patchy connection).
1002
+
1003
+ **Wrapping read/write methods**
1004
+
1005
+ To measure throughput through a file-like object's ``read`` or ``write``
1006
+ methods, use ``CallbackIOWrapper``:
1007
+
1008
+ .. code:: python
1009
+
1010
+ from tqdm.auto import tqdm
1011
+ from tqdm.utils import CallbackIOWrapper
1012
+
1013
+ with tqdm(total=file_obj.size,
1014
+ unit='B', unit_scale=True, unit_divisor=1024) as t:
1015
+ fobj = CallbackIOWrapper(t.update, file_obj, "read")
1016
+ while True:
1017
+ chunk = fobj.read(chunk_size)
1018
+ if not chunk:
1019
+ break
1020
+ t.reset()
1021
+ # ... continue to use `t` for something else
1022
+
1023
+ Alternatively, use the even simpler ``wrapattr`` convenience function,
1024
+ which would condense both the ``urllib`` and ``CallbackIOWrapper`` examples
1025
+ down to:
1026
+
1027
+ .. code:: python
1028
+
1029
+ import urllib, os
1030
+ from tqdm import tqdm
1031
+
1032
+ eg_link = "https://caspersci.uk.to/matryoshka.zip"
1033
+ response = getattr(urllib, 'request', urllib).urlopen(eg_link)
1034
+ with tqdm.wrapattr(open(os.devnull, "wb"), "write",
1035
+ miniters=1, desc=eg_link.split('/')[-1],
1036
+ total=getattr(response, 'length', None)) as fout:
1037
+ for chunk in response:
1038
+ fout.write(chunk)
1039
+
1040
+ The ``requests`` equivalent is nearly identical:
1041
+
1042
+ .. code:: python
1043
+
1044
+ import requests, os
1045
+ from tqdm import tqdm
1046
+
1047
+ eg_link = "https://caspersci.uk.to/matryoshka.zip"
1048
+ response = requests.get(eg_link, stream=True)
1049
+ with tqdm.wrapattr(open(os.devnull, "wb"), "write",
1050
+ miniters=1, desc=eg_link.split('/')[-1],
1051
+ total=int(response.headers.get('content-length', 0))) as fout:
1052
+ for chunk in response.iter_content(chunk_size=4096):
1053
+ fout.write(chunk)
1054
+
1055
+ **Custom callback**
1056
+
1057
+ ``tqdm`` is known for intelligently skipping unnecessary displays. To make a
1058
+ custom callback take advantage of this, simply use the return value of
1059
+ ``update()``. This is set to ``True`` if a ``display()`` was triggered.
1060
+
1061
+ .. code:: python
1062
+
1063
+ from tqdm.auto import tqdm as std_tqdm
1064
+
1065
+ def external_callback(*args, **kwargs):
1066
+ ...
1067
+
1068
+ class TqdmExt(std_tqdm):
1069
+ def update(self, n=1):
1070
+ displayed = super().update(n)
1071
+ if displayed:
1072
+ external_callback(**self.format_dict)
1073
+ return displayed
1074
+
1075
+ ``asyncio``
1076
+ ~~~~~~~~~~~
1077
+
1078
+ Note that ``break`` isn't currently caught by asynchronous iterators.
1079
+ This means that ``tqdm`` cannot clean up after itself in this case:
1080
+
1081
+ .. code:: python
1082
+
1083
+ from tqdm.asyncio import tqdm
1084
+
1085
+ async for i in tqdm(range(9)):
1086
+ if i == 2:
1087
+ break
1088
+
1089
+ Instead, either call ``pbar.close()`` manually or use the context manager syntax:
1090
+
1091
+ .. code:: python
1092
+
1093
+ from tqdm.asyncio import tqdm
1094
+
1095
+ with tqdm(range(9)) as pbar:
1096
+ async for i in pbar:
1097
+ if i == 2:
1098
+ break
1099
+
1100
+ Pandas Integration
1101
+ ~~~~~~~~~~~~~~~~~~
1102
+
1103
+ Due to popular demand we've added support for ``pandas`` -- here's an example
1104
+ for ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
1105
+
1106
+ .. code:: python
1107
+
1108
+ import pandas as pd
1109
+ import numpy as np
1110
+ from tqdm import tqdm
1111
+
1112
+ df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
1113
+
1114
+ # Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
1115
+ # (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.)
1116
+ tqdm.pandas(desc="my bar!")
1117
+
1118
+ # Now you can use `progress_apply` instead of `apply`
1119
+ # and `progress_map` instead of `map`
1120
+ df.progress_apply(lambda x: x**2)
1121
+ # can also groupby:
1122
+ # df.groupby(0).progress_apply(lambda x: x**2)
1123
+
1124
+ In case you're interested in how this works (and how to modify it for your
1125
+ own callbacks), see the
1126
+ `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
1127
+ folder or import the module and run ``help()``.
1128
+
1129
+ Keras Integration
1130
+ ~~~~~~~~~~~~~~~~~
1131
+
1132
+ A ``keras`` callback is also available:
1133
+
1134
+ .. code:: python
1135
+
1136
+ from tqdm.keras import TqdmCallback
1137
+
1138
+ ...
1139
+
1140
+ model.fit(..., verbose=0, callbacks=[TqdmCallback()])
1141
+
1142
+ Dask Integration
1143
+ ~~~~~~~~~~~~~~~~
1144
+
1145
+ A ``dask`` callback is also available:
1146
+
1147
+ .. code:: python
1148
+
1149
+ from tqdm.dask import TqdmCallback
1150
+
1151
+ with TqdmCallback(desc="compute"):
1152
+ ...
1153
+ arr.compute()
1154
+
1155
+ # or use callback globally
1156
+ cb = TqdmCallback(desc="global")
1157
+ cb.register()
1158
+ arr.compute()
1159
+
1160
+ IPython/Jupyter Integration
1161
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1162
+
1163
+ IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
1164
+
1165
+ .. code:: python
1166
+
1167
+ from tqdm.notebook import trange, tqdm
1168
+ from time import sleep
1169
+
1170
+ for i in trange(3, desc='1st loop'):
1171
+ for j in tqdm(range(100), desc='2nd loop'):
1172
+ sleep(0.01)
1173
+
1174
+ In addition to ``tqdm`` features, the submodule provides a native Jupyter
1175
+ widget (compatible with IPython v1-v4 and Jupyter), fully working nested bars
1176
+ and colour hints (blue: normal, green: completed, red: error/interrupt,
1177
+ light blue: no ETA); as demonstrated below.
1178
+
1179
+ |Screenshot-Jupyter1|
1180
+ |Screenshot-Jupyter2|
1181
+ |Screenshot-Jupyter3|
1182
+
1183
+ The ``notebook`` version supports percentage or pixels for overall width
1184
+ (e.g.: ``ncols='100%'`` or ``ncols='480px'``).
1185
+
1186
+ It is also possible to let ``tqdm`` automatically choose between
1187
+ console or notebook versions by using the ``autonotebook`` submodule:
1188
+
1189
+ .. code:: python
1190
+
1191
+ from tqdm.autonotebook import tqdm
1192
+ tqdm.pandas()
1193
+
1194
+ Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebook
1195
+ since it is not meant to be possible to distinguish between ``jupyter notebook``
1196
+ and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppress
1197
+ this warning.
1198
+
1199
+ Note that notebooks will display the bar in the cell where it was created.
1200
+ This may be a different cell from the one where it is used.
1201
+ If this is not desired, either
1202
+
1203
+ - delay the creation of the bar to the cell where it must be displayed, or
1204
+ - create the bar with ``display=False``, and in a later cell call
1205
+ ``display(bar.container)``:
1206
+
1207
+ .. code:: python
1208
+
1209
+ from tqdm.notebook import tqdm
1210
+ pbar = tqdm(..., display=False)
1211
+
1212
+ .. code:: python
1213
+
1214
+ # different cell
1215
+ display(pbar.container)
1216
+
1217
+ The ``keras`` callback has a ``display()`` method which can be used likewise:
1218
+
1219
+ .. code:: python
1220
+
1221
+ from tqdm.keras import TqdmCallback
1222
+ cbk = TqdmCallback(display=False)
1223
+
1224
+ .. code:: python
1225
+
1226
+ # different cell
1227
+ cbk.display()
1228
+ model.fit(..., verbose=0, callbacks=[cbk])
1229
+
1230
+ Another possibility is to have a single bar (near the top of the notebook)
1231
+ which is constantly re-used (using ``reset()`` rather than ``close()``).
1232
+ For this reason, the notebook version (unlike the CLI version) does not
1233
+ automatically call ``close()`` upon ``Exception``.
1234
+
1235
+ .. code:: python
1236
+
1237
+ from tqdm.notebook import tqdm
1238
+ pbar = tqdm()
1239
+
1240
+ .. code:: python
1241
+
1242
+ # different cell
1243
+ iterable = range(100)
1244
+ pbar.reset(total=len(iterable)) # initialise with new `total`
1245
+ for i in iterable:
1246
+ pbar.update()
1247
+ pbar.refresh() # force print final status but don't `close()`
1248
+
1249
+ Custom Integration
1250
+ ~~~~~~~~~~~~~~~~~~
1251
+
1252
+ To change the default arguments (such as making ``dynamic_ncols=True``),
1253
+ simply use built-in Python magic:
1254
+
1255
+ .. code:: python
1256
+
1257
+ from functools import partial
1258
+ from tqdm import tqdm as std_tqdm
1259
+ tqdm = partial(std_tqdm, dynamic_ncols=True)
1260
+
1261
+ For further customisation,
1262
+ ``tqdm`` may be inherited from to create custom callbacks (as with the
1263
+ ``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends
1264
+ (e.g. GUIs such as notebook or plotting packages). In the latter case:
1265
+
1266
+ 1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
1267
+ terminal ``status_printer`` creation.
1268
+ 2. Redefine: ``close()``, ``clear()``, ``display()``.
1269
+
1270
+ Consider overloading ``display()`` to use e.g.
1271
+ ``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
1272
+
1273
+ Some submodule examples of inheritance:
1274
+
1275
+ - `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__
1276
+ - `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__
1277
+ - `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__
1278
+ - `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__
1279
+ - `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__
1280
+ - `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
1281
+
1282
+ Dynamic Monitor/Meter
1283
+ ~~~~~~~~~~~~~~~~~~~~~
1284
+
1285
+ You can use a ``tqdm`` as a meter which is not monotonically increasing.
1286
+ This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``
1287
+ changes.
1288
+
1289
+ One example would be recursively searching for files. The ``total`` is the
1290
+ number of objects found so far, while ``n`` is the number of those objects which
1291
+ are files (rather than folders):
1292
+
1293
+ .. code:: python
1294
+
1295
+ from tqdm import tqdm
1296
+ import os.path
1297
+
1298
+ def find_files_recursively(path, show_progress=True):
1299
+ files = []
1300
+ # total=1 assumes `path` is a file
1301
+ t = tqdm(total=1, unit="file", disable=not show_progress)
1302
+ if not os.path.exists(path):
1303
+ raise IOError("Cannot find:" + path)
1304
+
1305
+ def append_found_file(f):
1306
+ files.append(f)
1307
+ t.update()
1308
+
1309
+ def list_found_dir(path):
1310
+ """returns os.listdir(path) assuming os.path.isdir(path)"""
1311
+ listing = os.listdir(path)
1312
+ # subtract 1 since a "file" we found was actually this directory
1313
+ t.total += len(listing) - 1
1314
+ # fancy way to give info without forcing a refresh
1315
+ t.set_postfix(dir=path[-10:], refresh=False)
1316
+ t.update(0) # may trigger a refresh
1317
+ return listing
1318
+
1319
+ def recursively_search(path):
1320
+ if os.path.isdir(path):
1321
+ for f in list_found_dir(path):
1322
+ recursively_search(os.path.join(path, f))
1323
+ else:
1324
+ append_found_file(path)
1325
+
1326
+ recursively_search(path)
1327
+ t.set_postfix(dir=path)
1328
+ t.close()
1329
+ return files
1330
+
1331
+ Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger a
1332
+ display refresh to avoid console spamming.
1333
+
1334
+ Writing messages
1335
+ ~~~~~~~~~~~~~~~~
1336
+
1337
+ This is a work in progress (see
1338
+ `#737 <https://github.com/tqdm/tqdm/issues/737>`__).
1339
+
1340
+ Since ``tqdm`` uses a simple printing mechanism to display progress bars,
1341
+ you should not write any message in the terminal using ``print()`` while
1342
+ a progressbar is open.
1343
+
1344
+ To write messages in the terminal without any collision with ``tqdm`` bar
1345
+ display, a ``.write()`` method is provided:
1346
+
1347
+ .. code:: python
1348
+
1349
+ from tqdm.auto import tqdm, trange
1350
+ from time import sleep
1351
+
1352
+ bar = trange(10)
1353
+ for i in bar:
1354
+ # Print using tqdm class method .write()
1355
+ sleep(0.1)
1356
+ if not (i % 3):
1357
+ tqdm.write("Done task %i" % i)
1358
+ # Can also use bar.write()
1359
+
1360
+ By default, this will print to standard output ``sys.stdout``. but you can
1361
+ specify any file-like object using the ``file`` argument. For example, this
1362
+ can be used to redirect the messages writing to a log file or class.
1363
+
1364
+ Redirecting writing
1365
+ ~~~~~~~~~~~~~~~~~~~
1366
+
1367
+ If using a library that can print messages to the console, editing the library
1368
+ by replacing ``print()`` with ``tqdm.write()`` may not be desirable.
1369
+ In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
1370
+
1371
+ To redirect ``sys.stdout``, create a file-like class that will write
1372
+ any input string to ``tqdm.write()``, and supply the arguments
1373
+ ``file=sys.stdout, dynamic_ncols=True``.
1374
+
1375
+ A reusable canonical example is given below:
1376
+
1377
+ .. code:: python
1378
+
1379
+ from time import sleep
1380
+ import contextlib
1381
+ import sys
1382
+ from tqdm import tqdm
1383
+ from tqdm.contrib import DummyTqdmFile
1384
+
1385
+
1386
+ @contextlib.contextmanager
1387
+ def std_out_err_redirect_tqdm():
1388
+ orig_out_err = sys.stdout, sys.stderr
1389
+ try:
1390
+ sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
1391
+ yield orig_out_err[0]
1392
+ # Relay exceptions
1393
+ except Exception as exc:
1394
+ raise exc
1395
+ # Always restore sys.stdout/err if necessary
1396
+ finally:
1397
+ sys.stdout, sys.stderr = orig_out_err
1398
+
1399
+ def some_fun(i):
1400
+ print("Fee, fi, fo,".split()[i])
1401
+
1402
+ # Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
1403
+ with std_out_err_redirect_tqdm() as orig_stdout:
1404
+ # tqdm needs the original stdout
1405
+ # and dynamic_ncols=True to autodetect console width
1406
+ for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True):
1407
+ sleep(.5)
1408
+ some_fun(i)
1409
+
1410
+ # After the `with`, printing is restored
1411
+ print("Done!")
1412
+
1413
+ Redirecting ``logging``
1414
+ ~~~~~~~~~~~~~~~~~~~~~~~
1415
+
1416
+ Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``
1417
+ may also be redirected to ``tqdm.write()``.
1418
+
1419
+ Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure to
1420
+ redirect ``logging`` first if needed.
1421
+
1422
+ Helper methods are available in ``tqdm.contrib.logging``. For example:
1423
+
1424
+ .. code:: python
1425
+
1426
+ import logging
1427
+ from tqdm import trange
1428
+ from tqdm.contrib.logging import logging_redirect_tqdm
1429
+
1430
+ LOG = logging.getLogger(__name__)
1431
+
1432
+ if __name__ == '__main__':
1433
+ logging.basicConfig(level=logging.INFO)
1434
+ with logging_redirect_tqdm():
1435
+ for i in trange(9):
1436
+ if i == 4:
1437
+ LOG.info("console logging redirected to `tqdm.write()`")
1438
+ # logging restored
1439
+
1440
+ Monitoring thread, intervals and miniters
1441
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1442
+
1443
+ ``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
1444
+
1445
+ - Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long
1446
+ to wait between each refresh. ``tqdm`` always gets updated in the background,
1447
+ but it will display only every ``mininterval``.
1448
+ - Reduce number of calls to check system clock/time.
1449
+ - ``mininterval`` is more intuitive to configure than ``miniters``.
1450
+ A clever adjustment system ``dynamic_miniters`` will automatically adjust
1451
+ ``miniters`` to the amount of iterations that fit into time ``mininterval``.
1452
+ Essentially, ``tqdm`` will check if it's time to print without actually
1453
+ checking time. This behaviour can be still be bypassed by manually setting
1454
+ ``miniters``.
1455
+
1456
+ However, consider a case with a combination of fast and slow iterations.
1457
+ After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to a
1458
+ large number. When iteration rate subsequently slows, ``miniters`` will
1459
+ remain large and thus reduce display update frequency. To address this:
1460
+
1461
+ - ``maxinterval`` defines the maximum time between display refreshes.
1462
+ A concurrent monitoring thread checks for overdue updates and forces one
1463
+ where necessary.
1464
+
1465
+ The monitoring thread should not have a noticeable overhead, and guarantees
1466
+ updates at least every 10 seconds by default.
1467
+ This value can be directly changed by setting the ``monitor_interval`` of
1468
+ any ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).
1469
+ The monitor thread may be disabled application-wide by setting
1470
+ ``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
1471
+
1472
+
1473
+ Merch
1474
+ -----
1475
+
1476
+ You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
1477
+
1478
+ Contributions
1479
+ -------------
1480
+
1481
+ |GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
1482
+
1483
+ All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.
1484
+ Contributions are welcome.
1485
+
1486
+ See the
1487
+ `CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__
1488
+ file for more information.
1489
+
1490
+ Developers who have made significant contributions, ranked by *SLoC*
1491
+ (surviving lines of code,
1492
+ `git fame <https://github.com/casperdcl/git-fame>`__ ``-wMC --excl '\.(png|gif|jpg)$'``),
1493
+ are:
1494
+
1495
+ ==================== ======================================================== ==== ================================
1496
+ Name ID SLoC Notes
1497
+ ==================== ======================================================== ==== ================================
1498
+ Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ ~80% primary maintainer |Gift-Casper|
1499
+ Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ ~9% team member
1500
+ Martin Zugnoni `martinzugnoni <https://github.com/martinzugnoni>`__ ~3%
1501
+ Daniel Ecer `de-code <https://github.com/de-code>`__ ~2%
1502
+ Richard Sheridan `richardsheridan <https://github.com/richardsheridan>`__ ~1%
1503
+ Guangshuo Chen `chengs <https://github.com/chengs>`__ ~1%
1504
+ Helio Machado `0x2b3bfa0 <https://github.com/0x2b3bfa0>`__ ~1%
1505
+ Kyle Altendorf `altendky <https://github.com/altendky>`__ <1%
1506
+ Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ <1% original author
1507
+ Matthew Stevens `mjstevens777 <https://github.com/mjstevens777>`__ <1%
1508
+ Hadrien Mary `hadim <https://github.com/hadim>`__ <1% team member
1509
+ Mikhail Korobov `kmike <https://github.com/kmike>`__ <1% team member
1510
+ ==================== ======================================================== ==== ================================
1511
+
1512
+ Ports to Other Languages
1513
+ ~~~~~~~~~~~~~~~~~~~~~~~~
1514
+
1515
+ A list is available on
1516
+ `this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
1517
+
1518
+
1519
+ LICENCE
1520
+ -------
1521
+
1522
+ Open Source (OSI approved): |LICENCE|
1523
+
1524
+ Citation information: |DOI|
1525
+
1526
+ |README-Hits| (Since 19 May 2016)
1527
+
1528
+ .. |Logo| image:: https://tqdm.github.io/img/logo.gif
1529
+ .. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif
1530
+ .. |Video| image:: https://tqdm.github.io/img/video.jpg
1531
+ :target: https://tqdm.github.io/video
1532
+ .. |Slides| image:: https://tqdm.github.io/img/slides.jpg
1533
+ :target: https://tqdm.github.io/PyData2019/slides.html
1534
+ .. |Merch| image:: https://tqdm.github.io/img/merch.jpg
1535
+ :target: https://tqdm.github.io/merch
1536
+ .. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub
1537
+ :target: https://github.com/tqdm/tqdm/actions/workflows/test.yml
1538
+ .. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls
1539
+ :target: https://coveralls.io/github/tqdm/tqdm
1540
+ .. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg
1541
+ :target: https://codecov.io/gh/tqdm/tqdm
1542
+ .. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177
1543
+ :target: https://www.codacy.com/gh/tqdm/tqdm/dashboard
1544
+ .. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge
1545
+ :target: https://bestpractices.coreinfrastructure.org/projects/3264
1546
+ .. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white
1547
+ :target: https://github.com/tqdm/tqdm/releases
1548
+ .. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white
1549
+ :target: https://github.com/tqdm/tqdm/network
1550
+ .. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white
1551
+ :target: https://github.com/tqdm/tqdm/stargazers
1552
+ .. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white
1553
+ :target: https://github.com/tqdm/tqdm/graphs/commit-activity
1554
+ .. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white
1555
+ :target: https://github.com/tqdm/tqdm/issues?q=
1556
+ .. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white
1557
+ :target: https://github.com/tqdm/tqdm/pulls
1558
+ .. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white
1559
+ :target: https://github.com/tqdm/tqdm/graphs/contributors
1560
+ .. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed
1561
+ :target: https://github.com/tqdm/tqdm/pulse
1562
+ .. |Gift-Casper| image:: https://img.shields.io/badge/dynamic/json.svg?color=ff69b4&label=gifts%20received&prefix=%C2%A3&query=%24..sum&url=https%3A%2F%2Fcaspersci.uk.to%2Fgifts.json
1563
+ :target: https://cdcl.ml/sponsor
1564
+ .. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg
1565
+ :target: https://tqdm.github.io/releases
1566
+ .. |PyPI-Downloads| image:: https://img.shields.io/pypi/dm/tqdm.svg?label=pypi%20downloads&logo=PyPI&logoColor=white
1567
+ :target: https://pepy.tech/project/tqdm
1568
+ .. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white
1569
+ :target: https://pypi.org/project/tqdm
1570
+ .. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge
1571
+ :target: https://anaconda.org/conda-forge/tqdm
1572
+ .. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft
1573
+ :target: https://snapcraft.io/tqdm
1574
+ .. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white
1575
+ :target: https://hub.docker.com/r/tqdm/tqdm
1576
+ .. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white
1577
+ :target: https://libraries.io/pypi/tqdm
1578
+ .. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white
1579
+ :target: https://github.com/tqdm/tqdm/network/dependents
1580
+ .. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif
1581
+ :target: https://www.openhub.net/p/tqdm?ref=Thin+badge
1582
+ .. |awesome-python| image:: https://awesome.re/mentioned-badge.svg
1583
+ :target: https://github.com/vinta/awesome-python
1584
+ .. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg
1585
+ :target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE
1586
+ .. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg
1587
+ :target: https://doi.org/10.5281/zenodo.595120
1588
+ .. |binder-demo| image:: https://mybinder.org/badge_logo.svg
1589
+ :target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb
1590
+ .. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif
1591
+ .. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif
1592
+ .. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif
1593
+ .. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif
1594
+ :target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/RECORD ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/tqdm,sha256=akZSQuiOUlCAtUjEATi6BV-0M1Z7cRwIsxobbyAbeUM,229
2
+ tqdm-4.67.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
3
+ tqdm-4.67.1.dist-info/LICENCE,sha256=3DMlLoKQFeOxUAhvubOkD2rW-zLC9GEM6BL6Z301mGo,1985
4
+ tqdm-4.67.1.dist-info/METADATA,sha256=aIoWMt9SWhmP7FLc_vsSRtMerO6cA1qsrC1-r42P9mk,57675
5
+ tqdm-4.67.1.dist-info/RECORD,,
6
+ tqdm-4.67.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ tqdm-4.67.1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
8
+ tqdm-4.67.1.dist-info/entry_points.txt,sha256=ReJCH7Ui3Zyh6M16E4OhsZ1oU7WtMXCfbtoyBhGO29Y,39
9
+ tqdm-4.67.1.dist-info/top_level.txt,sha256=NLiUJNfmc9At15s7JURiwvqMEjUi9G5PMGRrmMYzNSM,5
10
+ tqdm/__init__.py,sha256=9mQNYSSqP99JasubEC1POJLMmhkkBH6cJZxPIR5G2pQ,1572
11
+ tqdm/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
12
+ tqdm/__pycache__/__init__.cpython-310.pyc,,
13
+ tqdm/__pycache__/__main__.cpython-310.pyc,,
14
+ tqdm/__pycache__/_dist_ver.cpython-310.pyc,,
15
+ tqdm/__pycache__/_main.cpython-310.pyc,,
16
+ tqdm/__pycache__/_monitor.cpython-310.pyc,,
17
+ tqdm/__pycache__/_tqdm.cpython-310.pyc,,
18
+ tqdm/__pycache__/_tqdm_gui.cpython-310.pyc,,
19
+ tqdm/__pycache__/_tqdm_notebook.cpython-310.pyc,,
20
+ tqdm/__pycache__/_tqdm_pandas.cpython-310.pyc,,
21
+ tqdm/__pycache__/_utils.cpython-310.pyc,,
22
+ tqdm/__pycache__/asyncio.cpython-310.pyc,,
23
+ tqdm/__pycache__/auto.cpython-310.pyc,,
24
+ tqdm/__pycache__/autonotebook.cpython-310.pyc,,
25
+ tqdm/__pycache__/cli.cpython-310.pyc,,
26
+ tqdm/__pycache__/dask.cpython-310.pyc,,
27
+ tqdm/__pycache__/gui.cpython-310.pyc,,
28
+ tqdm/__pycache__/keras.cpython-310.pyc,,
29
+ tqdm/__pycache__/notebook.cpython-310.pyc,,
30
+ tqdm/__pycache__/rich.cpython-310.pyc,,
31
+ tqdm/__pycache__/std.cpython-310.pyc,,
32
+ tqdm/__pycache__/tk.cpython-310.pyc,,
33
+ tqdm/__pycache__/utils.cpython-310.pyc,,
34
+ tqdm/__pycache__/version.cpython-310.pyc,,
35
+ tqdm/_dist_ver.py,sha256=m5AdYI-jB-v6P0VJ_70isH_p24EzSOGSwVvuAZmkmKY,23
36
+ tqdm/_main.py,sha256=9ySvgmi_2Sw4CAo5UDW0Q2dxfTryboEWGHohfCJz0sA,283
37
+ tqdm/_monitor.py,sha256=Uku-DPWgzJ7dO5CK08xKJK-E_F6qQ-JB3ksuXczSYR0,3699
38
+ tqdm/_tqdm.py,sha256=LfLCuJ6bpsVo9xilmtBXyEm1vGnUCFrliW85j3J-nD4,283
39
+ tqdm/_tqdm_gui.py,sha256=03Hc8KayxJveieI5-0-2NGiDpLvw9jZekofJUV7CCwk,287
40
+ tqdm/_tqdm_notebook.py,sha256=BuHiLuxu6uEfZFaPJW3RPpPaxaVctEQA3kdSJSDL1hw,307
41
+ tqdm/_tqdm_pandas.py,sha256=c9jptUgigN6axRDhRd4Rif98Tmxeopc1nFNFhIpbFUE,888
42
+ tqdm/_utils.py,sha256=_4E73bfDj4f1s3sM42NLHNrZDOkijZoWq-n6xWLkdZ8,553
43
+ tqdm/asyncio.py,sha256=Kp2rSkNRf9KRqa3d9YpgeZQ7L7EZf2Ki4bSc7UPIyoo,2757
44
+ tqdm/auto.py,sha256=nDZflj6p2zKkjBCNBourrhS81zYfZy1_dQvbckrdW8o,871
45
+ tqdm/autonotebook.py,sha256=Yb9F5uaiBPhfbDDFpbtoG8I2YUw3uQJ89rUDLbfR6ws,956
46
+ tqdm/cli.py,sha256=SbKlN8QyZ2ogenqt-wT_p6_sx2OOdCjCyhoZBFnlmyI,11010
47
+ tqdm/completion.sh,sha256=j79KbSmpIj_E11jfTfBXrGnUTzKXVpQ1vGVQvsyDRl4,946
48
+ tqdm/contrib/__init__.py,sha256=OgSwVXm-vlDJ-2imtoQ9z8qdom4snMSRztH72KMA82A,2494
49
+ tqdm/contrib/__pycache__/__init__.cpython-310.pyc,,
50
+ tqdm/contrib/__pycache__/bells.cpython-310.pyc,,
51
+ tqdm/contrib/__pycache__/concurrent.cpython-310.pyc,,
52
+ tqdm/contrib/__pycache__/discord.cpython-310.pyc,,
53
+ tqdm/contrib/__pycache__/itertools.cpython-310.pyc,,
54
+ tqdm/contrib/__pycache__/logging.cpython-310.pyc,,
55
+ tqdm/contrib/__pycache__/slack.cpython-310.pyc,,
56
+ tqdm/contrib/__pycache__/telegram.cpython-310.pyc,,
57
+ tqdm/contrib/__pycache__/utils_worker.cpython-310.pyc,,
58
+ tqdm/contrib/bells.py,sha256=Yx1HqGCmHrESCAO700j5wE__JCleNODJxedh1ijPLD0,837
59
+ tqdm/contrib/concurrent.py,sha256=K1yjloKS5WRNFyjLRth0DmU5PAnDbF0A-GD27N-J4a8,3986
60
+ tqdm/contrib/discord.py,sha256=MtVIL1s_dxH21G4sL8FBgQ4Wei23ho9Ek5T-AommvNc,5243
61
+ tqdm/contrib/itertools.py,sha256=WdKKQU5eSzsqHu29SN_oH12huYZo0Jihqoi9-nVhwz4,774
62
+ tqdm/contrib/logging.py,sha256=NsYtnKttj2mMrGm58mEdo5a9DP_2vv8pZyrimSuWulA,3760
63
+ tqdm/contrib/slack.py,sha256=eP_Mr5sQonYniHxxQNGue3jk2JkIPmPWFZqIYxnOui0,4007
64
+ tqdm/contrib/telegram.py,sha256=vn_9SATMbbwn2PAbzSDyOX6av3eBB01QBug11P4H-Og,5008
65
+ tqdm/contrib/utils_worker.py,sha256=HJP5Mz1S1xyzEke2JaqJ2sYLHXADYoo2epT5AzQ38eA,1207
66
+ tqdm/dask.py,sha256=9Ei58eVqTossRLhAfWyUFCduXYKjmLmwkaXIy-CHYfs,1319
67
+ tqdm/gui.py,sha256=STIB3K8iDzDgkNUqWIpvcI_u0OGtbGNy5NwpALXhfWs,5479
68
+ tqdm/keras.py,sha256=op9sBkb6q6c6dw2wJ0SD2ZwpPK7yM1Vbg4l1Qiy3MIo,4373
69
+ tqdm/notebook.py,sha256=GtZ3IapLL1v8WNDaTSvPw0bJGTyfp71Vfz5HDnAzx1M,10895
70
+ tqdm/rich.py,sha256=YyMPkEHVyYUVUR3adJKbVX26iTmNKpNMf3DEqmm-m60,5021
71
+ tqdm/std.py,sha256=tWjz6-QCa92aqYjz7PIdkLUCAfiy-lJZheBtZyIIyO0,57461
72
+ tqdm/tk.py,sha256=Gu0uwXwLCGPRGHORdi3WvBLGiseUp_xxX_h_gp9VpK0,6701
73
+ tqdm/tqdm.1,sha256=aILyUPk2S4OPe_uWy2P4AMjUf0oQ6PUW0nLYXB-BWwI,7889
74
+ tqdm/utils.py,sha256=6E0BQw3Sg7uGWKBM_cDn3P42tXswRhzkggbhBgLDjl8,11821
75
+ tqdm/version.py,sha256=-1yWjfu3P0eghVsysHH07fbzdiADNRdzRtYPqOaqR2A,333
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/REQUESTED ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.6.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ tqdm = tqdm.cli:main
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm-4.67.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ tqdm
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_main.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .cli import * # NOQA
4
+ from .cli import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.cli.*` instead of `tqdm._main.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_monitor.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ from threading import Event, Thread, current_thread
3
+ from time import time
4
+ from warnings import warn
5
+
6
+ __all__ = ["TMonitor", "TqdmSynchronisationWarning"]
7
+
8
+
9
+ class TqdmSynchronisationWarning(RuntimeWarning):
10
+ """tqdm multi-thread/-process errors which may cause incorrect nesting
11
+ but otherwise no adverse effects"""
12
+ pass
13
+
14
+
15
+ class TMonitor(Thread):
16
+ """
17
+ Monitoring thread for tqdm bars.
18
+ Monitors if tqdm bars are taking too much time to display
19
+ and readjusts miniters automatically if necessary.
20
+
21
+ Parameters
22
+ ----------
23
+ tqdm_cls : class
24
+ tqdm class to use (can be core tqdm or a submodule).
25
+ sleep_interval : float
26
+ Time to sleep between monitoring checks.
27
+ """
28
+ _test = {} # internal vars for unit testing
29
+
30
+ def __init__(self, tqdm_cls, sleep_interval):
31
+ Thread.__init__(self)
32
+ self.daemon = True # kill thread when main killed (KeyboardInterrupt)
33
+ self.woken = 0 # last time woken up, to sync with monitor
34
+ self.tqdm_cls = tqdm_cls
35
+ self.sleep_interval = sleep_interval
36
+ self._time = self._test.get("time", time)
37
+ self.was_killed = self._test.get("Event", Event)()
38
+ atexit.register(self.exit)
39
+ self.start()
40
+
41
+ def exit(self):
42
+ self.was_killed.set()
43
+ if self is not current_thread():
44
+ self.join()
45
+ return self.report()
46
+
47
+ def get_instances(self):
48
+ # returns a copy of started `tqdm_cls` instances
49
+ return [i for i in self.tqdm_cls._instances.copy()
50
+ # Avoid race by checking that the instance started
51
+ if hasattr(i, 'start_t')]
52
+
53
+ def run(self):
54
+ cur_t = self._time()
55
+ while True:
56
+ # After processing and before sleeping, notify that we woke
57
+ # Need to be done just before sleeping
58
+ self.woken = cur_t
59
+ # Sleep some time...
60
+ self.was_killed.wait(self.sleep_interval)
61
+ # Quit if killed
62
+ if self.was_killed.is_set():
63
+ return
64
+ # Then monitor!
65
+ # Acquire lock (to access _instances)
66
+ with self.tqdm_cls.get_lock():
67
+ cur_t = self._time()
68
+ # Check tqdm instances are waiting too long to print
69
+ instances = self.get_instances()
70
+ for instance in instances:
71
+ # Check event in loop to reduce blocking time on exit
72
+ if self.was_killed.is_set():
73
+ return
74
+ # Only if mininterval > 1 (else iterations are just slow)
75
+ # and last refresh exceeded maxinterval
76
+ if (
77
+ instance.miniters > 1
78
+ and (cur_t - instance.last_print_t) >= instance.maxinterval
79
+ ):
80
+ # force bypassing miniters on next iteration
81
+ # (dynamic_miniters adjusts mininterval automatically)
82
+ instance.miniters = 1
83
+ # Refresh now! (works only for manual tqdm)
84
+ instance.refresh(nolock=True)
85
+ # Remove accidental long-lived strong reference
86
+ del instance
87
+ if instances != self.get_instances(): # pragma: nocover
88
+ warn("Set changed size during iteration" +
89
+ " (see https://github.com/tqdm/tqdm/issues/481)",
90
+ TqdmSynchronisationWarning, stacklevel=2)
91
+ # Remove accidental long-lived strong references
92
+ del instances
93
+
94
+ def report(self):
95
+ return not self.was_killed.is_set()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .std import * # NOQA
4
+ from .std import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.std.*` instead of `tqdm._tqdm.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm_gui.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .gui import * # NOQA
4
+ from .gui import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.gui.*` instead of `tqdm._tqdm_gui.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm_notebook.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .notebook import * # NOQA
4
+ from .notebook import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.notebook.*` instead of `tqdm._tqdm_notebook.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_tqdm_pandas.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ __author__ = "github.com/casperdcl"
4
+ __all__ = ['tqdm_pandas']
5
+
6
+
7
+ def tqdm_pandas(tclass, **tqdm_kwargs):
8
+ """
9
+ Registers the given `tqdm` instance with
10
+ `pandas.core.groupby.DataFrameGroupBy.progress_apply`.
11
+ """
12
+ from tqdm import TqdmDeprecationWarning
13
+
14
+ if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(
15
+ 'tqdm_')): # delayed adapter case
16
+ TqdmDeprecationWarning(
17
+ "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.",
18
+ fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))
19
+ tclass.pandas(**tqdm_kwargs)
20
+ else:
21
+ TqdmDeprecationWarning(
22
+ "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.",
23
+ fp_write=getattr(tclass.fp, 'write', sys.stderr.write))
24
+ type(tclass).pandas(deprecated_t=tclass)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/_utils.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .std import TqdmDeprecationWarning
4
+ from .utils import ( # NOQA, pylint: disable=unused-import
5
+ CUR_OS, IS_NIX, IS_WIN, RE_ANSI, Comparable, FormatReplace, SimpleTextIOWrapper,
6
+ _environ_cols_wrapper, _is_ascii, _is_utf, _screen_shape_linux, _screen_shape_tput,
7
+ _screen_shape_windows, _screen_shape_wrapper, _supports_unicode, _term_move_up, colorama)
8
+
9
+ warn("This function will be removed in tqdm==5.0.0\n"
10
+ "Please use `tqdm.utils.*` instead of `tqdm._utils.*`",
11
+ TqdmDeprecationWarning, stacklevel=2)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/asyncio.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Asynchronous progressbar decorator for iterators.
3
+ Includes a default `range` iterator printing to `stderr`.
4
+
5
+ Usage:
6
+ >>> from tqdm.asyncio import trange, tqdm
7
+ >>> async for i in trange(10):
8
+ ... ...
9
+ """
10
+ import asyncio
11
+ from sys import version_info
12
+
13
+ from .std import tqdm as std_tqdm
14
+
15
+ __author__ = {"github.com/": ["casperdcl"]}
16
+ __all__ = ['tqdm_asyncio', 'tarange', 'tqdm', 'trange']
17
+
18
+
19
+ class tqdm_asyncio(std_tqdm):
20
+ """
21
+ Asynchronous-friendly version of tqdm.
22
+ """
23
+ def __init__(self, iterable=None, *args, **kwargs):
24
+ super().__init__(iterable, *args, **kwargs)
25
+ self.iterable_awaitable = False
26
+ if iterable is not None:
27
+ if hasattr(iterable, "__anext__"):
28
+ self.iterable_next = iterable.__anext__
29
+ self.iterable_awaitable = True
30
+ elif hasattr(iterable, "__next__"):
31
+ self.iterable_next = iterable.__next__
32
+ else:
33
+ self.iterable_iterator = iter(iterable)
34
+ self.iterable_next = self.iterable_iterator.__next__
35
+
36
+ def __aiter__(self):
37
+ return self
38
+
39
+ async def __anext__(self):
40
+ try:
41
+ if self.iterable_awaitable:
42
+ res = await self.iterable_next()
43
+ else:
44
+ res = self.iterable_next()
45
+ self.update()
46
+ return res
47
+ except StopIteration:
48
+ self.close()
49
+ raise StopAsyncIteration
50
+ except BaseException:
51
+ self.close()
52
+ raise
53
+
54
+ def send(self, *args, **kwargs):
55
+ return self.iterable.send(*args, **kwargs)
56
+
57
+ @classmethod
58
+ def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs):
59
+ """
60
+ Wrapper for `asyncio.as_completed`.
61
+ """
62
+ if total is None:
63
+ total = len(fs)
64
+ kwargs = {}
65
+ if version_info[:2] < (3, 10):
66
+ kwargs['loop'] = loop
67
+ yield from cls(asyncio.as_completed(fs, timeout=timeout, **kwargs),
68
+ total=total, **tqdm_kwargs)
69
+
70
+ @classmethod
71
+ async def gather(cls, *fs, loop=None, timeout=None, total=None, **tqdm_kwargs):
72
+ """
73
+ Wrapper for `asyncio.gather`.
74
+ """
75
+ async def wrap_awaitable(i, f):
76
+ return i, await f
77
+
78
+ ifs = [wrap_awaitable(i, f) for i, f in enumerate(fs)]
79
+ res = [await f for f in cls.as_completed(ifs, loop=loop, timeout=timeout,
80
+ total=total, **tqdm_kwargs)]
81
+ return [i for _, i in sorted(res)]
82
+
83
+
84
+ def tarange(*args, **kwargs):
85
+ """
86
+ A shortcut for `tqdm.asyncio.tqdm(range(*args), **kwargs)`.
87
+ """
88
+ return tqdm_asyncio(range(*args), **kwargs)
89
+
90
+
91
+ # Aliases
92
+ tqdm = tqdm_asyncio
93
+ trange = tarange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/auto.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enables multiple commonly used features.
3
+
4
+ Method resolution order:
5
+
6
+ - `tqdm.autonotebook` without import warnings
7
+ - `tqdm.asyncio`
8
+ - `tqdm.std` base class
9
+
10
+ Usage:
11
+ >>> from tqdm.auto import trange, tqdm
12
+ >>> for i in trange(10):
13
+ ... ...
14
+ """
15
+ import warnings
16
+
17
+ from .std import TqdmExperimentalWarning
18
+
19
+ with warnings.catch_warnings():
20
+ warnings.simplefilter("ignore", category=TqdmExperimentalWarning)
21
+ from .autonotebook import tqdm as notebook_tqdm
22
+
23
+ from .asyncio import tqdm as asyncio_tqdm
24
+ from .std import tqdm as std_tqdm
25
+
26
+ if notebook_tqdm != std_tqdm:
27
+ class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro
28
+ pass
29
+ else:
30
+ tqdm = asyncio_tqdm
31
+
32
+
33
+ def trange(*args, **kwargs):
34
+ """
35
+ A shortcut for `tqdm.auto.tqdm(range(*args), **kwargs)`.
36
+ """
37
+ return tqdm(range(*args), **kwargs)
38
+
39
+
40
+ __all__ = ["tqdm", "trange"]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/autonotebook.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Automatically choose between `tqdm.notebook` and `tqdm.std`.
3
+
4
+ Usage:
5
+ >>> from tqdm.autonotebook import trange, tqdm
6
+ >>> for i in trange(10):
7
+ ... ...
8
+ """
9
+ import sys
10
+ from warnings import warn
11
+
12
+ try:
13
+ get_ipython = sys.modules['IPython'].get_ipython
14
+ if 'IPKernelApp' not in get_ipython().config: # pragma: no cover
15
+ raise ImportError("console")
16
+ from .notebook import WARN_NOIPYW, IProgress
17
+ if IProgress is None:
18
+ from .std import TqdmWarning
19
+ warn(WARN_NOIPYW, TqdmWarning, stacklevel=2)
20
+ raise ImportError('ipywidgets')
21
+ except Exception:
22
+ from .std import tqdm, trange
23
+ else: # pragma: no cover
24
+ from .notebook import tqdm, trange
25
+ from .std import TqdmExperimentalWarning
26
+ warn("Using `tqdm.autonotebook.tqdm` in notebook mode."
27
+ " Use `tqdm.tqdm` instead to force console mode"
28
+ " (e.g. in jupyter console)", TqdmExperimentalWarning, stacklevel=2)
29
+ __all__ = ["tqdm", "trange"]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/cli.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module version for monitoring CLI pipes (`... | python -m tqdm | ...`).
3
+ """
4
+ import logging
5
+ import re
6
+ import sys
7
+ from ast import literal_eval as numeric
8
+ from textwrap import indent
9
+
10
+ from .std import TqdmKeyError, TqdmTypeError, tqdm
11
+ from .version import __version__
12
+
13
+ __all__ = ["main"]
14
+ log = logging.getLogger(__name__)
15
+
16
+
17
+ def cast(val, typ):
18
+ log.debug((val, typ))
19
+ if " or " in typ:
20
+ for t in typ.split(" or "):
21
+ try:
22
+ return cast(val, t)
23
+ except TqdmTypeError:
24
+ pass
25
+ raise TqdmTypeError(f"{val} : {typ}")
26
+
27
+ # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n')
28
+ if typ == 'bool':
29
+ if (val == 'True') or (val == ''):
30
+ return True
31
+ if val == 'False':
32
+ return False
33
+ raise TqdmTypeError(val + ' : ' + typ)
34
+ if typ == 'chr':
35
+ if len(val) == 1:
36
+ return val.encode()
37
+ if re.match(r"^\\\w+$", val):
38
+ return eval(f'"{val}"').encode()
39
+ raise TqdmTypeError(f"{val} : {typ}")
40
+ if typ == 'str':
41
+ return val
42
+ if typ == 'int':
43
+ try:
44
+ return int(val)
45
+ except ValueError as exc:
46
+ raise TqdmTypeError(f"{val} : {typ}") from exc
47
+ if typ == 'float':
48
+ try:
49
+ return float(val)
50
+ except ValueError as exc:
51
+ raise TqdmTypeError(f"{val} : {typ}") from exc
52
+ raise TqdmTypeError(f"{val} : {typ}")
53
+
54
+
55
+ def posix_pipe(fin, fout, delim=b'\\n', buf_size=256,
56
+ callback=lambda float: None, callback_len=True):
57
+ """
58
+ Params
59
+ ------
60
+ fin : binary file with `read(buf_size : int)` method
61
+ fout : binary file with `write` (and optionally `flush`) methods.
62
+ callback : function(float), e.g.: `tqdm.update`
63
+ callback_len : If (default: True) do `callback(len(buffer))`.
64
+ Otherwise, do `callback(data) for data in buffer.split(delim)`.
65
+ """
66
+ fp_write = fout.write
67
+
68
+ if not delim:
69
+ while True:
70
+ tmp = fin.read(buf_size)
71
+
72
+ # flush at EOF
73
+ if not tmp:
74
+ getattr(fout, 'flush', lambda: None)()
75
+ return
76
+
77
+ fp_write(tmp)
78
+ callback(len(tmp))
79
+ # return
80
+
81
+ buf = b''
82
+ len_delim = len(delim)
83
+ # n = 0
84
+ while True:
85
+ tmp = fin.read(buf_size)
86
+
87
+ # flush at EOF
88
+ if not tmp:
89
+ if buf:
90
+ fp_write(buf)
91
+ if callback_len:
92
+ # n += 1 + buf.count(delim)
93
+ callback(1 + buf.count(delim))
94
+ else:
95
+ for i in buf.split(delim):
96
+ callback(i)
97
+ getattr(fout, 'flush', lambda: None)()
98
+ return # n
99
+
100
+ while True:
101
+ i = tmp.find(delim)
102
+ if i < 0:
103
+ buf += tmp
104
+ break
105
+ fp_write(buf + tmp[:i + len(delim)])
106
+ # n += 1
107
+ callback(1 if callback_len else (buf + tmp[:i]))
108
+ buf = b''
109
+ tmp = tmp[i + len_delim:]
110
+
111
+
112
+ # ((opt, type), ... )
113
+ RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)')
114
+ # better split method assuming no positional args
115
+ RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)')
116
+
117
+ # TODO: add custom support for some of the following?
118
+ UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file')
119
+
120
+ # The 8 leading spaces are required for consistency
121
+ CLI_EXTRA_DOC = r"""
122
+ Extra CLI Options
123
+ -----------------
124
+ name : type, optional
125
+ TODO: find out why this is needed.
126
+ delim : chr, optional
127
+ Delimiting character [default: '\n']. Use '\0' for null.
128
+ N.B.: on Windows systems, Python converts '\n' to '\r\n'.
129
+ buf_size : int, optional
130
+ String buffer size in bytes [default: 256]
131
+ used when `delim` is specified.
132
+ bytes : bool, optional
133
+ If true, will count bytes, ignore `delim`, and default
134
+ `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'.
135
+ tee : bool, optional
136
+ If true, passes `stdin` to both `stderr` and `stdout`.
137
+ update : bool, optional
138
+ If true, will treat input as newly elapsed iterations,
139
+ i.e. numbers to pass to `update()`. Note that this is slow
140
+ (~2e5 it/s) since every input must be decoded as a number.
141
+ update_to : bool, optional
142
+ If true, will treat input as total elapsed iterations,
143
+ i.e. numbers to assign to `self.n`. Note that this is slow
144
+ (~2e5 it/s) since every input must be decoded as a number.
145
+ null : bool, optional
146
+ If true, will discard input (no stdout).
147
+ manpath : str, optional
148
+ Directory in which to install tqdm man pages.
149
+ comppath : str, optional
150
+ Directory in which to place tqdm completion.
151
+ log : str, optional
152
+ CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
153
+ """
154
+
155
+
156
+ def main(fp=sys.stderr, argv=None):
157
+ """
158
+ Parameters (internal use only)
159
+ ---------
160
+ fp : file-like object for tqdm
161
+ argv : list (default: sys.argv[1:])
162
+ """
163
+ if argv is None:
164
+ argv = sys.argv[1:]
165
+ try:
166
+ log_idx = argv.index('--log')
167
+ except ValueError:
168
+ for i in argv:
169
+ if i.startswith('--log='):
170
+ logLevel = i[len('--log='):]
171
+ break
172
+ else:
173
+ logLevel = 'INFO'
174
+ else:
175
+ # argv.pop(log_idx)
176
+ # logLevel = argv.pop(log_idx)
177
+ logLevel = argv[log_idx + 1]
178
+ logging.basicConfig(level=getattr(logging, logLevel),
179
+ format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
180
+
181
+ # py<3.13 doesn't dedent docstrings
182
+ d = (tqdm.__doc__ if sys.version_info < (3, 13)
183
+ else indent(tqdm.__doc__, " ")) + CLI_EXTRA_DOC
184
+
185
+ opt_types = dict(RE_OPTS.findall(d))
186
+ # opt_types['delim'] = 'chr'
187
+
188
+ for o in UNSUPPORTED_OPTS:
189
+ opt_types.pop(o)
190
+
191
+ log.debug(sorted(opt_types.items()))
192
+
193
+ # d = RE_OPTS.sub(r' --\1=<\1> : \2', d)
194
+ split = RE_OPTS.split(d)
195
+ opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
196
+ d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else
197
+ '\n --{0}=<{1}> : {2}{3}').format(
198
+ otd[0].replace('_', '-'), otd[0], *otd[1:])
199
+ for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS)
200
+
201
+ help_short = "Usage:\n tqdm [--help | options]\n"
202
+ d = help_short + """
203
+ Options:
204
+ -h, --help Print this help and exit.
205
+ -v, --version Print version and exit.
206
+ """ + d.strip('\n') + '\n'
207
+
208
+ # opts = docopt(d, version=__version__)
209
+ if any(v in argv for v in ('-v', '--version')):
210
+ sys.stdout.write(__version__ + '\n')
211
+ sys.exit(0)
212
+ elif any(v in argv for v in ('-h', '--help')):
213
+ sys.stdout.write(d + '\n')
214
+ sys.exit(0)
215
+ elif argv and argv[0][:2] != '--':
216
+ sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}")
217
+
218
+ argv = RE_SHLEX.split(' '.join(["tqdm"] + argv))
219
+ opts = dict(zip(argv[1::3], argv[3::3]))
220
+
221
+ log.debug(opts)
222
+ opts.pop('log', True)
223
+
224
+ tqdm_args = {'file': fp}
225
+ try:
226
+ for (o, v) in opts.items():
227
+ o = o.replace('-', '_')
228
+ try:
229
+ tqdm_args[o] = cast(v, opt_types[o])
230
+ except KeyError as e:
231
+ raise TqdmKeyError(str(e))
232
+ log.debug('args:' + str(tqdm_args))
233
+
234
+ delim_per_char = tqdm_args.pop('bytes', False)
235
+ update = tqdm_args.pop('update', False)
236
+ update_to = tqdm_args.pop('update_to', False)
237
+ if sum((delim_per_char, update, update_to)) > 1:
238
+ raise TqdmKeyError("Can only have one of --bytes --update --update_to")
239
+ except Exception:
240
+ fp.write("\nError:\n" + help_short)
241
+ stdin, stdout_write = sys.stdin, sys.stdout.write
242
+ for i in stdin:
243
+ stdout_write(i)
244
+ raise
245
+ else:
246
+ buf_size = tqdm_args.pop('buf_size', 256)
247
+ delim = tqdm_args.pop('delim', b'\\n')
248
+ tee = tqdm_args.pop('tee', False)
249
+ manpath = tqdm_args.pop('manpath', None)
250
+ comppath = tqdm_args.pop('comppath', None)
251
+ if tqdm_args.pop('null', False):
252
+ class stdout(object):
253
+ @staticmethod
254
+ def write(_):
255
+ pass
256
+ else:
257
+ stdout = sys.stdout
258
+ stdout = getattr(stdout, 'buffer', stdout)
259
+ stdin = getattr(sys.stdin, 'buffer', sys.stdin)
260
+ if manpath or comppath:
261
+ try: # py<3.9
262
+ import importlib_resources as resources
263
+ except ImportError:
264
+ from importlib import resources
265
+ from pathlib import Path
266
+
267
+ def cp(name, dst):
268
+ """copy resource `name` to `dst`"""
269
+ fi = resources.files('tqdm') / name
270
+ dst.write_bytes(fi.read_bytes())
271
+ log.info("written:%s", dst)
272
+ if manpath is not None:
273
+ cp('tqdm.1', Path(manpath) / 'tqdm.1')
274
+ if comppath is not None:
275
+ cp('completion.sh', Path(comppath) / 'tqdm_completion.sh')
276
+ sys.exit(0)
277
+ if tee:
278
+ stdout_write = stdout.write
279
+ fp_write = getattr(fp, 'buffer', fp).write
280
+
281
+ class stdout(object): # pylint: disable=function-redefined
282
+ @staticmethod
283
+ def write(x):
284
+ with tqdm.external_write_mode(file=fp):
285
+ fp_write(x)
286
+ stdout_write(x)
287
+ if delim_per_char:
288
+ tqdm_args.setdefault('unit', 'B')
289
+ tqdm_args.setdefault('unit_scale', True)
290
+ tqdm_args.setdefault('unit_divisor', 1024)
291
+ log.debug(tqdm_args)
292
+ with tqdm(**tqdm_args) as t:
293
+ posix_pipe(stdin, stdout, '', buf_size, t.update)
294
+ elif delim == b'\\n':
295
+ log.debug(tqdm_args)
296
+ write = stdout.write
297
+ if update or update_to:
298
+ with tqdm(**tqdm_args) as t:
299
+ if update:
300
+ def callback(i):
301
+ t.update(numeric(i.decode()))
302
+ else: # update_to
303
+ def callback(i):
304
+ t.update(numeric(i.decode()) - t.n)
305
+ for i in stdin:
306
+ write(i)
307
+ callback(i)
308
+ else:
309
+ for i in tqdm(stdin, **tqdm_args):
310
+ write(i)
311
+ else:
312
+ log.debug(tqdm_args)
313
+ with tqdm(**tqdm_args) as t:
314
+ callback_len = False
315
+ if update:
316
+ def callback(i):
317
+ t.update(numeric(i.decode()))
318
+ elif update_to:
319
+ def callback(i):
320
+ t.update(numeric(i.decode()) - t.n)
321
+ else:
322
+ callback = t.update
323
+ callback_len = True
324
+ posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/completion.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ _tqdm(){
3
+ local cur prv
4
+ cur="${COMP_WORDS[COMP_CWORD]}"
5
+ prv="${COMP_WORDS[COMP_CWORD - 1]}"
6
+
7
+ case ${prv} in
8
+ --bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor)
9
+ # await user input
10
+ ;;
11
+ "--log")
12
+ COMPREPLY=($(compgen -W 'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur}))
13
+ ;;
14
+ *)
15
+ COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur}))
16
+ ;;
17
+ esac
18
+ }
19
+ complete -F _tqdm tqdm
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/__init__.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around common functions.
3
+
4
+ Subpackages contain potentially unstable extensions.
5
+ """
6
+ from warnings import warn
7
+
8
+ from ..auto import tqdm as tqdm_auto
9
+ from ..std import TqdmDeprecationWarning, tqdm
10
+ from ..utils import ObjectWrapper
11
+
12
+ __author__ = {"github.com/": ["casperdcl"]}
13
+ __all__ = ['tenumerate', 'tzip', 'tmap']
14
+
15
+
16
+ class DummyTqdmFile(ObjectWrapper):
17
+ """Dummy file-like that will write to tqdm"""
18
+
19
+ def __init__(self, wrapped):
20
+ super().__init__(wrapped)
21
+ self._buf = []
22
+
23
+ def write(self, x, nolock=False):
24
+ nl = b"\n" if isinstance(x, bytes) else "\n"
25
+ pre, sep, post = x.rpartition(nl)
26
+ if sep:
27
+ blank = type(nl)()
28
+ tqdm.write(blank.join(self._buf + [pre, sep]),
29
+ end=blank, file=self._wrapped, nolock=nolock)
30
+ self._buf = [post]
31
+ else:
32
+ self._buf.append(x)
33
+
34
+ def __del__(self):
35
+ if self._buf:
36
+ blank = type(self._buf[0])()
37
+ try:
38
+ tqdm.write(blank.join(self._buf), end=blank, file=self._wrapped)
39
+ except (OSError, ValueError):
40
+ pass
41
+
42
+
43
+ def builtin_iterable(func):
44
+ """Returns `func`"""
45
+ warn("This function has no effect, and will be removed in tqdm==5.0.0",
46
+ TqdmDeprecationWarning, stacklevel=2)
47
+ return func
48
+
49
+
50
+ def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, **tqdm_kwargs):
51
+ """
52
+ Equivalent of `numpy.ndenumerate` or builtin `enumerate`.
53
+
54
+ Parameters
55
+ ----------
56
+ tqdm_class : [default: tqdm.auto.tqdm].
57
+ """
58
+ try:
59
+ import numpy as np
60
+ except ImportError:
61
+ pass
62
+ else:
63
+ if isinstance(iterable, np.ndarray):
64
+ return tqdm_class(np.ndenumerate(iterable), total=total or iterable.size,
65
+ **tqdm_kwargs)
66
+ return enumerate(tqdm_class(iterable, total=total, **tqdm_kwargs), start)
67
+
68
+
69
+ def tzip(iter1, *iter2plus, **tqdm_kwargs):
70
+ """
71
+ Equivalent of builtin `zip`.
72
+
73
+ Parameters
74
+ ----------
75
+ tqdm_class : [default: tqdm.auto.tqdm].
76
+ """
77
+ kwargs = tqdm_kwargs.copy()
78
+ tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
79
+ for i in zip(tqdm_class(iter1, **kwargs), *iter2plus):
80
+ yield i
81
+
82
+
83
+ def tmap(function, *sequences, **tqdm_kwargs):
84
+ """
85
+ Equivalent of builtin `map`.
86
+
87
+ Parameters
88
+ ----------
89
+ tqdm_class : [default: tqdm.auto.tqdm].
90
+ """
91
+ for i in tzip(*sequences, **tqdm_kwargs):
92
+ yield function(*i)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/bells.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Even more features than `tqdm.auto` (all the bells & whistles):
3
+
4
+ - `tqdm.auto`
5
+ - `tqdm.tqdm.pandas`
6
+ - `tqdm.contrib.telegram`
7
+ + uses `${TQDM_TELEGRAM_TOKEN}` and `${TQDM_TELEGRAM_CHAT_ID}`
8
+ - `tqdm.contrib.discord`
9
+ + uses `${TQDM_DISCORD_TOKEN}` and `${TQDM_DISCORD_CHANNEL_ID}`
10
+ """
11
+ __all__ = ['tqdm', 'trange']
12
+ import warnings
13
+ from os import getenv
14
+
15
+ if getenv("TQDM_SLACK_TOKEN") and getenv("TQDM_SLACK_CHANNEL"):
16
+ from .slack import tqdm, trange
17
+ elif getenv("TQDM_TELEGRAM_TOKEN") and getenv("TQDM_TELEGRAM_CHAT_ID"):
18
+ from .telegram import tqdm, trange
19
+ elif getenv("TQDM_DISCORD_TOKEN") and getenv("TQDM_DISCORD_CHANNEL_ID"):
20
+ from .discord import tqdm, trange
21
+ else:
22
+ from ..auto import tqdm, trange
23
+
24
+ with warnings.catch_warnings():
25
+ warnings.simplefilter("ignore", category=FutureWarning)
26
+ tqdm.pandas()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/concurrent.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around `concurrent.futures`.
3
+ """
4
+ from contextlib import contextmanager
5
+ from operator import length_hint
6
+ from os import cpu_count
7
+
8
+ from ..auto import tqdm as tqdm_auto
9
+ from ..std import TqdmWarning
10
+
11
+ __author__ = {"github.com/": ["casperdcl"]}
12
+ __all__ = ['thread_map', 'process_map']
13
+
14
+
15
+ @contextmanager
16
+ def ensure_lock(tqdm_class, lock_name=""):
17
+ """get (create if necessary) and then restore `tqdm_class`'s lock"""
18
+ old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock
19
+ lock = old_lock or tqdm_class.get_lock() # maybe create a new lock
20
+ lock = getattr(lock, lock_name, lock) # maybe subtype
21
+ tqdm_class.set_lock(lock)
22
+ yield lock
23
+ if old_lock is None:
24
+ del tqdm_class._lock
25
+ else:
26
+ tqdm_class.set_lock(old_lock)
27
+
28
+
29
+ def _executor_map(PoolExecutor, fn, *iterables, **tqdm_kwargs):
30
+ """
31
+ Implementation of `thread_map` and `process_map`.
32
+
33
+ Parameters
34
+ ----------
35
+ tqdm_class : [default: tqdm.auto.tqdm].
36
+ max_workers : [default: min(32, cpu_count() + 4)].
37
+ chunksize : [default: 1].
38
+ lock_name : [default: "":str].
39
+ """
40
+ kwargs = tqdm_kwargs.copy()
41
+ if "total" not in kwargs:
42
+ kwargs["total"] = length_hint(iterables[0])
43
+ tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
44
+ max_workers = kwargs.pop("max_workers", min(32, cpu_count() + 4))
45
+ chunksize = kwargs.pop("chunksize", 1)
46
+ lock_name = kwargs.pop("lock_name", "")
47
+ with ensure_lock(tqdm_class, lock_name=lock_name) as lk:
48
+ # share lock in case workers are already using `tqdm`
49
+ with PoolExecutor(max_workers=max_workers, initializer=tqdm_class.set_lock,
50
+ initargs=(lk,)) as ex:
51
+ return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs))
52
+
53
+
54
+ def thread_map(fn, *iterables, **tqdm_kwargs):
55
+ """
56
+ Equivalent of `list(map(fn, *iterables))`
57
+ driven by `concurrent.futures.ThreadPoolExecutor`.
58
+
59
+ Parameters
60
+ ----------
61
+ tqdm_class : optional
62
+ `tqdm` class to use for bars [default: tqdm.auto.tqdm].
63
+ max_workers : int, optional
64
+ Maximum number of workers to spawn; passed to
65
+ `concurrent.futures.ThreadPoolExecutor.__init__`.
66
+ [default: max(32, cpu_count() + 4)].
67
+ """
68
+ from concurrent.futures import ThreadPoolExecutor
69
+ return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
70
+
71
+
72
+ def process_map(fn, *iterables, **tqdm_kwargs):
73
+ """
74
+ Equivalent of `list(map(fn, *iterables))`
75
+ driven by `concurrent.futures.ProcessPoolExecutor`.
76
+
77
+ Parameters
78
+ ----------
79
+ tqdm_class : optional
80
+ `tqdm` class to use for bars [default: tqdm.auto.tqdm].
81
+ max_workers : int, optional
82
+ Maximum number of workers to spawn; passed to
83
+ `concurrent.futures.ProcessPoolExecutor.__init__`.
84
+ [default: min(32, cpu_count() + 4)].
85
+ chunksize : int, optional
86
+ Size of chunks sent to worker processes; passed to
87
+ `concurrent.futures.ProcessPoolExecutor.map`. [default: 1].
88
+ lock_name : str, optional
89
+ Member of `tqdm_class.get_lock()` to use [default: mp_lock].
90
+ """
91
+ from concurrent.futures import ProcessPoolExecutor
92
+ if iterables and "chunksize" not in tqdm_kwargs:
93
+ # default `chunksize=1` has poor performance for large iterables
94
+ # (most time spent dispatching items to workers).
95
+ longest_iterable_len = max(map(length_hint, iterables))
96
+ if longest_iterable_len > 1000:
97
+ from warnings import warn
98
+ warn("Iterable length %d > 1000 but `chunksize` is not set."
99
+ " This may seriously degrade multiprocess performance."
100
+ " Set `chunksize=1` or more." % longest_iterable_len,
101
+ TqdmWarning, stacklevel=2)
102
+ if "lock_name" not in tqdm_kwargs:
103
+ tqdm_kwargs = tqdm_kwargs.copy()
104
+ tqdm_kwargs["lock_name"] = "mp_lock"
105
+ return _executor_map(ProcessPoolExecutor, fn, *iterables, **tqdm_kwargs)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/discord.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sends updates to a Discord bot.
3
+
4
+ Usage:
5
+ >>> from tqdm.contrib.discord import tqdm, trange
6
+ >>> for i in trange(10, token='{token}', channel_id='{channel_id}'):
7
+ ... ...
8
+
9
+ ![screenshot](https://tqdm.github.io/img/screenshot-discord.png)
10
+ """
11
+ from os import getenv
12
+ from warnings import warn
13
+
14
+ from requests import Session
15
+ from requests.utils import default_user_agent
16
+
17
+ from ..auto import tqdm as tqdm_auto
18
+ from ..std import TqdmWarning
19
+ from ..version import __version__
20
+ from .utils_worker import MonoWorker
21
+
22
+ __author__ = {"github.com/": ["casperdcl", "guigoruiz1"]}
23
+ __all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange']
24
+
25
+
26
+ class DiscordIO(MonoWorker):
27
+ """Non-blocking file-like IO using a Discord Bot."""
28
+ API = "https://discord.com/api/v10"
29
+ UA = f"tqdm (https://tqdm.github.io, {__version__}) {default_user_agent()}"
30
+
31
+ def __init__(self, token, channel_id):
32
+ """Creates a new message in the given `channel_id`."""
33
+ super().__init__()
34
+ self.token = token
35
+ self.channel_id = channel_id
36
+ self.session = Session()
37
+ self.text = self.__class__.__name__
38
+ self.message_id
39
+
40
+ @property
41
+ def message_id(self):
42
+ if hasattr(self, '_message_id'):
43
+ return self._message_id
44
+ try:
45
+ res = self.session.post(
46
+ f'{self.API}/channels/{self.channel_id}/messages',
47
+ headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA},
48
+ json={'content': f"`{self.text}`"}).json()
49
+ except Exception as e:
50
+ tqdm_auto.write(str(e))
51
+ else:
52
+ if res.get('error_code') == 429:
53
+ warn("Creation rate limit: try increasing `mininterval`.",
54
+ TqdmWarning, stacklevel=2)
55
+ else:
56
+ self._message_id = res['id']
57
+ return self._message_id
58
+
59
+ def write(self, s):
60
+ """Replaces internal `message_id`'s text with `s`."""
61
+ if not s:
62
+ s = "..."
63
+ s = s.replace('\r', '').strip()
64
+ if s == self.text:
65
+ return # avoid duplicate message Bot error
66
+ message_id = self.message_id
67
+ if message_id is None:
68
+ return
69
+ self.text = s
70
+ try:
71
+ future = self.submit(
72
+ self.session.patch,
73
+ f'{self.API}/channels/{self.channel_id}/messages/{message_id}',
74
+ headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA},
75
+ json={'content': f"`{self.text}`"})
76
+ except Exception as e:
77
+ tqdm_auto.write(str(e))
78
+ else:
79
+ return future
80
+
81
+ def delete(self):
82
+ """Deletes internal `message_id`."""
83
+ try:
84
+ future = self.submit(
85
+ self.session.delete,
86
+ f'{self.API}/channels/{self.channel_id}/messages/{self.message_id}',
87
+ headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA})
88
+ except Exception as e:
89
+ tqdm_auto.write(str(e))
90
+ else:
91
+ return future
92
+
93
+
94
+ class tqdm_discord(tqdm_auto):
95
+ """
96
+ Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot.
97
+ May take a few seconds to create (`__init__`).
98
+
99
+ - create a discord bot (not public, no requirement of OAuth2 code
100
+ grant, only send message permissions) & invite it to a channel:
101
+ <https://discordpy.readthedocs.io/en/latest/discord.html>
102
+ - copy the bot `{token}` & `{channel_id}` and paste below
103
+
104
+ >>> from tqdm.contrib.discord import tqdm, trange
105
+ >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'):
106
+ ... ...
107
+ """
108
+ def __init__(self, *args, **kwargs):
109
+ """
110
+ Parameters
111
+ ----------
112
+ token : str, required. Discord bot token
113
+ [default: ${TQDM_DISCORD_TOKEN}].
114
+ channel_id : int, required. Discord channel ID
115
+ [default: ${TQDM_DISCORD_CHANNEL_ID}].
116
+
117
+ See `tqdm.auto.tqdm.__init__` for other parameters.
118
+ """
119
+ if not kwargs.get('disable'):
120
+ kwargs = kwargs.copy()
121
+ self.dio = DiscordIO(
122
+ kwargs.pop('token', getenv('TQDM_DISCORD_TOKEN')),
123
+ kwargs.pop('channel_id', getenv('TQDM_DISCORD_CHANNEL_ID')))
124
+ super().__init__(*args, **kwargs)
125
+
126
+ def display(self, **kwargs):
127
+ super().display(**kwargs)
128
+ fmt = self.format_dict
129
+ if fmt.get('bar_format', None):
130
+ fmt['bar_format'] = fmt['bar_format'].replace(
131
+ '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
132
+ else:
133
+ fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
134
+ self.dio.write(self.format_meter(**fmt))
135
+
136
+ def clear(self, *args, **kwargs):
137
+ super().clear(*args, **kwargs)
138
+ if not self.disable:
139
+ self.dio.write("")
140
+
141
+ def close(self):
142
+ if self.disable:
143
+ return
144
+ super().close()
145
+ if not (self.leave or (self.leave is None and self.pos == 0)):
146
+ self.dio.delete()
147
+
148
+
149
+ def tdrange(*args, **kwargs):
150
+ """Shortcut for `tqdm.contrib.discord.tqdm(range(*args), **kwargs)`."""
151
+ return tqdm_discord(range(*args), **kwargs)
152
+
153
+
154
+ # Aliases
155
+ tqdm = tqdm_discord
156
+ trange = tdrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/itertools.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around `itertools`.
3
+ """
4
+ import itertools
5
+
6
+ from ..auto import tqdm as tqdm_auto
7
+
8
+ __author__ = {"github.com/": ["casperdcl"]}
9
+ __all__ = ['product']
10
+
11
+
12
+ def product(*iterables, **tqdm_kwargs):
13
+ """
14
+ Equivalent of `itertools.product`.
15
+
16
+ Parameters
17
+ ----------
18
+ tqdm_class : [default: tqdm.auto.tqdm].
19
+ """
20
+ kwargs = tqdm_kwargs.copy()
21
+ tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
22
+ try:
23
+ lens = list(map(len, iterables))
24
+ except TypeError:
25
+ total = None
26
+ else:
27
+ total = 1
28
+ for i in lens:
29
+ total *= i
30
+ kwargs.setdefault("total", total)
31
+ with tqdm_class(**kwargs) as t:
32
+ it = itertools.product(*iterables)
33
+ for i in it:
34
+ yield i
35
+ t.update()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/logging.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functionality for interoperability with stdlib `logging`.
3
+ """
4
+ import logging
5
+ import sys
6
+ from contextlib import contextmanager
7
+
8
+ try:
9
+ from typing import Iterator, List, Optional, Type # noqa: F401
10
+ except ImportError:
11
+ pass
12
+
13
+ from ..std import tqdm as std_tqdm
14
+
15
+
16
+ class _TqdmLoggingHandler(logging.StreamHandler):
17
+ def __init__(
18
+ self,
19
+ tqdm_class=std_tqdm # type: Type[std_tqdm]
20
+ ):
21
+ super().__init__()
22
+ self.tqdm_class = tqdm_class
23
+
24
+ def emit(self, record):
25
+ try:
26
+ msg = self.format(record)
27
+ self.tqdm_class.write(msg, file=self.stream)
28
+ self.flush()
29
+ except (KeyboardInterrupt, SystemExit):
30
+ raise
31
+ except: # noqa pylint: disable=bare-except
32
+ self.handleError(record)
33
+
34
+
35
+ def _is_console_logging_handler(handler):
36
+ return (isinstance(handler, logging.StreamHandler)
37
+ and handler.stream in {sys.stdout, sys.stderr})
38
+
39
+
40
+ def _get_first_found_console_logging_handler(handlers):
41
+ for handler in handlers:
42
+ if _is_console_logging_handler(handler):
43
+ return handler
44
+
45
+
46
+ @contextmanager
47
+ def logging_redirect_tqdm(
48
+ loggers=None, # type: Optional[List[logging.Logger]],
49
+ tqdm_class=std_tqdm # type: Type[std_tqdm]
50
+ ):
51
+ # type: (...) -> Iterator[None]
52
+ """
53
+ Context manager redirecting console logging to `tqdm.write()`, leaving
54
+ other logging handlers (e.g. log files) unaffected.
55
+
56
+ Parameters
57
+ ----------
58
+ loggers : list, optional
59
+ Which handlers to redirect (default: [logging.root]).
60
+ tqdm_class : optional
61
+
62
+ Example
63
+ -------
64
+ ```python
65
+ import logging
66
+ from tqdm import trange
67
+ from tqdm.contrib.logging import logging_redirect_tqdm
68
+
69
+ LOG = logging.getLogger(__name__)
70
+
71
+ if __name__ == '__main__':
72
+ logging.basicConfig(level=logging.INFO)
73
+ with logging_redirect_tqdm():
74
+ for i in trange(9):
75
+ if i == 4:
76
+ LOG.info("console logging redirected to `tqdm.write()`")
77
+ # logging restored
78
+ ```
79
+ """
80
+ if loggers is None:
81
+ loggers = [logging.root]
82
+ original_handlers_list = [logger.handlers for logger in loggers]
83
+ try:
84
+ for logger in loggers:
85
+ tqdm_handler = _TqdmLoggingHandler(tqdm_class)
86
+ orig_handler = _get_first_found_console_logging_handler(logger.handlers)
87
+ if orig_handler is not None:
88
+ tqdm_handler.setFormatter(orig_handler.formatter)
89
+ tqdm_handler.stream = orig_handler.stream
90
+ logger.handlers = [
91
+ handler for handler in logger.handlers
92
+ if not _is_console_logging_handler(handler)] + [tqdm_handler]
93
+ yield
94
+ finally:
95
+ for logger, original_handlers in zip(loggers, original_handlers_list):
96
+ logger.handlers = original_handlers
97
+
98
+
99
+ @contextmanager
100
+ def tqdm_logging_redirect(
101
+ *args,
102
+ # loggers=None, # type: Optional[List[logging.Logger]]
103
+ # tqdm=None, # type: Optional[Type[tqdm.tqdm]]
104
+ **kwargs
105
+ ):
106
+ # type: (...) -> Iterator[None]
107
+ """
108
+ Convenience shortcut for:
109
+ ```python
110
+ with tqdm_class(*args, **tqdm_kwargs) as pbar:
111
+ with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class):
112
+ yield pbar
113
+ ```
114
+
115
+ Parameters
116
+ ----------
117
+ tqdm_class : optional, (default: tqdm.std.tqdm).
118
+ loggers : optional, list.
119
+ **tqdm_kwargs : passed to `tqdm_class`.
120
+ """
121
+ tqdm_kwargs = kwargs.copy()
122
+ loggers = tqdm_kwargs.pop('loggers', None)
123
+ tqdm_class = tqdm_kwargs.pop('tqdm_class', std_tqdm)
124
+ with tqdm_class(*args, **tqdm_kwargs) as pbar:
125
+ with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class):
126
+ yield pbar
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/slack.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sends updates to a Slack app.
3
+
4
+ Usage:
5
+ >>> from tqdm.contrib.slack import tqdm, trange
6
+ >>> for i in trange(10, token='{token}', channel='{channel}'):
7
+ ... ...
8
+
9
+ ![screenshot](https://tqdm.github.io/img/screenshot-slack.png)
10
+ """
11
+ import logging
12
+ from os import getenv
13
+
14
+ try:
15
+ from slack_sdk import WebClient
16
+ except ImportError:
17
+ raise ImportError("Please `pip install slack-sdk`")
18
+
19
+ from ..auto import tqdm as tqdm_auto
20
+ from .utils_worker import MonoWorker
21
+
22
+ __author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]}
23
+ __all__ = ['SlackIO', 'tqdm_slack', 'tsrange', 'tqdm', 'trange']
24
+
25
+
26
+ class SlackIO(MonoWorker):
27
+ """Non-blocking file-like IO using a Slack app."""
28
+ def __init__(self, token, channel):
29
+ """Creates a new message in the given `channel`."""
30
+ super().__init__()
31
+ self.client = WebClient(token=token)
32
+ self.text = self.__class__.__name__
33
+ try:
34
+ self.message = self.client.chat_postMessage(channel=channel, text=self.text)
35
+ except Exception as e:
36
+ tqdm_auto.write(str(e))
37
+ self.message = None
38
+
39
+ def write(self, s):
40
+ """Replaces internal `message`'s text with `s`."""
41
+ if not s:
42
+ s = "..."
43
+ s = s.replace('\r', '').strip()
44
+ if s == self.text:
45
+ return # skip duplicate message
46
+ message = self.message
47
+ if message is None:
48
+ return
49
+ self.text = s
50
+ try:
51
+ future = self.submit(self.client.chat_update, channel=message['channel'],
52
+ ts=message['ts'], text='`' + s + '`')
53
+ except Exception as e:
54
+ tqdm_auto.write(str(e))
55
+ else:
56
+ return future
57
+
58
+
59
+ class tqdm_slack(tqdm_auto):
60
+ """
61
+ Standard `tqdm.auto.tqdm` but also sends updates to a Slack app.
62
+ May take a few seconds to create (`__init__`).
63
+
64
+ - create a Slack app with the `chat:write` scope & invite it to a
65
+ channel: <https://api.slack.com/authentication/basics>
66
+ - copy the bot `{token}` & `{channel}` and paste below
67
+ >>> from tqdm.contrib.slack import tqdm, trange
68
+ >>> for i in tqdm(iterable, token='{token}', channel='{channel}'):
69
+ ... ...
70
+ """
71
+ def __init__(self, *args, **kwargs):
72
+ """
73
+ Parameters
74
+ ----------
75
+ token : str, required. Slack token
76
+ [default: ${TQDM_SLACK_TOKEN}].
77
+ channel : int, required. Slack channel
78
+ [default: ${TQDM_SLACK_CHANNEL}].
79
+ mininterval : float, optional.
80
+ Minimum of [default: 1.5] to avoid rate limit.
81
+
82
+ See `tqdm.auto.tqdm.__init__` for other parameters.
83
+ """
84
+ if not kwargs.get('disable'):
85
+ kwargs = kwargs.copy()
86
+ logging.getLogger("HTTPClient").setLevel(logging.WARNING)
87
+ self.sio = SlackIO(
88
+ kwargs.pop('token', getenv("TQDM_SLACK_TOKEN")),
89
+ kwargs.pop('channel', getenv("TQDM_SLACK_CHANNEL")))
90
+ kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5))
91
+ super().__init__(*args, **kwargs)
92
+
93
+ def display(self, **kwargs):
94
+ super().display(**kwargs)
95
+ fmt = self.format_dict
96
+ if fmt.get('bar_format', None):
97
+ fmt['bar_format'] = fmt['bar_format'].replace(
98
+ '<bar/>', '`{bar:10}`').replace('{bar}', '`{bar:10u}`')
99
+ else:
100
+ fmt['bar_format'] = '{l_bar}`{bar:10}`{r_bar}'
101
+ if fmt['ascii'] is False:
102
+ fmt['ascii'] = [":black_square:", ":small_blue_diamond:", ":large_blue_diamond:",
103
+ ":large_blue_square:"]
104
+ fmt['ncols'] = 336
105
+ self.sio.write(self.format_meter(**fmt))
106
+
107
+ def clear(self, *args, **kwargs):
108
+ super().clear(*args, **kwargs)
109
+ if not self.disable:
110
+ self.sio.write("")
111
+
112
+
113
+ def tsrange(*args, **kwargs):
114
+ """Shortcut for `tqdm.contrib.slack.tqdm(range(*args), **kwargs)`."""
115
+ return tqdm_slack(range(*args), **kwargs)
116
+
117
+
118
+ # Aliases
119
+ tqdm = tqdm_slack
120
+ trange = tsrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/telegram.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sends updates to a Telegram bot.
3
+
4
+ Usage:
5
+ >>> from tqdm.contrib.telegram import tqdm, trange
6
+ >>> for i in trange(10, token='{token}', chat_id='{chat_id}'):
7
+ ... ...
8
+
9
+ ![screenshot](https://tqdm.github.io/img/screenshot-telegram.gif)
10
+ """
11
+ from os import getenv
12
+ from warnings import warn
13
+
14
+ from requests import Session
15
+
16
+ from ..auto import tqdm as tqdm_auto
17
+ from ..std import TqdmWarning
18
+ from .utils_worker import MonoWorker
19
+
20
+ __author__ = {"github.com/": ["casperdcl"]}
21
+ __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
22
+
23
+
24
+ class TelegramIO(MonoWorker):
25
+ """Non-blocking file-like IO using a Telegram Bot."""
26
+ API = 'https://api.telegram.org/bot'
27
+
28
+ def __init__(self, token, chat_id):
29
+ """Creates a new message in the given `chat_id`."""
30
+ super().__init__()
31
+ self.token = token
32
+ self.chat_id = chat_id
33
+ self.session = Session()
34
+ self.text = self.__class__.__name__
35
+ self.message_id
36
+
37
+ @property
38
+ def message_id(self):
39
+ if hasattr(self, '_message_id'):
40
+ return self._message_id
41
+ try:
42
+ res = self.session.post(
43
+ self.API + '%s/sendMessage' % self.token,
44
+ data={'text': '`' + self.text + '`', 'chat_id': self.chat_id,
45
+ 'parse_mode': 'MarkdownV2'}).json()
46
+ except Exception as e:
47
+ tqdm_auto.write(str(e))
48
+ else:
49
+ if res.get('error_code') == 429:
50
+ warn("Creation rate limit: try increasing `mininterval`.",
51
+ TqdmWarning, stacklevel=2)
52
+ else:
53
+ self._message_id = res['result']['message_id']
54
+ return self._message_id
55
+
56
+ def write(self, s):
57
+ """Replaces internal `message_id`'s text with `s`."""
58
+ if not s:
59
+ s = "..."
60
+ s = s.replace('\r', '').strip()
61
+ if s == self.text:
62
+ return # avoid duplicate message Bot error
63
+ message_id = self.message_id
64
+ if message_id is None:
65
+ return
66
+ self.text = s
67
+ try:
68
+ future = self.submit(
69
+ self.session.post, self.API + '%s/editMessageText' % self.token,
70
+ data={'text': '`' + s + '`', 'chat_id': self.chat_id,
71
+ 'message_id': message_id, 'parse_mode': 'MarkdownV2'})
72
+ except Exception as e:
73
+ tqdm_auto.write(str(e))
74
+ else:
75
+ return future
76
+
77
+ def delete(self):
78
+ """Deletes internal `message_id`."""
79
+ try:
80
+ future = self.submit(
81
+ self.session.post, self.API + '%s/deleteMessage' % self.token,
82
+ data={'chat_id': self.chat_id, 'message_id': self.message_id})
83
+ except Exception as e:
84
+ tqdm_auto.write(str(e))
85
+ else:
86
+ return future
87
+
88
+
89
+ class tqdm_telegram(tqdm_auto):
90
+ """
91
+ Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot.
92
+ May take a few seconds to create (`__init__`).
93
+
94
+ - create a bot <https://core.telegram.org/bots#6-botfather>
95
+ - copy its `{token}`
96
+ - add the bot to a chat and send it a message such as `/start`
97
+ - go to <https://api.telegram.org/bot`{token}`/getUpdates> to find out
98
+ the `{chat_id}`
99
+ - paste the `{token}` & `{chat_id}` below
100
+
101
+ >>> from tqdm.contrib.telegram import tqdm, trange
102
+ >>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'):
103
+ ... ...
104
+ """
105
+ def __init__(self, *args, **kwargs):
106
+ """
107
+ Parameters
108
+ ----------
109
+ token : str, required. Telegram token
110
+ [default: ${TQDM_TELEGRAM_TOKEN}].
111
+ chat_id : str, required. Telegram chat ID
112
+ [default: ${TQDM_TELEGRAM_CHAT_ID}].
113
+
114
+ See `tqdm.auto.tqdm.__init__` for other parameters.
115
+ """
116
+ if not kwargs.get('disable'):
117
+ kwargs = kwargs.copy()
118
+ self.tgio = TelegramIO(
119
+ kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
120
+ kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
121
+ super().__init__(*args, **kwargs)
122
+
123
+ def display(self, **kwargs):
124
+ super().display(**kwargs)
125
+ fmt = self.format_dict
126
+ if fmt.get('bar_format', None):
127
+ fmt['bar_format'] = fmt['bar_format'].replace(
128
+ '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
129
+ else:
130
+ fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
131
+ self.tgio.write(self.format_meter(**fmt))
132
+
133
+ def clear(self, *args, **kwargs):
134
+ super().clear(*args, **kwargs)
135
+ if not self.disable:
136
+ self.tgio.write("")
137
+
138
+ def close(self):
139
+ if self.disable:
140
+ return
141
+ super().close()
142
+ if not (self.leave or (self.leave is None and self.pos == 0)):
143
+ self.tgio.delete()
144
+
145
+
146
+ def ttgrange(*args, **kwargs):
147
+ """Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`."""
148
+ return tqdm_telegram(range(*args), **kwargs)
149
+
150
+
151
+ # Aliases
152
+ tqdm = tqdm_telegram
153
+ trange = ttgrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/contrib/utils_worker.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ IO/concurrency helpers for `tqdm.contrib`.
3
+ """
4
+ from collections import deque
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+ from ..auto import tqdm as tqdm_auto
8
+
9
+ __author__ = {"github.com/": ["casperdcl"]}
10
+ __all__ = ['MonoWorker']
11
+
12
+
13
+ class MonoWorker(object):
14
+ """
15
+ Supports one running task and one waiting task.
16
+ The waiting task is the most recent submitted (others are discarded).
17
+ """
18
+ def __init__(self):
19
+ self.pool = ThreadPoolExecutor(max_workers=1)
20
+ self.futures = deque([], 2)
21
+
22
+ def submit(self, func, *args, **kwargs):
23
+ """`func(*args, **kwargs)` may replace currently waiting task."""
24
+ futures = self.futures
25
+ if len(futures) == futures.maxlen:
26
+ running = futures.popleft()
27
+ if not running.done():
28
+ if len(futures): # clear waiting
29
+ waiting = futures.pop()
30
+ waiting.cancel()
31
+ futures.appendleft(running) # re-insert running
32
+ try:
33
+ waiting = self.pool.submit(func, *args, **kwargs)
34
+ except Exception as e:
35
+ tqdm_auto.write(str(e))
36
+ else:
37
+ futures.append(waiting)
38
+ return waiting
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/dask.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ from dask.callbacks import Callback
4
+
5
+ from .auto import tqdm as tqdm_auto
6
+
7
+ __author__ = {"github.com/": ["casperdcl"]}
8
+ __all__ = ['TqdmCallback']
9
+
10
+
11
+ class TqdmCallback(Callback):
12
+ """Dask callback for task progress."""
13
+ def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
14
+ **tqdm_kwargs):
15
+ """
16
+ Parameters
17
+ ----------
18
+ tqdm_class : optional
19
+ `tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
20
+ tqdm_kwargs : optional
21
+ Any other arguments used for all bars.
22
+ """
23
+ super().__init__(start=start, pretask=pretask)
24
+ if tqdm_kwargs:
25
+ tqdm_class = partial(tqdm_class, **tqdm_kwargs)
26
+ self.tqdm_class = tqdm_class
27
+
28
+ def _start_state(self, _, state):
29
+ self.pbar = self.tqdm_class(total=sum(
30
+ len(state[k]) for k in ['ready', 'waiting', 'running', 'finished']))
31
+
32
+ def _posttask(self, *_, **__):
33
+ self.pbar.update()
34
+
35
+ def _finish(self, *_, **__):
36
+ self.pbar.close()
37
+
38
+ def display(self):
39
+ """Displays in the current cell in Notebooks."""
40
+ container = getattr(self.bar, 'container', None)
41
+ if container is None:
42
+ return
43
+ from .notebook import display
44
+ display(container)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/gui.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Matplotlib GUI progressbar decorator for iterators.
3
+
4
+ Usage:
5
+ >>> from tqdm.gui import trange, tqdm
6
+ >>> for i in trange(10):
7
+ ... ...
8
+ """
9
+ # future division is important to divide integers and get as
10
+ # a result precise floating numbers (instead of truncated int)
11
+ import re
12
+ from warnings import warn
13
+
14
+ # to inherit from the tqdm class
15
+ from .std import TqdmExperimentalWarning
16
+ from .std import tqdm as std_tqdm
17
+
18
+ # import compatibility functions and utilities
19
+
20
+ __author__ = {"github.com/": ["casperdcl", "lrq3000"]}
21
+ __all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
22
+
23
+
24
+ class tqdm_gui(std_tqdm): # pragma: no cover
25
+ """Experimental Matplotlib GUI version of tqdm!"""
26
+ # TODO: @classmethod: write() on GUI?
27
+ def __init__(self, *args, **kwargs):
28
+ from collections import deque
29
+
30
+ import matplotlib as mpl
31
+ import matplotlib.pyplot as plt
32
+ kwargs = kwargs.copy()
33
+ kwargs['gui'] = True
34
+ colour = kwargs.pop('colour', 'g')
35
+ super().__init__(*args, **kwargs)
36
+
37
+ if self.disable:
38
+ return
39
+
40
+ warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
41
+ self.mpl = mpl
42
+ self.plt = plt
43
+
44
+ # Remember if external environment uses toolbars
45
+ self.toolbar = self.mpl.rcParams['toolbar']
46
+ self.mpl.rcParams['toolbar'] = 'None'
47
+
48
+ self.mininterval = max(self.mininterval, 0.5)
49
+ self.fig, ax = plt.subplots(figsize=(9, 2.2))
50
+ # self.fig.subplots_adjust(bottom=0.2)
51
+ total = self.__len__() # avoids TypeError on None #971
52
+ if total is not None:
53
+ self.xdata = []
54
+ self.ydata = []
55
+ self.zdata = []
56
+ else:
57
+ self.xdata = deque([])
58
+ self.ydata = deque([])
59
+ self.zdata = deque([])
60
+ self.line1, = ax.plot(self.xdata, self.ydata, color='b')
61
+ self.line2, = ax.plot(self.xdata, self.zdata, color='k')
62
+ ax.set_ylim(0, 0.001)
63
+ if total is not None:
64
+ ax.set_xlim(0, 100)
65
+ ax.set_xlabel("percent")
66
+ self.fig.legend((self.line1, self.line2), ("cur", "est"),
67
+ loc='center right')
68
+ # progressbar
69
+ self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
70
+ else:
71
+ # ax.set_xlim(-60, 0)
72
+ ax.set_xlim(0, 60)
73
+ ax.invert_xaxis()
74
+ ax.set_xlabel("seconds")
75
+ ax.legend(("cur", "est"), loc='lower left')
76
+ ax.grid()
77
+ # ax.set_xlabel('seconds')
78
+ ax.set_ylabel((self.unit if self.unit else "it") + "/s")
79
+ if self.unit_scale:
80
+ plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
81
+ ax.yaxis.get_offset_text().set_x(-0.15)
82
+
83
+ # Remember if external environment is interactive
84
+ self.wasion = plt.isinteractive()
85
+ plt.ion()
86
+ self.ax = ax
87
+
88
+ def close(self):
89
+ if self.disable:
90
+ return
91
+
92
+ self.disable = True
93
+
94
+ with self.get_lock():
95
+ self._instances.remove(self)
96
+
97
+ # Restore toolbars
98
+ self.mpl.rcParams['toolbar'] = self.toolbar
99
+ # Return to non-interactive mode
100
+ if not self.wasion:
101
+ self.plt.ioff()
102
+ if self.leave:
103
+ self.display()
104
+ else:
105
+ self.plt.close(self.fig)
106
+
107
+ def clear(self, *_, **__):
108
+ pass
109
+
110
+ def display(self, *_, **__):
111
+ n = self.n
112
+ cur_t = self._time()
113
+ elapsed = cur_t - self.start_t
114
+ delta_it = n - self.last_print_n
115
+ delta_t = cur_t - self.last_print_t
116
+
117
+ # Inline due to multiple calls
118
+ total = self.total
119
+ xdata = self.xdata
120
+ ydata = self.ydata
121
+ zdata = self.zdata
122
+ ax = self.ax
123
+ line1 = self.line1
124
+ line2 = self.line2
125
+ hspan = getattr(self, 'hspan', None)
126
+ # instantaneous rate
127
+ y = delta_it / delta_t
128
+ # overall rate
129
+ z = n / elapsed
130
+ # update line data
131
+ xdata.append(n * 100.0 / total if total else cur_t)
132
+ ydata.append(y)
133
+ zdata.append(z)
134
+
135
+ # Discard old values
136
+ # xmin, xmax = ax.get_xlim()
137
+ # if (not total) and elapsed > xmin * 1.1:
138
+ if (not total) and elapsed > 66:
139
+ xdata.popleft()
140
+ ydata.popleft()
141
+ zdata.popleft()
142
+
143
+ ymin, ymax = ax.get_ylim()
144
+ if y > ymax or z > ymax:
145
+ ymax = 1.1 * y
146
+ ax.set_ylim(ymin, ymax)
147
+ ax.figure.canvas.draw()
148
+
149
+ if total:
150
+ line1.set_data(xdata, ydata)
151
+ line2.set_data(xdata, zdata)
152
+ if hspan:
153
+ hspan.set_xy((0, ymin))
154
+ hspan.set_height(ymax - ymin)
155
+ hspan.set_width(n / total)
156
+ else:
157
+ t_ago = [cur_t - i for i in xdata]
158
+ line1.set_data(t_ago, ydata)
159
+ line2.set_data(t_ago, zdata)
160
+
161
+ d = self.format_dict
162
+ # remove {bar}
163
+ d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
164
+ "{bar}", "<bar/>")
165
+ msg = self.format_meter(**d)
166
+ if '<bar/>' in msg:
167
+ msg = "".join(re.split(r'\|?<bar/>\|?', msg, maxsplit=1))
168
+ ax.set_title(msg, fontname="DejaVu Sans Mono", fontsize=11)
169
+ self.plt.pause(1e-9)
170
+
171
+
172
+ def tgrange(*args, **kwargs):
173
+ """Shortcut for `tqdm.gui.tqdm(range(*args), **kwargs)`."""
174
+ return tqdm_gui(range(*args), **kwargs)
175
+
176
+
177
+ # Aliases
178
+ tqdm = tqdm_gui
179
+ trange = tgrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/keras.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import copy
2
+ from functools import partial
3
+
4
+ from .auto import tqdm as tqdm_auto
5
+
6
+ try:
7
+ import keras
8
+ except (ImportError, AttributeError) as e:
9
+ try:
10
+ from tensorflow import keras
11
+ except ImportError:
12
+ raise e
13
+ __author__ = {"github.com/": ["casperdcl"]}
14
+ __all__ = ['TqdmCallback']
15
+
16
+
17
+ class TqdmCallback(keras.callbacks.Callback):
18
+ """Keras callback for epoch and batch progress."""
19
+ @staticmethod
20
+ def bar2callback(bar, pop=None, delta=(lambda logs: 1)):
21
+ def callback(_, logs=None):
22
+ n = delta(logs)
23
+ if logs:
24
+ if pop:
25
+ logs = copy(logs)
26
+ [logs.pop(i, 0) for i in pop]
27
+ bar.set_postfix(logs, refresh=False)
28
+ bar.update(n)
29
+
30
+ return callback
31
+
32
+ def __init__(self, epochs=None, data_size=None, batch_size=None, verbose=1,
33
+ tqdm_class=tqdm_auto, **tqdm_kwargs):
34
+ """
35
+ Parameters
36
+ ----------
37
+ epochs : int, optional
38
+ data_size : int, optional
39
+ Number of training pairs.
40
+ batch_size : int, optional
41
+ Number of training pairs per batch.
42
+ verbose : int
43
+ 0: epoch, 1: batch (transient), 2: batch. [default: 1].
44
+ Will be set to `0` unless both `data_size` and `batch_size`
45
+ are given.
46
+ tqdm_class : optional
47
+ `tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
48
+ tqdm_kwargs : optional
49
+ Any other arguments used for all bars.
50
+ """
51
+ if tqdm_kwargs:
52
+ tqdm_class = partial(tqdm_class, **tqdm_kwargs)
53
+ self.tqdm_class = tqdm_class
54
+ self.epoch_bar = tqdm_class(total=epochs, unit='epoch')
55
+ self.on_epoch_end = self.bar2callback(self.epoch_bar)
56
+ if data_size and batch_size:
57
+ self.batches = batches = (data_size + batch_size - 1) // batch_size
58
+ else:
59
+ self.batches = batches = None
60
+ self.verbose = verbose
61
+ if verbose == 1:
62
+ self.batch_bar = tqdm_class(total=batches, unit='batch', leave=False)
63
+ self.on_batch_end = self.bar2callback(
64
+ self.batch_bar, pop=['batch', 'size'],
65
+ delta=lambda logs: logs.get('size', 1))
66
+
67
+ def on_train_begin(self, *_, **__):
68
+ params = self.params.get
69
+ auto_total = params('epochs', params('nb_epoch', None))
70
+ if auto_total is not None and auto_total != self.epoch_bar.total:
71
+ self.epoch_bar.reset(total=auto_total)
72
+
73
+ def on_epoch_begin(self, epoch, *_, **__):
74
+ if self.epoch_bar.n < epoch:
75
+ ebar = self.epoch_bar
76
+ ebar.n = ebar.last_print_n = ebar.initial = epoch
77
+ if self.verbose:
78
+ params = self.params.get
79
+ total = params('samples', params(
80
+ 'nb_sample', params('steps', None))) or self.batches
81
+ if self.verbose == 2:
82
+ if hasattr(self, 'batch_bar'):
83
+ self.batch_bar.close()
84
+ self.batch_bar = self.tqdm_class(
85
+ total=total, unit='batch', leave=True,
86
+ unit_scale=1 / (params('batch_size', 1) or 1))
87
+ self.on_batch_end = self.bar2callback(
88
+ self.batch_bar, pop=['batch', 'size'],
89
+ delta=lambda logs: logs.get('size', 1))
90
+ elif self.verbose == 1:
91
+ self.batch_bar.unit_scale = 1 / (params('batch_size', 1) or 1)
92
+ self.batch_bar.reset(total=total)
93
+ else:
94
+ raise KeyError('Unknown verbosity')
95
+
96
+ def on_train_end(self, *_, **__):
97
+ if hasattr(self, 'batch_bar'):
98
+ self.batch_bar.close()
99
+ self.epoch_bar.close()
100
+
101
+ def display(self):
102
+ """Displays in the current cell in Notebooks."""
103
+ container = getattr(self.epoch_bar, 'container', None)
104
+ if container is None:
105
+ return
106
+ from .notebook import display
107
+ display(container)
108
+ batch_bar = getattr(self, 'batch_bar', None)
109
+ if batch_bar is not None:
110
+ display(batch_bar.container)
111
+
112
+ @staticmethod
113
+ def _implements_train_batch_hooks():
114
+ return True
115
+
116
+ @staticmethod
117
+ def _implements_test_batch_hooks():
118
+ return True
119
+
120
+ @staticmethod
121
+ def _implements_predict_batch_hooks():
122
+ return True
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/notebook.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ IPython/Jupyter Notebook progressbar decorator for iterators.
3
+ Includes a default `range` iterator printing to `stderr`.
4
+
5
+ Usage:
6
+ >>> from tqdm.notebook import trange, tqdm
7
+ >>> for i in trange(10):
8
+ ... ...
9
+ """
10
+ # import compatibility functions and utilities
11
+ import re
12
+ import sys
13
+ from html import escape
14
+ from weakref import proxy
15
+
16
+ # to inherit from the tqdm class
17
+ from .std import tqdm as std_tqdm
18
+
19
+ if True: # pragma: no cover
20
+ # import IPython/Jupyter base widget and display utilities
21
+ IPY = 0
22
+ try: # IPython 4.x
23
+ import ipywidgets
24
+ IPY = 4
25
+ except ImportError: # IPython 3.x / 2.x
26
+ IPY = 32
27
+ import warnings
28
+ with warnings.catch_warnings():
29
+ warnings.filterwarnings(
30
+ 'ignore', message=".*The `IPython.html` package has been deprecated.*")
31
+ try:
32
+ import IPython.html.widgets as ipywidgets # NOQA: F401
33
+ except ImportError:
34
+ pass
35
+
36
+ try: # IPython 4.x / 3.x
37
+ if IPY == 32:
38
+ from IPython.html.widgets import HTML
39
+ from IPython.html.widgets import FloatProgress as IProgress
40
+ from IPython.html.widgets import HBox
41
+ IPY = 3
42
+ else:
43
+ from ipywidgets import HTML
44
+ from ipywidgets import FloatProgress as IProgress
45
+ from ipywidgets import HBox
46
+ except ImportError:
47
+ try: # IPython 2.x
48
+ from IPython.html.widgets import HTML
49
+ from IPython.html.widgets import ContainerWidget as HBox
50
+ from IPython.html.widgets import FloatProgressWidget as IProgress
51
+ IPY = 2
52
+ except ImportError:
53
+ IPY = 0
54
+ IProgress = None
55
+ HBox = object
56
+
57
+ try:
58
+ from IPython.display import display # , clear_output
59
+ except ImportError:
60
+ pass
61
+
62
+ __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
63
+ __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
64
+ WARN_NOIPYW = ("IProgress not found. Please update jupyter and ipywidgets."
65
+ " See https://ipywidgets.readthedocs.io/en/stable"
66
+ "/user_install.html")
67
+
68
+
69
+ class TqdmHBox(HBox):
70
+ """`ipywidgets.HBox` with a pretty representation"""
71
+ def _json_(self, pretty=None):
72
+ pbar = getattr(self, 'pbar', None)
73
+ if pbar is None:
74
+ return {}
75
+ d = pbar.format_dict
76
+ if pretty is not None:
77
+ d["ascii"] = not pretty
78
+ return d
79
+
80
+ def __repr__(self, pretty=False):
81
+ pbar = getattr(self, 'pbar', None)
82
+ if pbar is None:
83
+ return super().__repr__()
84
+ return pbar.format_meter(**self._json_(pretty))
85
+
86
+ def _repr_pretty_(self, pp, *_, **__):
87
+ pp.text(self.__repr__(True))
88
+
89
+
90
+ class tqdm_notebook(std_tqdm):
91
+ """
92
+ Experimental IPython/Jupyter Notebook widget using tqdm!
93
+ """
94
+ @staticmethod
95
+ def status_printer(_, total=None, desc=None, ncols=None):
96
+ """
97
+ Manage the printing of an IPython/Jupyter Notebook progress bar widget.
98
+ """
99
+ # Fallback to text bar if there's no total
100
+ # DEPRECATED: replaced with an 'info' style bar
101
+ # if not total:
102
+ # return super(tqdm_notebook, tqdm_notebook).status_printer(file)
103
+
104
+ # fp = file
105
+
106
+ # Prepare IPython progress bar
107
+ if IProgress is None: # #187 #451 #558 #872
108
+ raise ImportError(WARN_NOIPYW)
109
+ if total:
110
+ pbar = IProgress(min=0, max=total)
111
+ else: # No total? Show info style bar with no progress tqdm status
112
+ pbar = IProgress(min=0, max=1)
113
+ pbar.value = 1
114
+ pbar.bar_style = 'info'
115
+ if ncols is None:
116
+ pbar.layout.width = "20px"
117
+
118
+ ltext = HTML()
119
+ rtext = HTML()
120
+ if desc:
121
+ ltext.value = desc
122
+ container = TqdmHBox(children=[ltext, pbar, rtext])
123
+ # Prepare layout
124
+ if ncols is not None: # use default style of ipywidgets
125
+ # ncols could be 100, "100px", "100%"
126
+ ncols = str(ncols) # ipywidgets only accepts string
127
+ try:
128
+ if int(ncols) > 0: # isnumeric and positive
129
+ ncols += 'px'
130
+ except ValueError:
131
+ pass
132
+ pbar.layout.flex = '2'
133
+ container.layout.width = ncols
134
+ container.layout.display = 'inline-flex'
135
+ container.layout.flex_flow = 'row wrap'
136
+
137
+ return container
138
+
139
+ def display(self, msg=None, pos=None,
140
+ # additional signals
141
+ close=False, bar_style=None, check_delay=True):
142
+ # Note: contrary to native tqdm, msg='' does NOT clear bar
143
+ # goal is to keep all infos if error happens so user knows
144
+ # at which iteration the loop failed.
145
+
146
+ # Clear previous output (really necessary?)
147
+ # clear_output(wait=1)
148
+
149
+ if not msg and not close:
150
+ d = self.format_dict
151
+ # remove {bar}
152
+ d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
153
+ "{bar}", "<bar/>")
154
+ msg = self.format_meter(**d)
155
+
156
+ ltext, pbar, rtext = self.container.children
157
+ pbar.value = self.n
158
+
159
+ if msg:
160
+ msg = msg.replace(' ', u'\u2007') # fix html space padding
161
+ # html escape special characters (like '&')
162
+ if '<bar/>' in msg:
163
+ left, right = map(escape, re.split(r'\|?<bar/>\|?', msg, maxsplit=1))
164
+ else:
165
+ left, right = '', escape(msg)
166
+
167
+ # Update description
168
+ ltext.value = left
169
+ # never clear the bar (signal: msg='')
170
+ if right:
171
+ rtext.value = right
172
+
173
+ # Change bar style
174
+ if bar_style:
175
+ # Hack-ish way to avoid the danger bar_style being overridden by
176
+ # success because the bar gets closed after the error...
177
+ if pbar.bar_style != 'danger' or bar_style != 'success':
178
+ pbar.bar_style = bar_style
179
+
180
+ # Special signal to close the bar
181
+ if close and pbar.bar_style != 'danger': # hide only if no error
182
+ try:
183
+ self.container.close()
184
+ except AttributeError:
185
+ self.container.visible = False
186
+ self.container.layout.visibility = 'hidden' # IPYW>=8
187
+
188
+ if check_delay and self.delay > 0 and not self.displayed:
189
+ display(self.container)
190
+ self.displayed = True
191
+
192
+ @property
193
+ def colour(self):
194
+ if hasattr(self, 'container'):
195
+ return self.container.children[-2].style.bar_color
196
+
197
+ @colour.setter
198
+ def colour(self, bar_color):
199
+ if hasattr(self, 'container'):
200
+ self.container.children[-2].style.bar_color = bar_color
201
+
202
+ def __init__(self, *args, **kwargs):
203
+ """
204
+ Supports the usual `tqdm.tqdm` parameters as well as those listed below.
205
+
206
+ Parameters
207
+ ----------
208
+ display : Whether to call `display(self.container)` immediately
209
+ [default: True].
210
+ """
211
+ kwargs = kwargs.copy()
212
+ # Setup default output
213
+ file_kwarg = kwargs.get('file', sys.stderr)
214
+ if file_kwarg is sys.stderr or file_kwarg is None:
215
+ kwargs['file'] = sys.stdout # avoid the red block in IPython
216
+
217
+ # Initialize parent class + avoid printing by using gui=True
218
+ kwargs['gui'] = True
219
+ # convert disable = None to False
220
+ kwargs['disable'] = bool(kwargs.get('disable', False))
221
+ colour = kwargs.pop('colour', None)
222
+ display_here = kwargs.pop('display', True)
223
+ super().__init__(*args, **kwargs)
224
+ if self.disable or not kwargs['gui']:
225
+ self.disp = lambda *_, **__: None
226
+ return
227
+
228
+ # Get bar width
229
+ self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
230
+
231
+ # Replace with IPython progress bar display (with correct total)
232
+ unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
233
+ total = self.total * unit_scale if self.total else self.total
234
+ self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
235
+ self.container.pbar = proxy(self)
236
+ self.displayed = False
237
+ if display_here and self.delay <= 0:
238
+ display(self.container)
239
+ self.displayed = True
240
+ self.disp = self.display
241
+ self.colour = colour
242
+
243
+ # Print initial bar state
244
+ if not self.disable:
245
+ self.display(check_delay=False)
246
+
247
+ def __iter__(self):
248
+ try:
249
+ it = super().__iter__()
250
+ for obj in it:
251
+ # return super(tqdm...) will not catch exception
252
+ yield obj
253
+ # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt
254
+ except: # NOQA
255
+ self.disp(bar_style='danger')
256
+ raise
257
+ # NB: don't `finally: close()`
258
+ # since this could be a shared bar which the user will `reset()`
259
+
260
+ def update(self, n=1):
261
+ try:
262
+ return super().update(n=n)
263
+ # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt
264
+ except: # NOQA
265
+ # cannot catch KeyboardInterrupt when using manual tqdm
266
+ # as the interrupt will most likely happen on another statement
267
+ self.disp(bar_style='danger')
268
+ raise
269
+ # NB: don't `finally: close()`
270
+ # since this could be a shared bar which the user will `reset()`
271
+
272
+ def close(self):
273
+ if self.disable:
274
+ return
275
+ super().close()
276
+ # Try to detect if there was an error or KeyboardInterrupt
277
+ # in manual mode: if n < total, things probably got wrong
278
+ if self.total and self.n < self.total:
279
+ self.disp(bar_style='danger', check_delay=False)
280
+ else:
281
+ if self.leave:
282
+ self.disp(bar_style='success', check_delay=False)
283
+ else:
284
+ self.disp(close=True, check_delay=False)
285
+
286
+ def clear(self, *_, **__):
287
+ pass
288
+
289
+ def reset(self, total=None):
290
+ """
291
+ Resets to 0 iterations for repeated use.
292
+
293
+ Consider combining with `leave=True`.
294
+
295
+ Parameters
296
+ ----------
297
+ total : int or float, optional. Total to use for the new bar.
298
+ """
299
+ if self.disable:
300
+ return super().reset(total=total)
301
+ _, pbar, _ = self.container.children
302
+ pbar.bar_style = ''
303
+ if total is not None:
304
+ pbar.max = total
305
+ if not self.total and self.ncols is None: # no longer unknown total
306
+ pbar.layout.width = None # reset width
307
+ return super().reset(total=total)
308
+
309
+
310
+ def tnrange(*args, **kwargs):
311
+ """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`."""
312
+ return tqdm_notebook(range(*args), **kwargs)
313
+
314
+
315
+ # Aliases
316
+ tqdm = tqdm_notebook
317
+ trange = tnrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/rich.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ `rich.progress` decorator for iterators.
3
+
4
+ Usage:
5
+ >>> from tqdm.rich import trange, tqdm
6
+ >>> for i in trange(10):
7
+ ... ...
8
+ """
9
+ from warnings import warn
10
+
11
+ from rich.progress import (
12
+ BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
13
+
14
+ from .std import TqdmExperimentalWarning
15
+ from .std import tqdm as std_tqdm
16
+
17
+ __author__ = {"github.com/": ["casperdcl"]}
18
+ __all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
19
+
20
+
21
+ class FractionColumn(ProgressColumn):
22
+ """Renders completed/total, e.g. '0.5/2.3 G'."""
23
+ def __init__(self, unit_scale=False, unit_divisor=1000):
24
+ self.unit_scale = unit_scale
25
+ self.unit_divisor = unit_divisor
26
+ super().__init__()
27
+
28
+ def render(self, task):
29
+ """Calculate common unit for completed and total."""
30
+ completed = int(task.completed)
31
+ total = int(task.total)
32
+ if self.unit_scale:
33
+ unit, suffix = filesize.pick_unit_and_suffix(
34
+ total,
35
+ ["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
36
+ self.unit_divisor,
37
+ )
38
+ else:
39
+ unit, suffix = filesize.pick_unit_and_suffix(total, [""], 1)
40
+ precision = 0 if unit == 1 else 1
41
+ return Text(
42
+ f"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}",
43
+ style="progress.download")
44
+
45
+
46
+ class RateColumn(ProgressColumn):
47
+ """Renders human readable transfer speed."""
48
+ def __init__(self, unit="", unit_scale=False, unit_divisor=1000):
49
+ self.unit = unit
50
+ self.unit_scale = unit_scale
51
+ self.unit_divisor = unit_divisor
52
+ super().__init__()
53
+
54
+ def render(self, task):
55
+ """Show data transfer speed."""
56
+ speed = task.speed
57
+ if speed is None:
58
+ return Text(f"? {self.unit}/s", style="progress.data.speed")
59
+ if self.unit_scale:
60
+ unit, suffix = filesize.pick_unit_and_suffix(
61
+ speed,
62
+ ["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
63
+ self.unit_divisor,
64
+ )
65
+ else:
66
+ unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1)
67
+ precision = 0 if unit == 1 else 1
68
+ return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s",
69
+ style="progress.data.speed")
70
+
71
+
72
+ class tqdm_rich(std_tqdm): # pragma: no cover
73
+ """Experimental rich.progress GUI version of tqdm!"""
74
+ # TODO: @classmethod: write()?
75
+ def __init__(self, *args, **kwargs):
76
+ """
77
+ This class accepts the following parameters *in addition* to
78
+ the parameters accepted by `tqdm`.
79
+
80
+ Parameters
81
+ ----------
82
+ progress : tuple, optional
83
+ arguments for `rich.progress.Progress()`.
84
+ options : dict, optional
85
+ keyword arguments for `rich.progress.Progress()`.
86
+ """
87
+ kwargs = kwargs.copy()
88
+ kwargs['gui'] = True
89
+ # convert disable = None to False
90
+ kwargs['disable'] = bool(kwargs.get('disable', False))
91
+ progress = kwargs.pop('progress', None)
92
+ options = kwargs.pop('options', {}).copy()
93
+ super().__init__(*args, **kwargs)
94
+
95
+ if self.disable:
96
+ return
97
+
98
+ warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
99
+ d = self.format_dict
100
+ if progress is None:
101
+ progress = (
102
+ "[progress.description]{task.description}"
103
+ "[progress.percentage]{task.percentage:>4.0f}%",
104
+ BarColumn(bar_width=None),
105
+ FractionColumn(
106
+ unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
107
+ "[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
108
+ ",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
109
+ unit_divisor=d['unit_divisor']), "]"
110
+ )
111
+ options.setdefault('transient', not self.leave)
112
+ self._prog = Progress(*progress, **options)
113
+ self._prog.__enter__()
114
+ self._task_id = self._prog.add_task(self.desc or "", **d)
115
+
116
+ def close(self):
117
+ if self.disable:
118
+ return
119
+ self.display() # print 100%, vis #1306
120
+ super().close()
121
+ self._prog.__exit__(None, None, None)
122
+
123
+ def clear(self, *_, **__):
124
+ pass
125
+
126
+ def display(self, *_, **__):
127
+ if not hasattr(self, '_prog'):
128
+ return
129
+ self._prog.update(self._task_id, completed=self.n, description=self.desc)
130
+
131
+ def reset(self, total=None):
132
+ """
133
+ Resets to 0 iterations for repeated use.
134
+
135
+ Parameters
136
+ ----------
137
+ total : int or float, optional. Total to use for the new bar.
138
+ """
139
+ if hasattr(self, '_prog'):
140
+ self._prog.reset(total=total)
141
+ super().reset(total=total)
142
+
143
+
144
+ def trrange(*args, **kwargs):
145
+ """Shortcut for `tqdm.rich.tqdm(range(*args), **kwargs)`."""
146
+ return tqdm_rich(range(*args), **kwargs)
147
+
148
+
149
+ # Aliases
150
+ tqdm = tqdm_rich
151
+ trange = trrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/std.py ADDED
@@ -0,0 +1,1524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Customisable progressbar decorator for iterators.
3
+ Includes a default `range` iterator printing to `stderr`.
4
+
5
+ Usage:
6
+ >>> from tqdm import trange, tqdm
7
+ >>> for i in trange(10):
8
+ ... ...
9
+ """
10
+ import sys
11
+ from collections import OrderedDict, defaultdict
12
+ from contextlib import contextmanager
13
+ from datetime import datetime, timedelta, timezone
14
+ from numbers import Number
15
+ from time import time
16
+ from warnings import warn
17
+ from weakref import WeakSet
18
+
19
+ from ._monitor import TMonitor
20
+ from .utils import (
21
+ CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper,
22
+ _is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim,
23
+ envwrap)
24
+
25
+ __author__ = "https://github.com/tqdm/tqdm#contributions"
26
+ __all__ = ['tqdm', 'trange',
27
+ 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning',
28
+ 'TqdmExperimentalWarning', 'TqdmDeprecationWarning',
29
+ 'TqdmMonitorWarning']
30
+
31
+
32
+ class TqdmTypeError(TypeError):
33
+ pass
34
+
35
+
36
+ class TqdmKeyError(KeyError):
37
+ pass
38
+
39
+
40
+ class TqdmWarning(Warning):
41
+ """base class for all tqdm warnings.
42
+
43
+ Used for non-external-code-breaking errors, such as garbled printing.
44
+ """
45
+ def __init__(self, msg, fp_write=None, *a, **k):
46
+ if fp_write is not None:
47
+ fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
48
+ else:
49
+ super().__init__(msg, *a, **k)
50
+
51
+
52
+ class TqdmExperimentalWarning(TqdmWarning, FutureWarning):
53
+ """beta feature, unstable API and behaviour"""
54
+ pass
55
+
56
+
57
+ class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning):
58
+ # not suppressed if raised
59
+ pass
60
+
61
+
62
+ class TqdmMonitorWarning(TqdmWarning, RuntimeWarning):
63
+ """tqdm monitor errors which do not affect external functionality"""
64
+ pass
65
+
66
+
67
+ def TRLock(*args, **kwargs):
68
+ """threading RLock"""
69
+ try:
70
+ from threading import RLock
71
+ return RLock(*args, **kwargs)
72
+ except (ImportError, OSError): # pragma: no cover
73
+ pass
74
+
75
+
76
+ class TqdmDefaultWriteLock(object):
77
+ """
78
+ Provide a default write lock for thread and multiprocessing safety.
79
+ Works only on platforms supporting `fork` (so Windows is excluded).
80
+ You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
81
+ before forking in order for the write lock to work.
82
+ On Windows, you need to supply the lock from the parent to the children as
83
+ an argument to joblib or the parallelism lib you use.
84
+ """
85
+ # global thread lock so no setup required for multithreading.
86
+ # NB: Do not create multiprocessing lock as it sets the multiprocessing
87
+ # context, disallowing `spawn()`/`forkserver()`
88
+ th_lock = TRLock()
89
+
90
+ def __init__(self):
91
+ # Create global parallelism locks to avoid racing issues with parallel
92
+ # bars works only if fork available (Linux/MacOSX, but not Windows)
93
+ cls = type(self)
94
+ root_lock = cls.th_lock
95
+ if root_lock is not None:
96
+ root_lock.acquire()
97
+ cls.create_mp_lock()
98
+ self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
99
+ if root_lock is not None:
100
+ root_lock.release()
101
+
102
+ def acquire(self, *a, **k):
103
+ for lock in self.locks:
104
+ lock.acquire(*a, **k)
105
+
106
+ def release(self):
107
+ for lock in self.locks[::-1]: # Release in inverse order of acquisition
108
+ lock.release()
109
+
110
+ def __enter__(self):
111
+ self.acquire()
112
+
113
+ def __exit__(self, *exc):
114
+ self.release()
115
+
116
+ @classmethod
117
+ def create_mp_lock(cls):
118
+ if not hasattr(cls, 'mp_lock'):
119
+ try:
120
+ from multiprocessing import RLock
121
+ cls.mp_lock = RLock()
122
+ except (ImportError, OSError): # pragma: no cover
123
+ cls.mp_lock = None
124
+
125
+ @classmethod
126
+ def create_th_lock(cls):
127
+ assert hasattr(cls, 'th_lock')
128
+ warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
129
+
130
+
131
+ class Bar(object):
132
+ """
133
+ `str.format`-able bar with format specifiers: `[width][type]`
134
+
135
+ - `width`
136
+ + unspecified (default): use `self.default_len`
137
+ + `int >= 0`: overrides `self.default_len`
138
+ + `int < 0`: subtract from `self.default_len`
139
+ - `type`
140
+ + `a`: ascii (`charset=self.ASCII` override)
141
+ + `u`: unicode (`charset=self.UTF` override)
142
+ + `b`: blank (`charset=" "` override)
143
+ """
144
+ ASCII = " 123456789#"
145
+ UTF = u" " + u''.join(map(chr, range(0x258F, 0x2587, -1)))
146
+ BLANK = " "
147
+ COLOUR_RESET = '\x1b[0m'
148
+ COLOUR_RGB = '\x1b[38;2;%d;%d;%dm'
149
+ COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m',
150
+ 'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m',
151
+ 'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
152
+
153
+ def __init__(self, frac, default_len=10, charset=UTF, colour=None):
154
+ if not 0 <= frac <= 1:
155
+ warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2)
156
+ frac = max(0, min(1, frac))
157
+ assert default_len > 0
158
+ self.frac = frac
159
+ self.default_len = default_len
160
+ self.charset = charset
161
+ self.colour = colour
162
+
163
+ @property
164
+ def colour(self):
165
+ return self._colour
166
+
167
+ @colour.setter
168
+ def colour(self, value):
169
+ if not value:
170
+ self._colour = None
171
+ return
172
+ try:
173
+ if value.upper() in self.COLOURS:
174
+ self._colour = self.COLOURS[value.upper()]
175
+ elif value[0] == '#' and len(value) == 7:
176
+ self._colour = self.COLOUR_RGB % tuple(
177
+ int(i, 16) for i in (value[1:3], value[3:5], value[5:7]))
178
+ else:
179
+ raise KeyError
180
+ except (KeyError, AttributeError):
181
+ warn("Unknown colour (%s); valid choices: [hex (#00ff00), %s]" % (
182
+ value, ", ".join(self.COLOURS)),
183
+ TqdmWarning, stacklevel=2)
184
+ self._colour = None
185
+
186
+ def __format__(self, format_spec):
187
+ if format_spec:
188
+ _type = format_spec[-1].lower()
189
+ try:
190
+ charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type]
191
+ except KeyError:
192
+ charset = self.charset
193
+ else:
194
+ format_spec = format_spec[:-1]
195
+ if format_spec:
196
+ N_BARS = int(format_spec)
197
+ if N_BARS < 0:
198
+ N_BARS += self.default_len
199
+ else:
200
+ N_BARS = self.default_len
201
+ else:
202
+ charset = self.charset
203
+ N_BARS = self.default_len
204
+
205
+ nsyms = len(charset) - 1
206
+ bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
207
+
208
+ res = charset[-1] * bar_length
209
+ if bar_length < N_BARS: # whitespace padding
210
+ res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1)
211
+ return self.colour + res + self.COLOUR_RESET if self.colour else res
212
+
213
+
214
+ class EMA(object):
215
+ """
216
+ Exponential moving average: smoothing to give progressively lower
217
+ weights to older values.
218
+
219
+ Parameters
220
+ ----------
221
+ smoothing : float, optional
222
+ Smoothing factor in range [0, 1], [default: 0.3].
223
+ Increase to give more weight to recent values.
224
+ Ranges from 0 (yields old value) to 1 (yields new value).
225
+ """
226
+ def __init__(self, smoothing=0.3):
227
+ self.alpha = smoothing
228
+ self.last = 0
229
+ self.calls = 0
230
+
231
+ def __call__(self, x=None):
232
+ """
233
+ Parameters
234
+ ----------
235
+ x : float
236
+ New value to include in EMA.
237
+ """
238
+ beta = 1 - self.alpha
239
+ if x is not None:
240
+ self.last = self.alpha * x + beta * self.last
241
+ self.calls += 1
242
+ return self.last / (1 - beta ** self.calls) if self.calls else self.last
243
+
244
+
245
+ class tqdm(Comparable):
246
+ """
247
+ Decorate an iterable object, returning an iterator which acts exactly
248
+ like the original iterable, but prints a dynamically updating
249
+ progressbar every time a value is requested.
250
+
251
+ Parameters
252
+ ----------
253
+ iterable : iterable, optional
254
+ Iterable to decorate with a progressbar.
255
+ Leave blank to manually manage the updates.
256
+ desc : str, optional
257
+ Prefix for the progressbar.
258
+ total : int or float, optional
259
+ The number of expected iterations. If unspecified,
260
+ len(iterable) is used if possible. If float("inf") or as a last
261
+ resort, only basic progress statistics are displayed
262
+ (no ETA, no progressbar).
263
+ If `gui` is True and this parameter needs subsequent updating,
264
+ specify an initial arbitrary large positive number,
265
+ e.g. 9e9.
266
+ leave : bool, optional
267
+ If [default: True], keeps all traces of the progressbar
268
+ upon termination of iteration.
269
+ If `None`, will leave only if `position` is `0`.
270
+ file : `io.TextIOWrapper` or `io.StringIO`, optional
271
+ Specifies where to output the progress messages
272
+ (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
273
+ methods. For encoding, see `write_bytes`.
274
+ ncols : int, optional
275
+ The width of the entire output message. If specified,
276
+ dynamically resizes the progressbar to stay within this bound.
277
+ If unspecified, attempts to use environment width. The
278
+ fallback is a meter width of 10 and no limit for the counter and
279
+ statistics. If 0, will not print any meter (only stats).
280
+ mininterval : float, optional
281
+ Minimum progress display update interval [default: 0.1] seconds.
282
+ maxinterval : float, optional
283
+ Maximum progress display update interval [default: 10] seconds.
284
+ Automatically adjusts `miniters` to correspond to `mininterval`
285
+ after long display update lag. Only works if `dynamic_miniters`
286
+ or monitor thread is enabled.
287
+ miniters : int or float, optional
288
+ Minimum progress display update interval, in iterations.
289
+ If 0 and `dynamic_miniters`, will automatically adjust to equal
290
+ `mininterval` (more CPU efficient, good for tight loops).
291
+ If > 0, will skip display of specified number of iterations.
292
+ Tweak this and `mininterval` to get very efficient loops.
293
+ If your progress is erratic with both fast and slow iterations
294
+ (network, skipping items, etc) you should set miniters=1.
295
+ ascii : bool or str, optional
296
+ If unspecified or False, use unicode (smooth blocks) to fill
297
+ the meter. The fallback is to use ASCII characters " 123456789#".
298
+ disable : bool, optional
299
+ Whether to disable the entire progressbar wrapper
300
+ [default: False]. If set to None, disable on non-TTY.
301
+ unit : str, optional
302
+ String that will be used to define the unit of each iteration
303
+ [default: it].
304
+ unit_scale : bool or int or float, optional
305
+ If 1 or True, the number of iterations will be reduced/scaled
306
+ automatically and a metric prefix following the
307
+ International System of Units standard will be added
308
+ (kilo, mega, etc.) [default: False]. If any other non-zero
309
+ number, will scale `total` and `n`.
310
+ dynamic_ncols : bool, optional
311
+ If set, constantly alters `ncols` and `nrows` to the
312
+ environment (allowing for window resizes) [default: False].
313
+ smoothing : float, optional
314
+ Exponential moving average smoothing factor for speed estimates
315
+ (ignored in GUI mode). Ranges from 0 (average speed) to 1
316
+ (current/instantaneous speed) [default: 0.3].
317
+ bar_format : str, optional
318
+ Specify a custom bar string formatting. May impact performance.
319
+ [default: '{l_bar}{bar}{r_bar}'], where
320
+ l_bar='{desc}: {percentage:3.0f}%|' and
321
+ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
322
+ '{rate_fmt}{postfix}]'
323
+ Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
324
+ percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
325
+ rate, rate_fmt, rate_noinv, rate_noinv_fmt,
326
+ rate_inv, rate_inv_fmt, postfix, unit_divisor,
327
+ remaining, remaining_s, eta.
328
+ Note that a trailing ": " is automatically removed after {desc}
329
+ if the latter is empty.
330
+ initial : int or float, optional
331
+ The initial counter value. Useful when restarting a progress
332
+ bar [default: 0]. If using float, consider specifying `{n:.3f}`
333
+ or similar in `bar_format`, or specifying `unit_scale`.
334
+ position : int, optional
335
+ Specify the line offset to print this bar (starting from 0)
336
+ Automatic if unspecified.
337
+ Useful to manage multiple bars at once (eg, from threads).
338
+ postfix : dict or *, optional
339
+ Specify additional stats to display at the end of the bar.
340
+ Calls `set_postfix(**postfix)` if possible (dict).
341
+ unit_divisor : float, optional
342
+ [default: 1000], ignored unless `unit_scale` is True.
343
+ write_bytes : bool, optional
344
+ Whether to write bytes. If (default: False) will write unicode.
345
+ lock_args : tuple, optional
346
+ Passed to `refresh` for intermediate output
347
+ (initialisation, iterating, and updating).
348
+ nrows : int, optional
349
+ The screen height. If specified, hides nested bars outside this
350
+ bound. If unspecified, attempts to use environment height.
351
+ The fallback is 20.
352
+ colour : str, optional
353
+ Bar colour (e.g. 'green', '#00ff00').
354
+ delay : float, optional
355
+ Don't display until [default: 0] seconds have elapsed.
356
+ gui : bool, optional
357
+ WARNING: internal parameter - do not use.
358
+ Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
359
+ matplotlib animations for a graphical output [default: False].
360
+
361
+ Returns
362
+ -------
363
+ out : decorated iterator.
364
+ """
365
+
366
+ monitor_interval = 10 # set to 0 to disable the thread
367
+ monitor = None
368
+ _instances = WeakSet()
369
+
370
+ @staticmethod
371
+ def format_sizeof(num, suffix='', divisor=1000):
372
+ """
373
+ Formats a number (greater than unity) with SI Order of Magnitude
374
+ prefixes.
375
+
376
+ Parameters
377
+ ----------
378
+ num : float
379
+ Number ( >= 1) to format.
380
+ suffix : str, optional
381
+ Post-postfix [default: ''].
382
+ divisor : float, optional
383
+ Divisor between prefixes [default: 1000].
384
+
385
+ Returns
386
+ -------
387
+ out : str
388
+ Number with Order of Magnitude SI unit postfix.
389
+ """
390
+ for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
391
+ if abs(num) < 999.5:
392
+ if abs(num) < 99.95:
393
+ if abs(num) < 9.995:
394
+ return f'{num:1.2f}{unit}{suffix}'
395
+ return f'{num:2.1f}{unit}{suffix}'
396
+ return f'{num:3.0f}{unit}{suffix}'
397
+ num /= divisor
398
+ return f'{num:3.1f}Y{suffix}'
399
+
400
+ @staticmethod
401
+ def format_interval(t):
402
+ """
403
+ Formats a number of seconds as a clock time, [H:]MM:SS
404
+
405
+ Parameters
406
+ ----------
407
+ t : int
408
+ Number of seconds.
409
+
410
+ Returns
411
+ -------
412
+ out : str
413
+ [H:]MM:SS
414
+ """
415
+ mins, s = divmod(int(t), 60)
416
+ h, m = divmod(mins, 60)
417
+ return f'{h:d}:{m:02d}:{s:02d}' if h else f'{m:02d}:{s:02d}'
418
+
419
+ @staticmethod
420
+ def format_num(n):
421
+ """
422
+ Intelligent scientific notation (.3g).
423
+
424
+ Parameters
425
+ ----------
426
+ n : int or float or Numeric
427
+ A Number.
428
+
429
+ Returns
430
+ -------
431
+ out : str
432
+ Formatted number.
433
+ """
434
+ f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-')
435
+ n = str(n)
436
+ return f if len(f) < len(n) else n
437
+
438
+ @staticmethod
439
+ def status_printer(file):
440
+ """
441
+ Manage the printing and in-place updating of a line of characters.
442
+ Note that if the string is longer than a line, then in-place
443
+ updating may not work (it will print a new line at each refresh).
444
+ """
445
+ fp = file
446
+ fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
447
+ if fp in (sys.stderr, sys.stdout):
448
+ getattr(sys.stderr, 'flush', lambda: None)()
449
+ getattr(sys.stdout, 'flush', lambda: None)()
450
+
451
+ def fp_write(s):
452
+ fp.write(str(s))
453
+ fp_flush()
454
+
455
+ last_len = [0]
456
+
457
+ def print_status(s):
458
+ len_s = disp_len(s)
459
+ fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
460
+ last_len[0] = len_s
461
+
462
+ return print_status
463
+
464
+ @staticmethod
465
+ def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it',
466
+ unit_scale=False, rate=None, bar_format=None, postfix=None,
467
+ unit_divisor=1000, initial=0, colour=None, **extra_kwargs):
468
+ """
469
+ Return a string-based progress bar given some parameters
470
+
471
+ Parameters
472
+ ----------
473
+ n : int or float
474
+ Number of finished iterations.
475
+ total : int or float
476
+ The expected total number of iterations. If meaningless (None),
477
+ only basic progress statistics are displayed (no ETA).
478
+ elapsed : float
479
+ Number of seconds passed since start.
480
+ ncols : int, optional
481
+ The width of the entire output message. If specified,
482
+ dynamically resizes `{bar}` to stay within this bound
483
+ [default: None]. If `0`, will not print any bar (only stats).
484
+ The fallback is `{bar:10}`.
485
+ prefix : str, optional
486
+ Prefix message (included in total width) [default: ''].
487
+ Use as {desc} in bar_format string.
488
+ ascii : bool, optional or str, optional
489
+ If not set, use unicode (smooth blocks) to fill the meter
490
+ [default: False]. The fallback is to use ASCII characters
491
+ " 123456789#".
492
+ unit : str, optional
493
+ The iteration unit [default: 'it'].
494
+ unit_scale : bool or int or float, optional
495
+ If 1 or True, the number of iterations will be printed with an
496
+ appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
497
+ [default: False]. If any other non-zero number, will scale
498
+ `total` and `n`.
499
+ rate : float, optional
500
+ Manual override for iteration rate.
501
+ If [default: None], uses n/elapsed.
502
+ bar_format : str, optional
503
+ Specify a custom bar string formatting. May impact performance.
504
+ [default: '{l_bar}{bar}{r_bar}'], where
505
+ l_bar='{desc}: {percentage:3.0f}%|' and
506
+ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
507
+ '{rate_fmt}{postfix}]'
508
+ Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
509
+ percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
510
+ rate, rate_fmt, rate_noinv, rate_noinv_fmt,
511
+ rate_inv, rate_inv_fmt, postfix, unit_divisor,
512
+ remaining, remaining_s, eta.
513
+ Note that a trailing ": " is automatically removed after {desc}
514
+ if the latter is empty.
515
+ postfix : *, optional
516
+ Similar to `prefix`, but placed at the end
517
+ (e.g. for additional stats).
518
+ Note: postfix is usually a string (not a dict) for this method,
519
+ and will if possible be set to postfix = ', ' + postfix.
520
+ However other types are supported (#382).
521
+ unit_divisor : float, optional
522
+ [default: 1000], ignored unless `unit_scale` is True.
523
+ initial : int or float, optional
524
+ The initial counter value [default: 0].
525
+ colour : str, optional
526
+ Bar colour (e.g. 'green', '#00ff00').
527
+
528
+ Returns
529
+ -------
530
+ out : Formatted meter and stats, ready to display.
531
+ """
532
+
533
+ # sanity check: total
534
+ if total and n >= (total + 0.5): # allow float imprecision (#849)
535
+ total = None
536
+
537
+ # apply custom scale if necessary
538
+ if unit_scale and unit_scale not in (True, 1):
539
+ if total:
540
+ total *= unit_scale
541
+ n *= unit_scale
542
+ if rate:
543
+ rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt
544
+ unit_scale = False
545
+
546
+ elapsed_str = tqdm.format_interval(elapsed)
547
+
548
+ # if unspecified, attempt to use rate = average speed
549
+ # (we allow manual override since predicting time is an arcane art)
550
+ if rate is None and elapsed:
551
+ rate = (n - initial) / elapsed
552
+ inv_rate = 1 / rate if rate else None
553
+ format_sizeof = tqdm.format_sizeof
554
+ rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}')
555
+ if rate else '?') + unit + '/s'
556
+ rate_inv_fmt = (
557
+ (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}')
558
+ if inv_rate else '?') + 's/' + unit
559
+ rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
560
+
561
+ if unit_scale:
562
+ n_fmt = format_sizeof(n, divisor=unit_divisor)
563
+ total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?'
564
+ else:
565
+ n_fmt = str(n)
566
+ total_fmt = str(total) if total is not None else '?'
567
+
568
+ try:
569
+ postfix = ', ' + postfix if postfix else ''
570
+ except TypeError:
571
+ pass
572
+
573
+ remaining = (total - n) / rate if rate and total else 0
574
+ remaining_str = tqdm.format_interval(remaining) if rate else '?'
575
+ try:
576
+ eta_dt = (datetime.now() + timedelta(seconds=remaining)
577
+ if rate and total else datetime.fromtimestamp(0, timezone.utc))
578
+ except OverflowError:
579
+ eta_dt = datetime.max
580
+
581
+ # format the stats displayed to the left and right sides of the bar
582
+ if prefix:
583
+ # old prefix setup work around
584
+ bool_prefix_colon_already = (prefix[-2:] == ": ")
585
+ l_bar = prefix if bool_prefix_colon_already else prefix + ": "
586
+ else:
587
+ l_bar = ''
588
+
589
+ r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
590
+
591
+ # Custom bar formatting
592
+ # Populate a dict with all available progress indicators
593
+ format_dict = {
594
+ # slight extension of self.format_dict
595
+ 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt,
596
+ 'elapsed': elapsed_str, 'elapsed_s': elapsed,
597
+ 'ncols': ncols, 'desc': prefix or '', 'unit': unit,
598
+ 'rate': inv_rate if inv_rate and inv_rate > 1 else rate,
599
+ 'rate_fmt': rate_fmt, 'rate_noinv': rate,
600
+ 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate,
601
+ 'rate_inv_fmt': rate_inv_fmt,
602
+ 'postfix': postfix, 'unit_divisor': unit_divisor,
603
+ 'colour': colour,
604
+ # plus more useful definitions
605
+ 'remaining': remaining_str, 'remaining_s': remaining,
606
+ 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt,
607
+ **extra_kwargs}
608
+
609
+ # total is known: we can predict some stats
610
+ if total:
611
+ # fractional and percentage progress
612
+ frac = n / total
613
+ percentage = frac * 100
614
+
615
+ l_bar += f'{percentage:3.0f}%|'
616
+
617
+ if ncols == 0:
618
+ return l_bar[:-1] + r_bar[1:]
619
+
620
+ format_dict.update(l_bar=l_bar)
621
+ if bar_format:
622
+ format_dict.update(percentage=percentage)
623
+
624
+ # auto-remove colon for empty `{desc}`
625
+ if not prefix:
626
+ bar_format = bar_format.replace("{desc}: ", '')
627
+ else:
628
+ bar_format = "{l_bar}{bar}{r_bar}"
629
+
630
+ full_bar = FormatReplace()
631
+ nobar = bar_format.format(bar=full_bar, **format_dict)
632
+ if not full_bar.format_called:
633
+ return nobar # no `{bar}`; nothing else to do
634
+
635
+ # Formatting progress bar space available for bar's display
636
+ full_bar = Bar(frac,
637
+ max(1, ncols - disp_len(nobar)) if ncols else 10,
638
+ charset=Bar.ASCII if ascii is True else ascii or Bar.UTF,
639
+ colour=colour)
640
+ if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
641
+ bar_format = str(bar_format)
642
+ res = bar_format.format(bar=full_bar, **format_dict)
643
+ return disp_trim(res, ncols) if ncols else res
644
+
645
+ elif bar_format:
646
+ # user-specified bar_format but no total
647
+ l_bar += '|'
648
+ format_dict.update(l_bar=l_bar, percentage=0)
649
+ full_bar = FormatReplace()
650
+ nobar = bar_format.format(bar=full_bar, **format_dict)
651
+ if not full_bar.format_called:
652
+ return nobar
653
+ full_bar = Bar(0,
654
+ max(1, ncols - disp_len(nobar)) if ncols else 10,
655
+ charset=Bar.BLANK, colour=colour)
656
+ res = bar_format.format(bar=full_bar, **format_dict)
657
+ return disp_trim(res, ncols) if ncols else res
658
+ else:
659
+ # no total: no progressbar, ETA, just progress stats
660
+ return (f'{(prefix + ": ") if prefix else ""}'
661
+ f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
662
+
663
+ def __new__(cls, *_, **__):
664
+ instance = object.__new__(cls)
665
+ with cls.get_lock(): # also constructs lock if non-existent
666
+ cls._instances.add(instance)
667
+ # create monitoring thread
668
+ if cls.monitor_interval and (cls.monitor is None
669
+ or not cls.monitor.report()):
670
+ try:
671
+ cls.monitor = TMonitor(cls, cls.monitor_interval)
672
+ except Exception as e: # pragma: nocover
673
+ warn("tqdm:disabling monitor support"
674
+ " (monitor_interval = 0) due to:\n" + str(e),
675
+ TqdmMonitorWarning, stacklevel=2)
676
+ cls.monitor_interval = 0
677
+ return instance
678
+
679
+ @classmethod
680
+ def _get_free_pos(cls, instance=None):
681
+ """Skips specified instance."""
682
+ positions = {abs(inst.pos) for inst in cls._instances
683
+ if inst is not instance and hasattr(inst, "pos")}
684
+ return min(set(range(len(positions) + 1)).difference(positions))
685
+
686
+ @classmethod
687
+ def _decr_instances(cls, instance):
688
+ """
689
+ Remove from list and reposition another unfixed bar
690
+ to fill the new gap.
691
+
692
+ This means that by default (where all nested bars are unfixed),
693
+ order is not maintained but screen flicker/blank space is minimised.
694
+ (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
695
+ """
696
+ with cls._lock:
697
+ try:
698
+ cls._instances.remove(instance)
699
+ except KeyError:
700
+ # if not instance.gui: # pragma: no cover
701
+ # raise
702
+ pass # py2: maybe magically removed already
703
+ # else:
704
+ if not instance.gui:
705
+ last = (instance.nrows or 20) - 1
706
+ # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`)
707
+ instances = list(filter(
708
+ lambda i: hasattr(i, "pos") and last <= i.pos,
709
+ cls._instances))
710
+ # set first found to current `pos`
711
+ if instances:
712
+ inst = min(instances, key=lambda i: i.pos)
713
+ inst.clear(nolock=True)
714
+ inst.pos = abs(instance.pos)
715
+
716
+ @classmethod
717
+ def write(cls, s, file=None, end="\n", nolock=False):
718
+ """Print a message via tqdm (without overlap with bars)."""
719
+ fp = file if file is not None else sys.stdout
720
+ with cls.external_write_mode(file=file, nolock=nolock):
721
+ # Write the message
722
+ fp.write(s)
723
+ fp.write(end)
724
+
725
+ @classmethod
726
+ @contextmanager
727
+ def external_write_mode(cls, file=None, nolock=False):
728
+ """
729
+ Disable tqdm within context and refresh tqdm when exits.
730
+ Useful when writing to standard output stream
731
+ """
732
+ fp = file if file is not None else sys.stdout
733
+
734
+ try:
735
+ if not nolock:
736
+ cls.get_lock().acquire()
737
+ # Clear all bars
738
+ inst_cleared = []
739
+ for inst in getattr(cls, '_instances', []):
740
+ # Clear instance if in the target output file
741
+ # or if write output + tqdm output are both either
742
+ # sys.stdout or sys.stderr (because both are mixed in terminal)
743
+ if hasattr(inst, "start_t") and (inst.fp == fp or all(
744
+ f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))):
745
+ inst.clear(nolock=True)
746
+ inst_cleared.append(inst)
747
+ yield
748
+ # Force refresh display of bars we cleared
749
+ for inst in inst_cleared:
750
+ inst.refresh(nolock=True)
751
+ finally:
752
+ if not nolock:
753
+ cls._lock.release()
754
+
755
+ @classmethod
756
+ def set_lock(cls, lock):
757
+ """Set the global lock."""
758
+ cls._lock = lock
759
+
760
+ @classmethod
761
+ def get_lock(cls):
762
+ """Get the global lock. Construct it if it does not exist."""
763
+ if not hasattr(cls, '_lock'):
764
+ cls._lock = TqdmDefaultWriteLock()
765
+ return cls._lock
766
+
767
+ @classmethod
768
+ def pandas(cls, **tqdm_kwargs):
769
+ """
770
+ Registers the current `tqdm` class with
771
+ pandas.core.
772
+ ( frame.DataFrame
773
+ | series.Series
774
+ | groupby.(generic.)DataFrameGroupBy
775
+ | groupby.(generic.)SeriesGroupBy
776
+ ).progress_apply
777
+
778
+ A new instance will be created every time `progress_apply` is called,
779
+ and each instance will automatically `close()` upon completion.
780
+
781
+ Parameters
782
+ ----------
783
+ tqdm_kwargs : arguments for the tqdm instance
784
+
785
+ Examples
786
+ --------
787
+ >>> import pandas as pd
788
+ >>> import numpy as np
789
+ >>> from tqdm import tqdm
790
+ >>> from tqdm.gui import tqdm as tqdm_gui
791
+ >>>
792
+ >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
793
+ >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc
794
+ >>> # Now you can use `progress_apply` instead of `apply`
795
+ >>> df.groupby(0).progress_apply(lambda x: x**2)
796
+
797
+ References
798
+ ----------
799
+ <https://stackoverflow.com/questions/18603270/\
800
+ progress-indicator-during-pandas-operations-python>
801
+ """
802
+ from warnings import catch_warnings, simplefilter
803
+
804
+ from pandas.core.frame import DataFrame
805
+ from pandas.core.series import Series
806
+ try:
807
+ with catch_warnings():
808
+ simplefilter("ignore", category=FutureWarning)
809
+ from pandas import Panel
810
+ except ImportError: # pandas>=1.2.0
811
+ Panel = None
812
+ Rolling, Expanding = None, None
813
+ try: # pandas>=1.0.0
814
+ from pandas.core.window.rolling import _Rolling_and_Expanding
815
+ except ImportError:
816
+ try: # pandas>=0.18.0
817
+ from pandas.core.window import _Rolling_and_Expanding
818
+ except ImportError: # pandas>=1.2.0
819
+ try: # pandas>=1.2.0
820
+ from pandas.core.window.expanding import Expanding
821
+ from pandas.core.window.rolling import Rolling
822
+ _Rolling_and_Expanding = Rolling, Expanding
823
+ except ImportError: # pragma: no cover
824
+ _Rolling_and_Expanding = None
825
+ try: # pandas>=0.25.0
826
+ from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy
827
+ from pandas.core.groupby.generic import DataFrameGroupBy
828
+ except ImportError: # pragma: no cover
829
+ try: # pandas>=0.23.0
830
+ from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy
831
+ except ImportError:
832
+ from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
833
+ try: # pandas>=0.23.0
834
+ from pandas.core.groupby.groupby import GroupBy
835
+ except ImportError: # pragma: no cover
836
+ from pandas.core.groupby import GroupBy
837
+
838
+ try: # pandas>=0.23.0
839
+ from pandas.core.groupby.groupby import PanelGroupBy
840
+ except ImportError:
841
+ try:
842
+ from pandas.core.groupby import PanelGroupBy
843
+ except ImportError: # pandas>=0.25.0
844
+ PanelGroupBy = None
845
+
846
+ tqdm_kwargs = tqdm_kwargs.copy()
847
+ deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
848
+
849
+ def inner_generator(df_function='apply'):
850
+ def inner(df, func, *args, **kwargs):
851
+ """
852
+ Parameters
853
+ ----------
854
+ df : (DataFrame|Series)[GroupBy]
855
+ Data (may be grouped).
856
+ func : function
857
+ To be applied on the (grouped) data.
858
+ **kwargs : optional
859
+ Transmitted to `df.apply()`.
860
+ """
861
+
862
+ # Precompute total iterations
863
+ total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
864
+ if total is None: # not grouped
865
+ if df_function == 'applymap':
866
+ total = df.size
867
+ elif isinstance(df, Series):
868
+ total = len(df)
869
+ elif (_Rolling_and_Expanding is None or
870
+ not isinstance(df, _Rolling_and_Expanding)):
871
+ # DataFrame or Panel
872
+ axis = kwargs.get('axis', 0)
873
+ if axis == 'index':
874
+ axis = 0
875
+ elif axis == 'columns':
876
+ axis = 1
877
+ # when axis=0, total is shape[axis1]
878
+ total = df.size // df.shape[axis]
879
+
880
+ # Init bar
881
+ if deprecated_t[0] is not None:
882
+ t = deprecated_t[0]
883
+ deprecated_t[0] = None
884
+ else:
885
+ t = cls(total=total, **tqdm_kwargs)
886
+
887
+ if len(args) > 0:
888
+ # *args intentionally not supported (see #244, #299)
889
+ TqdmDeprecationWarning(
890
+ "Except func, normal arguments are intentionally" +
891
+ " not supported by" +
892
+ " `(DataFrame|Series|GroupBy).progress_apply`." +
893
+ " Use keyword arguments instead.",
894
+ fp_write=getattr(t.fp, 'write', sys.stderr.write))
895
+
896
+ try: # pandas>=1.3.0
897
+ from pandas.core.common import is_builtin_func
898
+ except ImportError:
899
+ is_builtin_func = df._is_builtin_func
900
+ try:
901
+ func = is_builtin_func(func)
902
+ except TypeError:
903
+ pass
904
+
905
+ # Define bar updating wrapper
906
+ def wrapper(*args, **kwargs):
907
+ # update tbar correctly
908
+ # it seems `pandas apply` calls `func` twice
909
+ # on the first column/row to decide whether it can
910
+ # take a fast or slow code path; so stop when t.total==t.n
911
+ t.update(n=1 if not t.total or t.n < t.total else 0)
912
+ return func(*args, **kwargs)
913
+
914
+ # Apply the provided function (in **kwargs)
915
+ # on the df using our wrapper (which provides bar updating)
916
+ try:
917
+ return getattr(df, df_function)(wrapper, **kwargs)
918
+ finally:
919
+ t.close()
920
+
921
+ return inner
922
+
923
+ # Monkeypatch pandas to provide easy methods
924
+ # Enable custom tqdm progress in pandas!
925
+ Series.progress_apply = inner_generator()
926
+ SeriesGroupBy.progress_apply = inner_generator()
927
+ Series.progress_map = inner_generator('map')
928
+ SeriesGroupBy.progress_map = inner_generator('map')
929
+
930
+ DataFrame.progress_apply = inner_generator()
931
+ DataFrameGroupBy.progress_apply = inner_generator()
932
+ DataFrame.progress_applymap = inner_generator('applymap')
933
+ DataFrame.progress_map = inner_generator('map')
934
+ DataFrameGroupBy.progress_map = inner_generator('map')
935
+
936
+ if Panel is not None:
937
+ Panel.progress_apply = inner_generator()
938
+ if PanelGroupBy is not None:
939
+ PanelGroupBy.progress_apply = inner_generator()
940
+
941
+ GroupBy.progress_apply = inner_generator()
942
+ GroupBy.progress_aggregate = inner_generator('aggregate')
943
+ GroupBy.progress_transform = inner_generator('transform')
944
+
945
+ if Rolling is not None and Expanding is not None:
946
+ Rolling.progress_apply = inner_generator()
947
+ Expanding.progress_apply = inner_generator()
948
+ elif _Rolling_and_Expanding is not None:
949
+ _Rolling_and_Expanding.progress_apply = inner_generator()
950
+
951
+ # override defaults via env vars
952
+ @envwrap("TQDM_", is_method=True, types={'total': float, 'ncols': int, 'miniters': float,
953
+ 'position': int, 'nrows': int})
954
+ def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
955
+ ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
956
+ ascii=None, disable=False, unit='it', unit_scale=False,
957
+ dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
958
+ position=None, postfix=None, unit_divisor=1000, write_bytes=False,
959
+ lock_args=None, nrows=None, colour=None, delay=0.0, gui=False,
960
+ **kwargs):
961
+ """see tqdm.tqdm for arguments"""
962
+ if file is None:
963
+ file = sys.stderr
964
+
965
+ if write_bytes:
966
+ # Despite coercing unicode into bytes, py2 sys.std* streams
967
+ # should have bytes written to them.
968
+ file = SimpleTextIOWrapper(
969
+ file, encoding=getattr(file, 'encoding', None) or 'utf-8')
970
+
971
+ file = DisableOnWriteError(file, tqdm_instance=self)
972
+
973
+ if disable is None and hasattr(file, "isatty") and not file.isatty():
974
+ disable = True
975
+
976
+ if total is None and iterable is not None:
977
+ try:
978
+ total = len(iterable)
979
+ except (TypeError, AttributeError):
980
+ total = None
981
+ if total == float("inf"):
982
+ # Infinite iterations, behave same as unknown
983
+ total = None
984
+
985
+ if disable:
986
+ self.iterable = iterable
987
+ self.disable = disable
988
+ with self._lock:
989
+ self.pos = self._get_free_pos(self)
990
+ self._instances.remove(self)
991
+ self.n = initial
992
+ self.total = total
993
+ self.leave = leave
994
+ return
995
+
996
+ if kwargs:
997
+ self.disable = True
998
+ with self._lock:
999
+ self.pos = self._get_free_pos(self)
1000
+ self._instances.remove(self)
1001
+ raise (
1002
+ TqdmDeprecationWarning(
1003
+ "`nested` is deprecated and automated.\n"
1004
+ "Use `position` instead for manual control.\n",
1005
+ fp_write=getattr(file, 'write', sys.stderr.write))
1006
+ if "nested" in kwargs else
1007
+ TqdmKeyError("Unknown argument(s): " + str(kwargs)))
1008
+
1009
+ # Preprocess the arguments
1010
+ if (
1011
+ (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout))
1012
+ ) or dynamic_ncols: # pragma: no cover
1013
+ if dynamic_ncols:
1014
+ dynamic_ncols = _screen_shape_wrapper()
1015
+ if dynamic_ncols:
1016
+ ncols, nrows = dynamic_ncols(file)
1017
+ else:
1018
+ _dynamic_ncols = _screen_shape_wrapper()
1019
+ if _dynamic_ncols:
1020
+ _ncols, _nrows = _dynamic_ncols(file)
1021
+ if ncols is None:
1022
+ ncols = _ncols
1023
+ if nrows is None:
1024
+ nrows = _nrows
1025
+
1026
+ if miniters is None:
1027
+ miniters = 0
1028
+ dynamic_miniters = True
1029
+ else:
1030
+ dynamic_miniters = False
1031
+
1032
+ if mininterval is None:
1033
+ mininterval = 0
1034
+
1035
+ if maxinterval is None:
1036
+ maxinterval = 0
1037
+
1038
+ if ascii is None:
1039
+ ascii = not _supports_unicode(file)
1040
+
1041
+ if bar_format and ascii is not True and not _is_ascii(ascii):
1042
+ # Convert bar format into unicode since terminal uses unicode
1043
+ bar_format = str(bar_format)
1044
+
1045
+ if smoothing is None:
1046
+ smoothing = 0
1047
+
1048
+ # Store the arguments
1049
+ self.iterable = iterable
1050
+ self.desc = desc or ''
1051
+ self.total = total
1052
+ self.leave = leave
1053
+ self.fp = file
1054
+ self.ncols = ncols
1055
+ self.nrows = nrows
1056
+ self.mininterval = mininterval
1057
+ self.maxinterval = maxinterval
1058
+ self.miniters = miniters
1059
+ self.dynamic_miniters = dynamic_miniters
1060
+ self.ascii = ascii
1061
+ self.disable = disable
1062
+ self.unit = unit
1063
+ self.unit_scale = unit_scale
1064
+ self.unit_divisor = unit_divisor
1065
+ self.initial = initial
1066
+ self.lock_args = lock_args
1067
+ self.delay = delay
1068
+ self.gui = gui
1069
+ self.dynamic_ncols = dynamic_ncols
1070
+ self.smoothing = smoothing
1071
+ self._ema_dn = EMA(smoothing)
1072
+ self._ema_dt = EMA(smoothing)
1073
+ self._ema_miniters = EMA(smoothing)
1074
+ self.bar_format = bar_format
1075
+ self.postfix = None
1076
+ self.colour = colour
1077
+ self._time = time
1078
+ if postfix:
1079
+ try:
1080
+ self.set_postfix(refresh=False, **postfix)
1081
+ except TypeError:
1082
+ self.postfix = postfix
1083
+
1084
+ # Init the iterations counters
1085
+ self.last_print_n = initial
1086
+ self.n = initial
1087
+
1088
+ # if nested, at initial sp() call we replace '\r' by '\n' to
1089
+ # not overwrite the outer progress bar
1090
+ with self._lock:
1091
+ # mark fixed positions as negative
1092
+ self.pos = self._get_free_pos(self) if position is None else -position
1093
+
1094
+ if not gui:
1095
+ # Initialize the screen printer
1096
+ self.sp = self.status_printer(self.fp)
1097
+ if delay <= 0:
1098
+ self.refresh(lock_args=self.lock_args)
1099
+
1100
+ # Init the time counter
1101
+ self.last_print_t = self._time()
1102
+ # NB: Avoid race conditions by setting start_t at the very end of init
1103
+ self.start_t = self.last_print_t
1104
+
1105
+ def __bool__(self):
1106
+ if self.total is not None:
1107
+ return self.total > 0
1108
+ if self.iterable is None:
1109
+ raise TypeError('bool() undefined when iterable == total == None')
1110
+ return bool(self.iterable)
1111
+
1112
+ def __len__(self):
1113
+ return (
1114
+ self.total if self.iterable is None
1115
+ else self.iterable.shape[0] if hasattr(self.iterable, "shape")
1116
+ else len(self.iterable) if hasattr(self.iterable, "__len__")
1117
+ else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__")
1118
+ else getattr(self, "total", None))
1119
+
1120
+ def __reversed__(self):
1121
+ try:
1122
+ orig = self.iterable
1123
+ except AttributeError:
1124
+ raise TypeError("'tqdm' object is not reversible")
1125
+ else:
1126
+ self.iterable = reversed(self.iterable)
1127
+ return self.__iter__()
1128
+ finally:
1129
+ self.iterable = orig
1130
+
1131
+ def __contains__(self, item):
1132
+ contains = getattr(self.iterable, '__contains__', None)
1133
+ return contains(item) if contains is not None else item in self.__iter__()
1134
+
1135
+ def __enter__(self):
1136
+ return self
1137
+
1138
+ def __exit__(self, exc_type, exc_value, traceback):
1139
+ try:
1140
+ self.close()
1141
+ except AttributeError:
1142
+ # maybe eager thread cleanup upon external error
1143
+ if (exc_type, exc_value, traceback) == (None, None, None):
1144
+ raise
1145
+ warn("AttributeError ignored", TqdmWarning, stacklevel=2)
1146
+
1147
+ def __del__(self):
1148
+ self.close()
1149
+
1150
+ def __str__(self):
1151
+ return self.format_meter(**self.format_dict)
1152
+
1153
+ @property
1154
+ def _comparable(self):
1155
+ return abs(getattr(self, "pos", 1 << 31))
1156
+
1157
+ def __hash__(self):
1158
+ return id(self)
1159
+
1160
+ def __iter__(self):
1161
+ """Backward-compatibility to use: for x in tqdm(iterable)"""
1162
+
1163
+ # Inlining instance variables as locals (speed optimisation)
1164
+ iterable = self.iterable
1165
+
1166
+ # If the bar is disabled, then just walk the iterable
1167
+ # (note: keep this check outside the loop for performance)
1168
+ if self.disable:
1169
+ for obj in iterable:
1170
+ yield obj
1171
+ return
1172
+
1173
+ mininterval = self.mininterval
1174
+ last_print_t = self.last_print_t
1175
+ last_print_n = self.last_print_n
1176
+ min_start_t = self.start_t + self.delay
1177
+ n = self.n
1178
+ time = self._time
1179
+
1180
+ try:
1181
+ for obj in iterable:
1182
+ yield obj
1183
+ # Update and possibly print the progressbar.
1184
+ # Note: does not call self.update(1) for speed optimisation.
1185
+ n += 1
1186
+
1187
+ if n - last_print_n >= self.miniters:
1188
+ cur_t = time()
1189
+ dt = cur_t - last_print_t
1190
+ if dt >= mininterval and cur_t >= min_start_t:
1191
+ self.update(n - last_print_n)
1192
+ last_print_n = self.last_print_n
1193
+ last_print_t = self.last_print_t
1194
+ finally:
1195
+ self.n = n
1196
+ self.close()
1197
+
1198
+ def update(self, n=1):
1199
+ """
1200
+ Manually update the progress bar, useful for streams
1201
+ such as reading files.
1202
+ E.g.:
1203
+ >>> t = tqdm(total=filesize) # Initialise
1204
+ >>> for current_buffer in stream:
1205
+ ... ...
1206
+ ... t.update(len(current_buffer))
1207
+ >>> t.close()
1208
+ The last line is highly recommended, but possibly not necessary if
1209
+ `t.update()` will be called in such a way that `filesize` will be
1210
+ exactly reached and printed.
1211
+
1212
+ Parameters
1213
+ ----------
1214
+ n : int or float, optional
1215
+ Increment to add to the internal counter of iterations
1216
+ [default: 1]. If using float, consider specifying `{n:.3f}`
1217
+ or similar in `bar_format`, or specifying `unit_scale`.
1218
+
1219
+ Returns
1220
+ -------
1221
+ out : bool or None
1222
+ True if a `display()` was triggered.
1223
+ """
1224
+ if self.disable:
1225
+ return
1226
+
1227
+ if n < 0:
1228
+ self.last_print_n += n # for auto-refresh logic to work
1229
+ self.n += n
1230
+
1231
+ # check counter first to reduce calls to time()
1232
+ if self.n - self.last_print_n >= self.miniters:
1233
+ cur_t = self._time()
1234
+ dt = cur_t - self.last_print_t
1235
+ if dt >= self.mininterval and cur_t >= self.start_t + self.delay:
1236
+ cur_t = self._time()
1237
+ dn = self.n - self.last_print_n # >= n
1238
+ if self.smoothing and dt and dn:
1239
+ # EMA (not just overall average)
1240
+ self._ema_dn(dn)
1241
+ self._ema_dt(dt)
1242
+ self.refresh(lock_args=self.lock_args)
1243
+ if self.dynamic_miniters:
1244
+ # If no `miniters` was specified, adjust automatically to the
1245
+ # maximum iteration rate seen so far between two prints.
1246
+ # e.g.: After running `tqdm.update(5)`, subsequent
1247
+ # calls to `tqdm.update()` will only cause an update after
1248
+ # at least 5 more iterations.
1249
+ if self.maxinterval and dt >= self.maxinterval:
1250
+ self.miniters = dn * (self.mininterval or self.maxinterval) / dt
1251
+ elif self.smoothing:
1252
+ # EMA miniters update
1253
+ self.miniters = self._ema_miniters(
1254
+ dn * (self.mininterval / dt if self.mininterval and dt
1255
+ else 1))
1256
+ else:
1257
+ # max iters between two prints
1258
+ self.miniters = max(self.miniters, dn)
1259
+
1260
+ # Store old values for next call
1261
+ self.last_print_n = self.n
1262
+ self.last_print_t = cur_t
1263
+ return True
1264
+
1265
+ def close(self):
1266
+ """Cleanup and (if leave=False) close the progressbar."""
1267
+ if self.disable:
1268
+ return
1269
+
1270
+ # Prevent multiple closures
1271
+ self.disable = True
1272
+
1273
+ # decrement instance pos and remove from internal set
1274
+ pos = abs(self.pos)
1275
+ self._decr_instances(self)
1276
+
1277
+ if self.last_print_t < self.start_t + self.delay:
1278
+ # haven't ever displayed; nothing to clear
1279
+ return
1280
+
1281
+ # GUI mode
1282
+ if getattr(self, 'sp', None) is None:
1283
+ return
1284
+
1285
+ # annoyingly, _supports_unicode isn't good enough
1286
+ def fp_write(s):
1287
+ self.fp.write(str(s))
1288
+
1289
+ try:
1290
+ fp_write('')
1291
+ except ValueError as e:
1292
+ if 'closed' in str(e):
1293
+ return
1294
+ raise # pragma: no cover
1295
+
1296
+ leave = pos == 0 if self.leave is None else self.leave
1297
+
1298
+ with self._lock:
1299
+ if leave:
1300
+ # stats for overall rate (no weighted average)
1301
+ self._ema_dt = lambda: None
1302
+ self.display(pos=0)
1303
+ fp_write('\n')
1304
+ else:
1305
+ # clear previous display
1306
+ if self.display(msg='', pos=pos) and not pos:
1307
+ fp_write('\r')
1308
+
1309
+ def clear(self, nolock=False):
1310
+ """Clear current bar display."""
1311
+ if self.disable:
1312
+ return
1313
+
1314
+ if not nolock:
1315
+ self._lock.acquire()
1316
+ pos = abs(self.pos)
1317
+ if pos < (self.nrows or 20):
1318
+ self.moveto(pos)
1319
+ self.sp('')
1320
+ self.fp.write('\r') # place cursor back at the beginning of line
1321
+ self.moveto(-pos)
1322
+ if not nolock:
1323
+ self._lock.release()
1324
+
1325
+ def refresh(self, nolock=False, lock_args=None):
1326
+ """
1327
+ Force refresh the display of this bar.
1328
+
1329
+ Parameters
1330
+ ----------
1331
+ nolock : bool, optional
1332
+ If `True`, does not lock.
1333
+ If [default: `False`]: calls `acquire()` on internal lock.
1334
+ lock_args : tuple, optional
1335
+ Passed to internal lock's `acquire()`.
1336
+ If specified, will only `display()` if `acquire()` returns `True`.
1337
+ """
1338
+ if self.disable:
1339
+ return
1340
+
1341
+ if not nolock:
1342
+ if lock_args:
1343
+ if not self._lock.acquire(*lock_args):
1344
+ return False
1345
+ else:
1346
+ self._lock.acquire()
1347
+ self.display()
1348
+ if not nolock:
1349
+ self._lock.release()
1350
+ return True
1351
+
1352
+ def unpause(self):
1353
+ """Restart tqdm timer from last print time."""
1354
+ if self.disable:
1355
+ return
1356
+ cur_t = self._time()
1357
+ self.start_t += cur_t - self.last_print_t
1358
+ self.last_print_t = cur_t
1359
+
1360
+ def reset(self, total=None):
1361
+ """
1362
+ Resets to 0 iterations for repeated use.
1363
+
1364
+ Consider combining with `leave=True`.
1365
+
1366
+ Parameters
1367
+ ----------
1368
+ total : int or float, optional. Total to use for the new bar.
1369
+ """
1370
+ self.n = 0
1371
+ if total is not None:
1372
+ self.total = total
1373
+ if self.disable:
1374
+ return
1375
+ self.last_print_n = 0
1376
+ self.last_print_t = self.start_t = self._time()
1377
+ self._ema_dn = EMA(self.smoothing)
1378
+ self._ema_dt = EMA(self.smoothing)
1379
+ self._ema_miniters = EMA(self.smoothing)
1380
+ self.refresh()
1381
+
1382
+ def set_description(self, desc=None, refresh=True):
1383
+ """
1384
+ Set/modify description of the progress bar.
1385
+
1386
+ Parameters
1387
+ ----------
1388
+ desc : str, optional
1389
+ refresh : bool, optional
1390
+ Forces refresh [default: True].
1391
+ """
1392
+ self.desc = desc + ': ' if desc else ''
1393
+ if refresh:
1394
+ self.refresh()
1395
+
1396
+ def set_description_str(self, desc=None, refresh=True):
1397
+ """Set/modify description without ': ' appended."""
1398
+ self.desc = desc or ''
1399
+ if refresh:
1400
+ self.refresh()
1401
+
1402
+ def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
1403
+ """
1404
+ Set/modify postfix (additional stats)
1405
+ with automatic formatting based on datatype.
1406
+
1407
+ Parameters
1408
+ ----------
1409
+ ordered_dict : dict or OrderedDict, optional
1410
+ refresh : bool, optional
1411
+ Forces refresh [default: True].
1412
+ kwargs : dict, optional
1413
+ """
1414
+ # Sort in alphabetical order to be more deterministic
1415
+ postfix = OrderedDict([] if ordered_dict is None else ordered_dict)
1416
+ for key in sorted(kwargs.keys()):
1417
+ postfix[key] = kwargs[key]
1418
+ # Preprocess stats according to datatype
1419
+ for key in postfix.keys():
1420
+ # Number: limit the length of the string
1421
+ if isinstance(postfix[key], Number):
1422
+ postfix[key] = self.format_num(postfix[key])
1423
+ # Else for any other type, try to get the string conversion
1424
+ elif not isinstance(postfix[key], str):
1425
+ postfix[key] = str(postfix[key])
1426
+ # Else if it's a string, don't need to preprocess anything
1427
+ # Stitch together to get the final postfix
1428
+ self.postfix = ', '.join(key + '=' + postfix[key].strip()
1429
+ for key in postfix.keys())
1430
+ if refresh:
1431
+ self.refresh()
1432
+
1433
+ def set_postfix_str(self, s='', refresh=True):
1434
+ """
1435
+ Postfix without dictionary expansion, similar to prefix handling.
1436
+ """
1437
+ self.postfix = str(s)
1438
+ if refresh:
1439
+ self.refresh()
1440
+
1441
+ def moveto(self, n):
1442
+ # TODO: private method
1443
+ self.fp.write('\n' * n + _term_move_up() * -n)
1444
+ getattr(self.fp, 'flush', lambda: None)()
1445
+
1446
+ @property
1447
+ def format_dict(self):
1448
+ """Public API for read-only member access."""
1449
+ if self.disable and not hasattr(self, 'unit'):
1450
+ return defaultdict(lambda: None, {
1451
+ 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'})
1452
+ if self.dynamic_ncols:
1453
+ self.ncols, self.nrows = self.dynamic_ncols(self.fp)
1454
+ return {
1455
+ 'n': self.n, 'total': self.total,
1456
+ 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0,
1457
+ 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc,
1458
+ 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale,
1459
+ 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None,
1460
+ 'bar_format': self.bar_format, 'postfix': self.postfix,
1461
+ 'unit_divisor': self.unit_divisor, 'initial': self.initial,
1462
+ 'colour': self.colour}
1463
+
1464
+ def display(self, msg=None, pos=None):
1465
+ """
1466
+ Use `self.sp` to display `msg` in the specified `pos`.
1467
+
1468
+ Consider overloading this function when inheriting to use e.g.:
1469
+ `self.some_frontend(**self.format_dict)` instead of `self.sp`.
1470
+
1471
+ Parameters
1472
+ ----------
1473
+ msg : str, optional. What to display (default: `repr(self)`).
1474
+ pos : int, optional. Position to `moveto`
1475
+ (default: `abs(self.pos)`).
1476
+ """
1477
+ if pos is None:
1478
+ pos = abs(self.pos)
1479
+
1480
+ nrows = self.nrows or 20
1481
+ if pos >= nrows - 1:
1482
+ if pos >= nrows:
1483
+ return False
1484
+ if msg or msg is None: # override at `nrows - 1`
1485
+ msg = " ... (more hidden) ..."
1486
+
1487
+ if not hasattr(self, "sp"):
1488
+ raise TqdmDeprecationWarning(
1489
+ "Please use `tqdm.gui.tqdm(...)`"
1490
+ " instead of `tqdm(..., gui=True)`\n",
1491
+ fp_write=getattr(self.fp, 'write', sys.stderr.write))
1492
+
1493
+ if pos:
1494
+ self.moveto(pos)
1495
+ self.sp(self.__str__() if msg is None else msg)
1496
+ if pos:
1497
+ self.moveto(-pos)
1498
+ return True
1499
+
1500
+ @classmethod
1501
+ @contextmanager
1502
+ def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
1503
+ """
1504
+ stream : file-like object.
1505
+ method : str, "read" or "write". The result of `read()` and
1506
+ the first argument of `write()` should have a `len()`.
1507
+
1508
+ >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
1509
+ ... while True:
1510
+ ... chunk = fobj.read(chunk_size)
1511
+ ... if not chunk:
1512
+ ... break
1513
+ """
1514
+ with cls(total=total, **tqdm_kwargs) as t:
1515
+ if bytes:
1516
+ t.unit = "B"
1517
+ t.unit_scale = True
1518
+ t.unit_divisor = 1024
1519
+ yield CallbackIOWrapper(t.update, stream, method)
1520
+
1521
+
1522
+ def trange(*args, **kwargs):
1523
+ """Shortcut for tqdm(range(*args), **kwargs)."""
1524
+ return tqdm(range(*args), **kwargs)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/tk.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tkinter GUI progressbar decorator for iterators.
3
+
4
+ Usage:
5
+ >>> from tqdm.tk import trange, tqdm
6
+ >>> for i in trange(10):
7
+ ... ...
8
+ """
9
+ import re
10
+ import sys
11
+ import tkinter
12
+ import tkinter.ttk as ttk
13
+ from warnings import warn
14
+
15
+ from .std import TqdmExperimentalWarning, TqdmWarning
16
+ from .std import tqdm as std_tqdm
17
+
18
+ __author__ = {"github.com/": ["richardsheridan", "casperdcl"]}
19
+ __all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange']
20
+
21
+
22
+ class tqdm_tk(std_tqdm): # pragma: no cover
23
+ """
24
+ Experimental Tkinter GUI version of tqdm!
25
+
26
+ Note: Window interactivity suffers if `tqdm_tk` is not running within
27
+ a Tkinter mainloop and values are generated infrequently. In this case,
28
+ consider calling `tqdm_tk.refresh()` frequently in the Tk thread.
29
+ """
30
+
31
+ # TODO: @classmethod: write()?
32
+
33
+ def __init__(self, *args, **kwargs):
34
+ """
35
+ This class accepts the following parameters *in addition* to
36
+ the parameters accepted by `tqdm`.
37
+
38
+ Parameters
39
+ ----------
40
+ grab : bool, optional
41
+ Grab the input across all windows of the process.
42
+ tk_parent : `tkinter.Wm`, optional
43
+ Parent Tk window.
44
+ cancel_callback : Callable, optional
45
+ Create a cancel button and set `cancel_callback` to be called
46
+ when the cancel or window close button is clicked.
47
+ """
48
+ kwargs = kwargs.copy()
49
+ kwargs['gui'] = True
50
+ # convert disable = None to False
51
+ kwargs['disable'] = bool(kwargs.get('disable', False))
52
+ self._warn_leave = 'leave' in kwargs
53
+ grab = kwargs.pop('grab', False)
54
+ tk_parent = kwargs.pop('tk_parent', None)
55
+ self._cancel_callback = kwargs.pop('cancel_callback', None)
56
+ super().__init__(*args, **kwargs)
57
+
58
+ if self.disable:
59
+ return
60
+
61
+ if tk_parent is None: # Discover parent widget
62
+ try:
63
+ tk_parent = tkinter._default_root
64
+ except AttributeError:
65
+ raise AttributeError(
66
+ "`tk_parent` required when using `tkinter.NoDefaultRoot()`")
67
+ if tk_parent is None: # use new default root window as display
68
+ self._tk_window = tkinter.Tk()
69
+ else: # some other windows already exist
70
+ self._tk_window = tkinter.Toplevel()
71
+ else:
72
+ self._tk_window = tkinter.Toplevel(tk_parent)
73
+
74
+ warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
75
+ self._tk_dispatching = self._tk_dispatching_helper()
76
+
77
+ self._tk_window.protocol("WM_DELETE_WINDOW", self.cancel)
78
+ self._tk_window.wm_title(self.desc)
79
+ self._tk_window.wm_attributes("-topmost", 1)
80
+ self._tk_window.after(0, lambda: self._tk_window.wm_attributes("-topmost", 0))
81
+ self._tk_n_var = tkinter.DoubleVar(self._tk_window, value=0)
82
+ self._tk_text_var = tkinter.StringVar(self._tk_window)
83
+ pbar_frame = ttk.Frame(self._tk_window, padding=5)
84
+ pbar_frame.pack()
85
+ _tk_label = ttk.Label(pbar_frame, textvariable=self._tk_text_var,
86
+ wraplength=600, anchor="center", justify="center")
87
+ _tk_label.pack()
88
+ self._tk_pbar = ttk.Progressbar(
89
+ pbar_frame, variable=self._tk_n_var, length=450)
90
+ if self.total is not None:
91
+ self._tk_pbar.configure(maximum=self.total)
92
+ else:
93
+ self._tk_pbar.configure(mode="indeterminate")
94
+ self._tk_pbar.pack()
95
+ if self._cancel_callback is not None:
96
+ _tk_button = ttk.Button(pbar_frame, text="Cancel", command=self.cancel)
97
+ _tk_button.pack()
98
+ if grab:
99
+ self._tk_window.grab_set()
100
+
101
+ def close(self):
102
+ if self.disable:
103
+ return
104
+
105
+ self.disable = True
106
+
107
+ with self.get_lock():
108
+ self._instances.remove(self)
109
+
110
+ def _close():
111
+ self._tk_window.after('idle', self._tk_window.destroy)
112
+ if not self._tk_dispatching:
113
+ self._tk_window.update()
114
+
115
+ self._tk_window.protocol("WM_DELETE_WINDOW", _close)
116
+
117
+ # if leave is set but we are self-dispatching, the left window is
118
+ # totally unresponsive unless the user manually dispatches
119
+ if not self.leave:
120
+ _close()
121
+ elif not self._tk_dispatching:
122
+ if self._warn_leave:
123
+ warn("leave flag ignored if not in tkinter mainloop",
124
+ TqdmWarning, stacklevel=2)
125
+ _close()
126
+
127
+ def clear(self, *_, **__):
128
+ pass
129
+
130
+ def display(self, *_, **__):
131
+ self._tk_n_var.set(self.n)
132
+ d = self.format_dict
133
+ # remove {bar}
134
+ d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
135
+ "{bar}", "<bar/>")
136
+ msg = self.format_meter(**d)
137
+ if '<bar/>' in msg:
138
+ msg = "".join(re.split(r'\|?<bar/>\|?', msg, maxsplit=1))
139
+ self._tk_text_var.set(msg)
140
+ if not self._tk_dispatching:
141
+ self._tk_window.update()
142
+
143
+ def set_description(self, desc=None, refresh=True):
144
+ self.set_description_str(desc, refresh)
145
+
146
+ def set_description_str(self, desc=None, refresh=True):
147
+ self.desc = desc
148
+ if not self.disable:
149
+ self._tk_window.wm_title(desc)
150
+ if refresh and not self._tk_dispatching:
151
+ self._tk_window.update()
152
+
153
+ def cancel(self):
154
+ """
155
+ `cancel_callback()` followed by `close()`
156
+ when close/cancel buttons clicked.
157
+ """
158
+ if self._cancel_callback is not None:
159
+ self._cancel_callback()
160
+ self.close()
161
+
162
+ def reset(self, total=None):
163
+ """
164
+ Resets to 0 iterations for repeated use.
165
+
166
+ Parameters
167
+ ----------
168
+ total : int or float, optional. Total to use for the new bar.
169
+ """
170
+ if hasattr(self, '_tk_pbar'):
171
+ if total is None:
172
+ self._tk_pbar.configure(maximum=100, mode="indeterminate")
173
+ else:
174
+ self._tk_pbar.configure(maximum=total, mode="determinate")
175
+ super().reset(total=total)
176
+
177
+ @staticmethod
178
+ def _tk_dispatching_helper():
179
+ """determine if Tkinter mainloop is dispatching events"""
180
+ codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
181
+ for frame in sys._current_frames().values():
182
+ while frame:
183
+ if frame.f_code in codes:
184
+ return True
185
+ frame = frame.f_back
186
+ return False
187
+
188
+
189
+ def ttkrange(*args, **kwargs):
190
+ """Shortcut for `tqdm.tk.tqdm(range(*args), **kwargs)`."""
191
+ return tqdm_tk(range(*args), **kwargs)
192
+
193
+
194
+ # Aliases
195
+ tqdm = tqdm_tk
196
+ trange = ttkrange
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/tqdm.1 ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .\" Automatically generated by Pandoc 1.19.2
2
+ .\"
3
+ .TH "TQDM" "1" "2015\-2021" "tqdm User Manuals" ""
4
+ .hy
5
+ .SH NAME
6
+ .PP
7
+ tqdm \- fast, extensible progress bar for Python and CLI
8
+ .SH SYNOPSIS
9
+ .PP
10
+ tqdm [\f[I]options\f[]]
11
+ .SH DESCRIPTION
12
+ .PP
13
+ See <https://github.com/tqdm/tqdm>.
14
+ Can be used as a pipe:
15
+ .IP
16
+ .nf
17
+ \f[C]
18
+ $\ #\ count\ lines\ of\ code
19
+ $\ cat\ *.py\ |\ tqdm\ |\ wc\ \-l
20
+ 327it\ [00:00,\ 981773.38it/s]
21
+ 327
22
+
23
+ $\ #\ find\ all\ files
24
+ $\ find\ .\ \-name\ "*.py"\ |\ tqdm\ |\ wc\ \-l
25
+ 432it\ [00:00,\ 833842.30it/s]
26
+ 432
27
+
28
+ #\ ...\ and\ more\ info
29
+ $\ find\ .\ \-name\ \[aq]*.py\[aq]\ \-exec\ wc\ \-l\ \\{}\ \\;\ \\
30
+ \ \ |\ tqdm\ \-\-total\ 432\ \-\-unit\ files\ \-\-desc\ counting\ \\
31
+ \ \ |\ awk\ \[aq]{\ sum\ +=\ $1\ };\ END\ {\ print\ sum\ }\[aq]
32
+ counting:\ 100%|█████████|\ 432/432\ [00:00<00:00,\ 794361.83files/s]
33
+ 131998
34
+ \f[]
35
+ .fi
36
+ .SH OPTIONS
37
+ .TP
38
+ .B \-h, \-\-help
39
+ Print this help and exit.
40
+ .RS
41
+ .RE
42
+ .TP
43
+ .B \-v, \-\-version
44
+ Print version and exit.
45
+ .RS
46
+ .RE
47
+ .TP
48
+ .B \-\-desc=\f[I]desc\f[]
49
+ str, optional.
50
+ Prefix for the progressbar.
51
+ .RS
52
+ .RE
53
+ .TP
54
+ .B \-\-total=\f[I]total\f[]
55
+ int or float, optional.
56
+ The number of expected iterations.
57
+ If unspecified, len(iterable) is used if possible.
58
+ If float("inf") or as a last resort, only basic progress statistics are
59
+ displayed (no ETA, no progressbar).
60
+ If \f[C]gui\f[] is True and this parameter needs subsequent updating,
61
+ specify an initial arbitrary large positive number, e.g.
62
+ 9e9.
63
+ .RS
64
+ .RE
65
+ .TP
66
+ .B \-\-leave
67
+ bool, optional.
68
+ If [default: True], keeps all traces of the progressbar upon termination
69
+ of iteration.
70
+ If \f[C]None\f[], will leave only if \f[C]position\f[] is \f[C]0\f[].
71
+ .RS
72
+ .RE
73
+ .TP
74
+ .B \-\-ncols=\f[I]ncols\f[]
75
+ int, optional.
76
+ The width of the entire output message.
77
+ If specified, dynamically resizes the progressbar to stay within this
78
+ bound.
79
+ If unspecified, attempts to use environment width.
80
+ The fallback is a meter width of 10 and no limit for the counter and
81
+ statistics.
82
+ If 0, will not print any meter (only stats).
83
+ .RS
84
+ .RE
85
+ .TP
86
+ .B \-\-mininterval=\f[I]mininterval\f[]
87
+ float, optional.
88
+ Minimum progress display update interval [default: 0.1] seconds.
89
+ .RS
90
+ .RE
91
+ .TP
92
+ .B \-\-maxinterval=\f[I]maxinterval\f[]
93
+ float, optional.
94
+ Maximum progress display update interval [default: 10] seconds.
95
+ Automatically adjusts \f[C]miniters\f[] to correspond to
96
+ \f[C]mininterval\f[] after long display update lag.
97
+ Only works if \f[C]dynamic_miniters\f[] or monitor thread is enabled.
98
+ .RS
99
+ .RE
100
+ .TP
101
+ .B \-\-miniters=\f[I]miniters\f[]
102
+ int or float, optional.
103
+ Minimum progress display update interval, in iterations.
104
+ If 0 and \f[C]dynamic_miniters\f[], will automatically adjust to equal
105
+ \f[C]mininterval\f[] (more CPU efficient, good for tight loops).
106
+ If > 0, will skip display of specified number of iterations.
107
+ Tweak this and \f[C]mininterval\f[] to get very efficient loops.
108
+ If your progress is erratic with both fast and slow iterations (network,
109
+ skipping items, etc) you should set miniters=1.
110
+ .RS
111
+ .RE
112
+ .TP
113
+ .B \-\-ascii=\f[I]ascii\f[]
114
+ bool or str, optional.
115
+ If unspecified or False, use unicode (smooth blocks) to fill the meter.
116
+ The fallback is to use ASCII characters " 123456789#".
117
+ .RS
118
+ .RE
119
+ .TP
120
+ .B \-\-disable
121
+ bool, optional.
122
+ Whether to disable the entire progressbar wrapper [default: False].
123
+ If set to None, disable on non\-TTY.
124
+ .RS
125
+ .RE
126
+ .TP
127
+ .B \-\-unit=\f[I]unit\f[]
128
+ str, optional.
129
+ String that will be used to define the unit of each iteration [default:
130
+ it].
131
+ .RS
132
+ .RE
133
+ .TP
134
+ .B \-\-unit\-scale=\f[I]unit_scale\f[]
135
+ bool or int or float, optional.
136
+ If 1 or True, the number of iterations will be reduced/scaled
137
+ automatically and a metric prefix following the International System of
138
+ Units standard will be added (kilo, mega, etc.) [default: False].
139
+ If any other non\-zero number, will scale \f[C]total\f[] and \f[C]n\f[].
140
+ .RS
141
+ .RE
142
+ .TP
143
+ .B \-\-dynamic\-ncols
144
+ bool, optional.
145
+ If set, constantly alters \f[C]ncols\f[] and \f[C]nrows\f[] to the
146
+ environment (allowing for window resizes) [default: False].
147
+ .RS
148
+ .RE
149
+ .TP
150
+ .B \-\-smoothing=\f[I]smoothing\f[]
151
+ float, optional.
152
+ Exponential moving average smoothing factor for speed estimates (ignored
153
+ in GUI mode).
154
+ Ranges from 0 (average speed) to 1 (current/instantaneous speed)
155
+ [default: 0.3].
156
+ .RS
157
+ .RE
158
+ .TP
159
+ .B \-\-bar\-format=\f[I]bar_format\f[]
160
+ str, optional.
161
+ Specify a custom bar string formatting.
162
+ May impact performance.
163
+ [default: \[aq]{l_bar}{bar}{r_bar}\[aq]], where l_bar=\[aq]{desc}:
164
+ {percentage:3.0f}%|\[aq] and r_bar=\[aq]| {n_fmt}/{total_fmt}
165
+ [{elapsed}<{remaining}, \[aq] \[aq]{rate_fmt}{postfix}]\[aq] Possible
166
+ vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage,
167
+ elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt,
168
+ rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix,
169
+ unit_divisor, remaining, remaining_s, eta.
170
+ Note that a trailing ": " is automatically removed after {desc} if the
171
+ latter is empty.
172
+ .RS
173
+ .RE
174
+ .TP
175
+ .B \-\-initial=\f[I]initial\f[]
176
+ int or float, optional.
177
+ The initial counter value.
178
+ Useful when restarting a progress bar [default: 0].
179
+ If using float, consider specifying \f[C]{n:.3f}\f[] or similar in
180
+ \f[C]bar_format\f[], or specifying \f[C]unit_scale\f[].
181
+ .RS
182
+ .RE
183
+ .TP
184
+ .B \-\-position=\f[I]position\f[]
185
+ int, optional.
186
+ Specify the line offset to print this bar (starting from 0) Automatic if
187
+ unspecified.
188
+ Useful to manage multiple bars at once (eg, from threads).
189
+ .RS
190
+ .RE
191
+ .TP
192
+ .B \-\-postfix=\f[I]postfix\f[]
193
+ dict or *, optional.
194
+ Specify additional stats to display at the end of the bar.
195
+ Calls \f[C]set_postfix(**postfix)\f[] if possible (dict).
196
+ .RS
197
+ .RE
198
+ .TP
199
+ .B \-\-unit\-divisor=\f[I]unit_divisor\f[]
200
+ float, optional.
201
+ [default: 1000], ignored unless \f[C]unit_scale\f[] is True.
202
+ .RS
203
+ .RE
204
+ .TP
205
+ .B \-\-write\-bytes
206
+ bool, optional.
207
+ Whether to write bytes.
208
+ If (default: False) will write unicode.
209
+ .RS
210
+ .RE
211
+ .TP
212
+ .B \-\-lock\-args=\f[I]lock_args\f[]
213
+ tuple, optional.
214
+ Passed to \f[C]refresh\f[] for intermediate output (initialisation,
215
+ iterating, and updating).
216
+ .RS
217
+ .RE
218
+ .TP
219
+ .B \-\-nrows=\f[I]nrows\f[]
220
+ int, optional.
221
+ The screen height.
222
+ If specified, hides nested bars outside this bound.
223
+ If unspecified, attempts to use environment height.
224
+ The fallback is 20.
225
+ .RS
226
+ .RE
227
+ .TP
228
+ .B \-\-colour=\f[I]colour\f[]
229
+ str, optional.
230
+ Bar colour (e.g.
231
+ \[aq]green\[aq], \[aq]#00ff00\[aq]).
232
+ .RS
233
+ .RE
234
+ .TP
235
+ .B \-\-delay=\f[I]delay\f[]
236
+ float, optional.
237
+ Don\[aq]t display until [default: 0] seconds have elapsed.
238
+ .RS
239
+ .RE
240
+ .TP
241
+ .B \-\-delim=\f[I]delim\f[]
242
+ chr, optional.
243
+ Delimiting character [default: \[aq]\\n\[aq]].
244
+ Use \[aq]\\0\[aq] for null.
245
+ N.B.: on Windows systems, Python converts \[aq]\\n\[aq] to
246
+ \[aq]\\r\\n\[aq].
247
+ .RS
248
+ .RE
249
+ .TP
250
+ .B \-\-buf\-size=\f[I]buf_size\f[]
251
+ int, optional.
252
+ String buffer size in bytes [default: 256] used when \f[C]delim\f[] is
253
+ specified.
254
+ .RS
255
+ .RE
256
+ .TP
257
+ .B \-\-bytes
258
+ bool, optional.
259
+ If true, will count bytes, ignore \f[C]delim\f[], and default
260
+ \f[C]unit_scale\f[] to True, \f[C]unit_divisor\f[] to 1024, and
261
+ \f[C]unit\f[] to \[aq]B\[aq].
262
+ .RS
263
+ .RE
264
+ .TP
265
+ .B \-\-tee
266
+ bool, optional.
267
+ If true, passes \f[C]stdin\f[] to both \f[C]stderr\f[] and
268
+ \f[C]stdout\f[].
269
+ .RS
270
+ .RE
271
+ .TP
272
+ .B \-\-update
273
+ bool, optional.
274
+ If true, will treat input as newly elapsed iterations, i.e.
275
+ numbers to pass to \f[C]update()\f[].
276
+ Note that this is slow (~2e5 it/s) since every input must be decoded as
277
+ a number.
278
+ .RS
279
+ .RE
280
+ .TP
281
+ .B \-\-update\-to
282
+ bool, optional.
283
+ If true, will treat input as total elapsed iterations, i.e.
284
+ numbers to assign to \f[C]self.n\f[].
285
+ Note that this is slow (~2e5 it/s) since every input must be decoded as
286
+ a number.
287
+ .RS
288
+ .RE
289
+ .TP
290
+ .B \-\-null
291
+ bool, optional.
292
+ If true, will discard input (no stdout).
293
+ .RS
294
+ .RE
295
+ .TP
296
+ .B \-\-manpath=\f[I]manpath\f[]
297
+ str, optional.
298
+ Directory in which to install tqdm man pages.
299
+ .RS
300
+ .RE
301
+ .TP
302
+ .B \-\-comppath=\f[I]comppath\f[]
303
+ str, optional.
304
+ Directory in which to place tqdm completion.
305
+ .RS
306
+ .RE
307
+ .TP
308
+ .B \-\-log=\f[I]log\f[]
309
+ str, optional.
310
+ CRITICAL|FATAL|ERROR|WARN(ING)|[default: \[aq]INFO\[aq]]|DEBUG|NOTSET.
311
+ .RS
312
+ .RE
313
+ .SH AUTHORS
314
+ tqdm developers <https://github.com/tqdm>.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/utils.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ General helpers required for `tqdm.std`.
3
+ """
4
+ import os
5
+ import re
6
+ import sys
7
+ from functools import partial, partialmethod, wraps
8
+ from inspect import signature
9
+ # TODO consider using wcswidth third-party package for 0-width characters
10
+ from unicodedata import east_asian_width
11
+ from warnings import warn
12
+ from weakref import proxy
13
+
14
+ _range, _unich, _unicode, _basestring = range, chr, str, str
15
+ CUR_OS = sys.platform
16
+ IS_WIN = any(CUR_OS.startswith(i) for i in ['win32', 'cygwin'])
17
+ IS_NIX = any(CUR_OS.startswith(i) for i in ['aix', 'linux', 'darwin', 'freebsd'])
18
+ RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]")
19
+
20
+ try:
21
+ if IS_WIN:
22
+ import colorama
23
+ else:
24
+ raise ImportError
25
+ except ImportError:
26
+ colorama = None
27
+ else:
28
+ try:
29
+ colorama.init(strip=False)
30
+ except TypeError:
31
+ colorama.init()
32
+
33
+
34
+ def envwrap(prefix, types=None, is_method=False):
35
+ """
36
+ Override parameter defaults via `os.environ[prefix + param_name]`.
37
+ Maps UPPER_CASE env vars map to lower_case param names.
38
+ camelCase isn't supported (because Windows ignores case).
39
+
40
+ Precedence (highest first):
41
+
42
+ - call (`foo(a=3)`)
43
+ - environ (`FOO_A=2`)
44
+ - signature (`def foo(a=1)`)
45
+
46
+ Parameters
47
+ ----------
48
+ prefix : str
49
+ Env var prefix, e.g. "FOO_"
50
+ types : dict, optional
51
+ Fallback mappings `{'param_name': type, ...}` if types cannot be
52
+ inferred from function signature.
53
+ Consider using `types=collections.defaultdict(lambda: ast.literal_eval)`.
54
+ is_method : bool, optional
55
+ Whether to use `functools.partialmethod`. If (default: False) use `functools.partial`.
56
+
57
+ Examples
58
+ --------
59
+ ```
60
+ $ cat foo.py
61
+ from tqdm.utils import envwrap
62
+ @envwrap("FOO_")
63
+ def test(a=1, b=2, c=3):
64
+ print(f"received: a={a}, b={b}, c={c}")
65
+
66
+ $ FOO_A=42 FOO_C=1337 python -c 'import foo; foo.test(c=99)'
67
+ received: a=42, b=2, c=99
68
+ ```
69
+ """
70
+ if types is None:
71
+ types = {}
72
+ i = len(prefix)
73
+ env_overrides = {k[i:].lower(): v for k, v in os.environ.items() if k.startswith(prefix)}
74
+ part = partialmethod if is_method else partial
75
+
76
+ def wrap(func):
77
+ params = signature(func).parameters
78
+ # ignore unknown env vars
79
+ overrides = {k: v for k, v in env_overrides.items() if k in params}
80
+ # infer overrides' `type`s
81
+ for k in overrides:
82
+ param = params[k]
83
+ if param.annotation is not param.empty: # typehints
84
+ for typ in getattr(param.annotation, '__args__', (param.annotation,)):
85
+ try:
86
+ overrides[k] = typ(overrides[k])
87
+ except Exception:
88
+ pass
89
+ else:
90
+ break
91
+ elif param.default is not None: # type of default value
92
+ overrides[k] = type(param.default)(overrides[k])
93
+ else:
94
+ try: # `types` fallback
95
+ overrides[k] = types[k](overrides[k])
96
+ except KeyError: # keep unconverted (`str`)
97
+ pass
98
+ return part(func, **overrides)
99
+ return wrap
100
+
101
+
102
+ class FormatReplace(object):
103
+ """
104
+ >>> a = FormatReplace('something')
105
+ >>> f"{a:5d}"
106
+ 'something'
107
+ """ # NOQA: P102
108
+ def __init__(self, replace=''):
109
+ self.replace = replace
110
+ self.format_called = 0
111
+
112
+ def __format__(self, _):
113
+ self.format_called += 1
114
+ return self.replace
115
+
116
+
117
+ class Comparable(object):
118
+ """Assumes child has self._comparable attr/@property"""
119
+ def __lt__(self, other):
120
+ return self._comparable < other._comparable
121
+
122
+ def __le__(self, other):
123
+ return (self < other) or (self == other)
124
+
125
+ def __eq__(self, other):
126
+ return self._comparable == other._comparable
127
+
128
+ def __ne__(self, other):
129
+ return not self == other
130
+
131
+ def __gt__(self, other):
132
+ return not self <= other
133
+
134
+ def __ge__(self, other):
135
+ return not self < other
136
+
137
+
138
+ class ObjectWrapper(object):
139
+ def __getattr__(self, name):
140
+ return getattr(self._wrapped, name)
141
+
142
+ def __setattr__(self, name, value):
143
+ return setattr(self._wrapped, name, value)
144
+
145
+ def wrapper_getattr(self, name):
146
+ """Actual `self.getattr` rather than self._wrapped.getattr"""
147
+ try:
148
+ return object.__getattr__(self, name)
149
+ except AttributeError: # py2
150
+ return getattr(self, name)
151
+
152
+ def wrapper_setattr(self, name, value):
153
+ """Actual `self.setattr` rather than self._wrapped.setattr"""
154
+ return object.__setattr__(self, name, value)
155
+
156
+ def __init__(self, wrapped):
157
+ """
158
+ Thin wrapper around a given object
159
+ """
160
+ self.wrapper_setattr('_wrapped', wrapped)
161
+
162
+
163
+ class SimpleTextIOWrapper(ObjectWrapper):
164
+ """
165
+ Change only `.write()` of the wrapped object by encoding the passed
166
+ value and passing the result to the wrapped object's `.write()` method.
167
+ """
168
+ # pylint: disable=too-few-public-methods
169
+ def __init__(self, wrapped, encoding):
170
+ super().__init__(wrapped)
171
+ self.wrapper_setattr('encoding', encoding)
172
+
173
+ def write(self, s):
174
+ """
175
+ Encode `s` and pass to the wrapped object's `.write()` method.
176
+ """
177
+ return self._wrapped.write(s.encode(self.wrapper_getattr('encoding')))
178
+
179
+ def __eq__(self, other):
180
+ return self._wrapped == getattr(other, '_wrapped', other)
181
+
182
+
183
+ class DisableOnWriteError(ObjectWrapper):
184
+ """
185
+ Disable the given `tqdm_instance` upon `write()` or `flush()` errors.
186
+ """
187
+ @staticmethod
188
+ def disable_on_exception(tqdm_instance, func):
189
+ """
190
+ Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`.
191
+ """
192
+ tqdm_instance = proxy(tqdm_instance)
193
+
194
+ def inner(*args, **kwargs):
195
+ try:
196
+ return func(*args, **kwargs)
197
+ except OSError as e:
198
+ if e.errno != 5:
199
+ raise
200
+ try:
201
+ tqdm_instance.miniters = float('inf')
202
+ except ReferenceError:
203
+ pass
204
+ except ValueError as e:
205
+ if 'closed' not in str(e):
206
+ raise
207
+ try:
208
+ tqdm_instance.miniters = float('inf')
209
+ except ReferenceError:
210
+ pass
211
+ return inner
212
+
213
+ def __init__(self, wrapped, tqdm_instance):
214
+ super().__init__(wrapped)
215
+ if hasattr(wrapped, 'write'):
216
+ self.wrapper_setattr(
217
+ 'write', self.disable_on_exception(tqdm_instance, wrapped.write))
218
+ if hasattr(wrapped, 'flush'):
219
+ self.wrapper_setattr(
220
+ 'flush', self.disable_on_exception(tqdm_instance, wrapped.flush))
221
+
222
+ def __eq__(self, other):
223
+ return self._wrapped == getattr(other, '_wrapped', other)
224
+
225
+
226
+ class CallbackIOWrapper(ObjectWrapper):
227
+ def __init__(self, callback, stream, method="read"):
228
+ """
229
+ Wrap a given `file`-like object's `read()` or `write()` to report
230
+ lengths to the given `callback`
231
+ """
232
+ super().__init__(stream)
233
+ func = getattr(stream, method)
234
+ if method == "write":
235
+ @wraps(func)
236
+ def write(data, *args, **kwargs):
237
+ res = func(data, *args, **kwargs)
238
+ callback(len(data))
239
+ return res
240
+ self.wrapper_setattr('write', write)
241
+ elif method == "read":
242
+ @wraps(func)
243
+ def read(*args, **kwargs):
244
+ data = func(*args, **kwargs)
245
+ callback(len(data))
246
+ return data
247
+ self.wrapper_setattr('read', read)
248
+ else:
249
+ raise KeyError("Can only wrap read/write methods")
250
+
251
+
252
+ def _is_utf(encoding):
253
+ try:
254
+ u'\u2588\u2589'.encode(encoding)
255
+ except UnicodeEncodeError:
256
+ return False
257
+ except Exception:
258
+ try:
259
+ return encoding.lower().startswith('utf-') or ('U8' == encoding)
260
+ except Exception:
261
+ return False
262
+ else:
263
+ return True
264
+
265
+
266
+ def _supports_unicode(fp):
267
+ try:
268
+ return _is_utf(fp.encoding)
269
+ except AttributeError:
270
+ return False
271
+
272
+
273
+ def _is_ascii(s):
274
+ if isinstance(s, str):
275
+ for c in s:
276
+ if ord(c) > 255:
277
+ return False
278
+ return True
279
+ return _supports_unicode(s)
280
+
281
+
282
+ def _screen_shape_wrapper(): # pragma: no cover
283
+ """
284
+ Return a function which returns console dimensions (width, height).
285
+ Supported: linux, osx, windows, cygwin.
286
+ """
287
+ _screen_shape = None
288
+ if IS_WIN:
289
+ _screen_shape = _screen_shape_windows
290
+ if _screen_shape is None:
291
+ _screen_shape = _screen_shape_tput
292
+ if IS_NIX:
293
+ _screen_shape = _screen_shape_linux
294
+ return _screen_shape
295
+
296
+
297
+ def _screen_shape_windows(fp): # pragma: no cover
298
+ try:
299
+ import struct
300
+ from ctypes import create_string_buffer, windll
301
+ from sys import stdin, stdout
302
+
303
+ io_handle = -12 # assume stderr
304
+ if fp == stdin:
305
+ io_handle = -10
306
+ elif fp == stdout:
307
+ io_handle = -11
308
+
309
+ h = windll.kernel32.GetStdHandle(io_handle)
310
+ csbi = create_string_buffer(22)
311
+ res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
312
+ if res:
313
+ (_bufx, _bufy, _curx, _cury, _wattr, left, top, right, bottom,
314
+ _maxx, _maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
315
+ return right - left, bottom - top # +1
316
+ except Exception: # nosec
317
+ pass
318
+ return None, None
319
+
320
+
321
+ def _screen_shape_tput(*_): # pragma: no cover
322
+ """cygwin xterm (windows)"""
323
+ try:
324
+ import shlex
325
+ from subprocess import check_call # nosec
326
+ return [int(check_call(shlex.split('tput ' + i))) - 1
327
+ for i in ('cols', 'lines')]
328
+ except Exception: # nosec
329
+ pass
330
+ return None, None
331
+
332
+
333
+ def _screen_shape_linux(fp): # pragma: no cover
334
+
335
+ try:
336
+ from array import array
337
+ from fcntl import ioctl
338
+ from termios import TIOCGWINSZ
339
+ except ImportError:
340
+ return None, None
341
+ else:
342
+ try:
343
+ rows, cols = array('h', ioctl(fp, TIOCGWINSZ, '\0' * 8))[:2]
344
+ return cols, rows
345
+ except Exception:
346
+ try:
347
+ return [int(os.environ[i]) - 1 for i in ("COLUMNS", "LINES")]
348
+ except (KeyError, ValueError):
349
+ return None, None
350
+
351
+
352
+ def _environ_cols_wrapper(): # pragma: no cover
353
+ """
354
+ Return a function which returns console width.
355
+ Supported: linux, osx, windows, cygwin.
356
+ """
357
+ warn("Use `_screen_shape_wrapper()(file)[0]` instead of"
358
+ " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2)
359
+ shape = _screen_shape_wrapper()
360
+ if not shape:
361
+ return None
362
+
363
+ @wraps(shape)
364
+ def inner(fp):
365
+ return shape(fp)[0]
366
+
367
+ return inner
368
+
369
+
370
+ def _term_move_up(): # pragma: no cover
371
+ return '' if (os.name == 'nt') and (colorama is None) else '\x1b[A'
372
+
373
+
374
+ def _text_width(s):
375
+ return sum(2 if east_asian_width(ch) in 'FW' else 1 for ch in str(s))
376
+
377
+
378
+ def disp_len(data):
379
+ """
380
+ Returns the real on-screen length of a string which may contain
381
+ ANSI control codes and wide chars.
382
+ """
383
+ return _text_width(RE_ANSI.sub('', data))
384
+
385
+
386
+ def disp_trim(data, length):
387
+ """
388
+ Trim a string which may contain ANSI control characters.
389
+ """
390
+ if len(data) == disp_len(data):
391
+ return data[:length]
392
+
393
+ ansi_present = bool(RE_ANSI.search(data))
394
+ while disp_len(data) > length: # carefully delete one char at a time
395
+ data = data[:-1]
396
+ if ansi_present and bool(RE_ANSI.search(data)):
397
+ # assume ANSI reset is required
398
+ return data if data.endswith("\033[0m") else data + "\033[0m"
399
+ return data
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/tqdm/version.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """`tqdm` version detector. Precedence: installed dist, git, 'UNKNOWN'."""
2
+ try:
3
+ from ._dist_ver import __version__
4
+ except ImportError:
5
+ try:
6
+ from setuptools_scm import get_version
7
+ __version__ = get_version(root='..', relative_to=__file__)
8
+ except (ImportError, LookupError):
9
+ __version__ = "UNKNOWN"
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/__init__.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ # When adding a new object to this init, remember to add it twice: once inside the `_import_structure` dictionary and
16
+ # once inside the `if TYPE_CHECKING` branch. The `TYPE_CHECKING` should have import statements as usual, but they are
17
+ # only there for type checking. The `_import_structure` is a dictionary submodule to list of object names, and is used
18
+ # to defer the actual importing for when the objects are requested. This way `import transformers` provides the names
19
+ # in the namespace without actually importing anything (and especially none of the backends).
20
+
21
+ __version__ = "4.56.2"
22
+
23
+ from pathlib import Path
24
+ from typing import TYPE_CHECKING
25
+
26
+ # Check the dependencies satisfy the minimal versions required.
27
+ from . import dependency_versions_check
28
+ from .utils import (
29
+ OptionalDependencyNotAvailable,
30
+ _LazyModule,
31
+ is_essentia_available,
32
+ is_g2p_en_available,
33
+ is_librosa_available,
34
+ is_mistral_common_available,
35
+ is_pretty_midi_available,
36
+ )
37
+
38
+ # Note: the following symbols are deliberately exported with `as`
39
+ # so that mypy, pylint or other static linters can recognize them,
40
+ # given that they are not exported using `__all__` in this file.
41
+ from .utils import is_bitsandbytes_available as is_bitsandbytes_available
42
+ from .utils import is_flax_available as is_flax_available
43
+ from .utils import is_keras_nlp_available as is_keras_nlp_available
44
+ from .utils import is_scipy_available as is_scipy_available
45
+ from .utils import is_sentencepiece_available as is_sentencepiece_available
46
+ from .utils import is_speech_available as is_speech_available
47
+ from .utils import is_tensorflow_text_available as is_tensorflow_text_available
48
+ from .utils import is_tf_available as is_tf_available
49
+ from .utils import is_timm_available as is_timm_available
50
+ from .utils import is_tokenizers_available as is_tokenizers_available
51
+ from .utils import is_torch_available as is_torch_available
52
+ from .utils import is_torchaudio_available as is_torchaudio_available
53
+ from .utils import is_torchvision_available as is_torchvision_available
54
+ from .utils import is_vision_available as is_vision_available
55
+ from .utils import logging as logging
56
+ from .utils.import_utils import define_import_structure
57
+
58
+
59
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
60
+
61
+ # Base objects, independent of any specific backend
62
+ _import_structure = {
63
+ "audio_utils": [],
64
+ "commands": [],
65
+ "configuration_utils": ["PretrainedConfig"],
66
+ "convert_graph_to_onnx": [],
67
+ "convert_slow_tokenizers_checkpoints_to_fast": [],
68
+ "convert_tf_hub_seq_to_seq_bert_to_pytorch": [],
69
+ "data": [
70
+ "DataProcessor",
71
+ "InputExample",
72
+ "InputFeatures",
73
+ "SingleSentenceClassificationProcessor",
74
+ "SquadExample",
75
+ "SquadFeatures",
76
+ "SquadV1Processor",
77
+ "SquadV2Processor",
78
+ "glue_compute_metrics",
79
+ "glue_convert_examples_to_features",
80
+ "glue_output_modes",
81
+ "glue_processors",
82
+ "glue_tasks_num_labels",
83
+ "squad_convert_examples_to_features",
84
+ "xnli_compute_metrics",
85
+ "xnli_output_modes",
86
+ "xnli_processors",
87
+ "xnli_tasks_num_labels",
88
+ ],
89
+ "data.data_collator": [
90
+ "DataCollator",
91
+ "DataCollatorForLanguageModeling",
92
+ "DataCollatorForMultipleChoice",
93
+ "DataCollatorForPermutationLanguageModeling",
94
+ "DataCollatorForSeq2Seq",
95
+ "DataCollatorForSOP",
96
+ "DataCollatorForTokenClassification",
97
+ "DataCollatorForWholeWordMask",
98
+ "DataCollatorWithFlattening",
99
+ "DataCollatorWithPadding",
100
+ "DefaultDataCollator",
101
+ "default_data_collator",
102
+ ],
103
+ "data.metrics": [],
104
+ "data.processors": [],
105
+ "debug_utils": [],
106
+ "dependency_versions_check": [],
107
+ "dependency_versions_table": [],
108
+ "dynamic_module_utils": [],
109
+ "feature_extraction_sequence_utils": ["SequenceFeatureExtractor"],
110
+ "feature_extraction_utils": ["BatchFeature", "FeatureExtractionMixin"],
111
+ "file_utils": [],
112
+ "generation": [
113
+ "AsyncTextIteratorStreamer",
114
+ "CompileConfig",
115
+ "GenerationConfig",
116
+ "TextIteratorStreamer",
117
+ "TextStreamer",
118
+ "WatermarkingConfig",
119
+ ],
120
+ "hf_argparser": ["HfArgumentParser"],
121
+ "hyperparameter_search": [],
122
+ "image_transforms": [],
123
+ "integrations": [
124
+ "is_clearml_available",
125
+ "is_comet_available",
126
+ "is_dvclive_available",
127
+ "is_neptune_available",
128
+ "is_optuna_available",
129
+ "is_ray_available",
130
+ "is_ray_tune_available",
131
+ "is_sigopt_available",
132
+ "is_swanlab_available",
133
+ "is_tensorboard_available",
134
+ "is_trackio_available",
135
+ "is_wandb_available",
136
+ ],
137
+ "loss": [],
138
+ "modelcard": ["ModelCard"],
139
+ # Losses
140
+ "modeling_tf_pytorch_utils": [
141
+ "convert_tf_weight_name_to_pt_weight_name",
142
+ "load_pytorch_checkpoint_in_tf2_model",
143
+ "load_pytorch_model_in_tf2_model",
144
+ "load_pytorch_weights_in_tf2_model",
145
+ "load_tf2_checkpoint_in_pytorch_model",
146
+ "load_tf2_model_in_pytorch_model",
147
+ "load_tf2_weights_in_pytorch_model",
148
+ ],
149
+ # Models
150
+ "onnx": [],
151
+ "pipelines": [
152
+ "AudioClassificationPipeline",
153
+ "AutomaticSpeechRecognitionPipeline",
154
+ "CsvPipelineDataFormat",
155
+ "DepthEstimationPipeline",
156
+ "DocumentQuestionAnsweringPipeline",
157
+ "FeatureExtractionPipeline",
158
+ "FillMaskPipeline",
159
+ "ImageClassificationPipeline",
160
+ "ImageFeatureExtractionPipeline",
161
+ "ImageSegmentationPipeline",
162
+ "ImageTextToTextPipeline",
163
+ "ImageToImagePipeline",
164
+ "ImageToTextPipeline",
165
+ "JsonPipelineDataFormat",
166
+ "KeypointMatchingPipeline",
167
+ "MaskGenerationPipeline",
168
+ "NerPipeline",
169
+ "ObjectDetectionPipeline",
170
+ "PipedPipelineDataFormat",
171
+ "Pipeline",
172
+ "PipelineDataFormat",
173
+ "QuestionAnsweringPipeline",
174
+ "SummarizationPipeline",
175
+ "TableQuestionAnsweringPipeline",
176
+ "Text2TextGenerationPipeline",
177
+ "TextClassificationPipeline",
178
+ "TextGenerationPipeline",
179
+ "TextToAudioPipeline",
180
+ "TokenClassificationPipeline",
181
+ "TranslationPipeline",
182
+ "VideoClassificationPipeline",
183
+ "VisualQuestionAnsweringPipeline",
184
+ "ZeroShotAudioClassificationPipeline",
185
+ "ZeroShotClassificationPipeline",
186
+ "ZeroShotImageClassificationPipeline",
187
+ "ZeroShotObjectDetectionPipeline",
188
+ "pipeline",
189
+ ],
190
+ "processing_utils": ["ProcessorMixin"],
191
+ "quantizers": [],
192
+ "testing_utils": [],
193
+ "tokenization_utils": ["PreTrainedTokenizer"],
194
+ "tokenization_utils_base": [
195
+ "AddedToken",
196
+ "BatchEncoding",
197
+ "CharSpan",
198
+ "PreTrainedTokenizerBase",
199
+ "SpecialTokensMixin",
200
+ "TokenSpan",
201
+ ],
202
+ "trainer_callback": [
203
+ "DefaultFlowCallback",
204
+ "EarlyStoppingCallback",
205
+ "PrinterCallback",
206
+ "ProgressCallback",
207
+ "TrainerCallback",
208
+ "TrainerControl",
209
+ "TrainerState",
210
+ ],
211
+ "trainer_utils": [
212
+ "EvalPrediction",
213
+ "IntervalStrategy",
214
+ "SchedulerType",
215
+ "enable_full_determinism",
216
+ "set_seed",
217
+ ],
218
+ "training_args": ["TrainingArguments"],
219
+ "training_args_seq2seq": ["Seq2SeqTrainingArguments"],
220
+ "training_args_tf": ["TFTrainingArguments"],
221
+ "utils": [
222
+ "CONFIG_NAME",
223
+ "MODEL_CARD_NAME",
224
+ "PYTORCH_PRETRAINED_BERT_CACHE",
225
+ "PYTORCH_TRANSFORMERS_CACHE",
226
+ "SPIECE_UNDERLINE",
227
+ "TF2_WEIGHTS_NAME",
228
+ "TF_WEIGHTS_NAME",
229
+ "TRANSFORMERS_CACHE",
230
+ "WEIGHTS_NAME",
231
+ "TensorType",
232
+ "add_end_docstrings",
233
+ "add_start_docstrings",
234
+ "is_apex_available",
235
+ "is_av_available",
236
+ "is_bitsandbytes_available",
237
+ "is_datasets_available",
238
+ "is_faiss_available",
239
+ "is_flax_available",
240
+ "is_keras_nlp_available",
241
+ "is_matplotlib_available",
242
+ "is_phonemizer_available",
243
+ "is_psutil_available",
244
+ "is_py3nvml_available",
245
+ "is_pyctcdecode_available",
246
+ "is_sacremoses_available",
247
+ "is_safetensors_available",
248
+ "is_scipy_available",
249
+ "is_sentencepiece_available",
250
+ "is_sklearn_available",
251
+ "is_speech_available",
252
+ "is_tensorflow_text_available",
253
+ "is_tf_available",
254
+ "is_timm_available",
255
+ "is_tokenizers_available",
256
+ "is_torch_available",
257
+ "is_torch_hpu_available",
258
+ "is_torch_mlu_available",
259
+ "is_torch_musa_available",
260
+ "is_torch_neuroncore_available",
261
+ "is_torch_npu_available",
262
+ "is_torchvision_available",
263
+ "is_torch_xla_available",
264
+ "is_torch_xpu_available",
265
+ "is_vision_available",
266
+ "logging",
267
+ ],
268
+ "utils.quantization_config": [
269
+ "AqlmConfig",
270
+ "AutoRoundConfig",
271
+ "AwqConfig",
272
+ "BitNetQuantConfig",
273
+ "BitsAndBytesConfig",
274
+ "CompressedTensorsConfig",
275
+ "EetqConfig",
276
+ "FbgemmFp8Config",
277
+ "FineGrainedFP8Config",
278
+ "GPTQConfig",
279
+ "HiggsConfig",
280
+ "HqqConfig",
281
+ "Mxfp4Config",
282
+ "QuantoConfig",
283
+ "QuarkConfig",
284
+ "FPQuantConfig",
285
+ "SpQRConfig",
286
+ "TorchAoConfig",
287
+ "VptqConfig",
288
+ ],
289
+ "video_utils": [],
290
+ }
291
+
292
+ # tokenizers-backed objects
293
+ try:
294
+ if not is_tokenizers_available():
295
+ raise OptionalDependencyNotAvailable()
296
+ except OptionalDependencyNotAvailable:
297
+ from .utils import dummy_tokenizers_objects
298
+
299
+ _import_structure["utils.dummy_tokenizers_objects"] = [
300
+ name for name in dir(dummy_tokenizers_objects) if not name.startswith("_")
301
+ ]
302
+ else:
303
+ # Fast tokenizers structure
304
+ _import_structure["tokenization_utils_fast"] = ["PreTrainedTokenizerFast"]
305
+
306
+
307
+ try:
308
+ if not (is_sentencepiece_available() and is_tokenizers_available()):
309
+ raise OptionalDependencyNotAvailable()
310
+ except OptionalDependencyNotAvailable:
311
+ from .utils import dummy_sentencepiece_and_tokenizers_objects
312
+
313
+ _import_structure["utils.dummy_sentencepiece_and_tokenizers_objects"] = [
314
+ name for name in dir(dummy_sentencepiece_and_tokenizers_objects) if not name.startswith("_")
315
+ ]
316
+ else:
317
+ _import_structure["convert_slow_tokenizer"] = [
318
+ "SLOW_TO_FAST_CONVERTERS",
319
+ "convert_slow_tokenizer",
320
+ ]
321
+
322
+ try:
323
+ if not (is_mistral_common_available()):
324
+ raise OptionalDependencyNotAvailable()
325
+ except OptionalDependencyNotAvailable:
326
+ from .utils import dummy_mistral_common_objects
327
+
328
+ _import_structure["utils.dummy_mistral_common_objects"] = [
329
+ name for name in dir(dummy_mistral_common_objects) if not name.startswith("_")
330
+ ]
331
+ else:
332
+ _import_structure["tokenization_mistral_common"] = ["MistralCommonTokenizer"]
333
+
334
+ # Vision-specific objects
335
+ try:
336
+ if not is_vision_available():
337
+ raise OptionalDependencyNotAvailable()
338
+ except OptionalDependencyNotAvailable:
339
+ from .utils import dummy_vision_objects
340
+
341
+ _import_structure["utils.dummy_vision_objects"] = [
342
+ name for name in dir(dummy_vision_objects) if not name.startswith("_")
343
+ ]
344
+ else:
345
+ _import_structure["image_processing_base"] = ["ImageProcessingMixin"]
346
+ _import_structure["image_processing_utils"] = ["BaseImageProcessor"]
347
+ _import_structure["image_utils"] = ["ImageFeatureExtractionMixin"]
348
+
349
+ try:
350
+ if not is_torchvision_available():
351
+ raise OptionalDependencyNotAvailable()
352
+ except OptionalDependencyNotAvailable:
353
+ from .utils import dummy_torchvision_objects
354
+
355
+ _import_structure["utils.dummy_torchvision_objects"] = [
356
+ name for name in dir(dummy_torchvision_objects) if not name.startswith("_")
357
+ ]
358
+ else:
359
+ _import_structure["image_processing_utils_fast"] = ["BaseImageProcessorFast"]
360
+ _import_structure["video_processing_utils"] = ["BaseVideoProcessor"]
361
+
362
+ # PyTorch-backed objects
363
+ try:
364
+ if not is_torch_available():
365
+ raise OptionalDependencyNotAvailable()
366
+ except OptionalDependencyNotAvailable:
367
+ from .utils import dummy_pt_objects
368
+
369
+ _import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")]
370
+ else:
371
+ _import_structure["model_debugging_utils"] = [
372
+ "model_addition_debugger_context",
373
+ ]
374
+ _import_structure["activations"] = []
375
+ _import_structure["cache_utils"] = [
376
+ "CacheLayerMixin",
377
+ "DynamicLayer",
378
+ "StaticLayer",
379
+ "SlidingWindowLayer",
380
+ "ChunkedSlidingLayer",
381
+ "QuantoQuantizedLayer",
382
+ "HQQQuantizedLayer",
383
+ "Cache",
384
+ "DynamicCache",
385
+ "EncoderDecoderCache",
386
+ "HQQQuantizedCache",
387
+ "HybridCache",
388
+ "HybridChunkedCache",
389
+ "OffloadedCache",
390
+ "OffloadedStaticCache",
391
+ "QuantizedCache",
392
+ "QuantoQuantizedCache",
393
+ "SinkCache",
394
+ "SlidingWindowCache",
395
+ "StaticCache",
396
+ ]
397
+ _import_structure["data.datasets"] = [
398
+ "GlueDataset",
399
+ "GlueDataTrainingArguments",
400
+ "LineByLineTextDataset",
401
+ "LineByLineWithRefDataset",
402
+ "LineByLineWithSOPTextDataset",
403
+ "SquadDataset",
404
+ "SquadDataTrainingArguments",
405
+ "TextDataset",
406
+ "TextDatasetForNextSentencePrediction",
407
+ ]
408
+ _import_structure["generation"].extend(
409
+ [
410
+ "AlternatingCodebooksLogitsProcessor",
411
+ "BayesianDetectorConfig",
412
+ "BayesianDetectorModel",
413
+ "BeamScorer",
414
+ "BeamSearchScorer",
415
+ "ClassifierFreeGuidanceLogitsProcessor",
416
+ "ConstrainedBeamSearchScorer",
417
+ "Constraint",
418
+ "ConstraintListState",
419
+ "DisjunctiveConstraint",
420
+ "EncoderNoRepeatNGramLogitsProcessor",
421
+ "EncoderRepetitionPenaltyLogitsProcessor",
422
+ "EosTokenCriteria",
423
+ "EpsilonLogitsWarper",
424
+ "EtaLogitsWarper",
425
+ "ExponentialDecayLengthPenalty",
426
+ "ForcedBOSTokenLogitsProcessor",
427
+ "ForcedEOSTokenLogitsProcessor",
428
+ "GenerationMixin",
429
+ "HammingDiversityLogitsProcessor",
430
+ "InfNanRemoveLogitsProcessor",
431
+ "LogitNormalization",
432
+ "LogitsProcessor",
433
+ "LogitsProcessorList",
434
+ "MaxLengthCriteria",
435
+ "MaxTimeCriteria",
436
+ "MinLengthLogitsProcessor",
437
+ "MinNewTokensLengthLogitsProcessor",
438
+ "MinPLogitsWarper",
439
+ "NoBadWordsLogitsProcessor",
440
+ "NoRepeatNGramLogitsProcessor",
441
+ "PhrasalConstraint",
442
+ "PrefixConstrainedLogitsProcessor",
443
+ "RepetitionPenaltyLogitsProcessor",
444
+ "SequenceBiasLogitsProcessor",
445
+ "StoppingCriteria",
446
+ "StoppingCriteriaList",
447
+ "StopStringCriteria",
448
+ "SuppressTokensAtBeginLogitsProcessor",
449
+ "SuppressTokensLogitsProcessor",
450
+ "SynthIDTextWatermarkDetector",
451
+ "SynthIDTextWatermarkingConfig",
452
+ "SynthIDTextWatermarkLogitsProcessor",
453
+ "TemperatureLogitsWarper",
454
+ "TopKLogitsWarper",
455
+ "TopPLogitsWarper",
456
+ "TypicalLogitsWarper",
457
+ "UnbatchedClassifierFreeGuidanceLogitsProcessor",
458
+ "WatermarkDetector",
459
+ "WatermarkLogitsProcessor",
460
+ "WhisperTimeStampLogitsProcessor",
461
+ ]
462
+ )
463
+
464
+ # PyTorch domain libraries integration
465
+ _import_structure["integrations.executorch"] = [
466
+ "TorchExportableModuleWithStaticCache",
467
+ "convert_and_export_with_cache",
468
+ ]
469
+
470
+ _import_structure["modeling_flash_attention_utils"] = []
471
+ _import_structure["modeling_layers"] = ["GradientCheckpointingLayer"]
472
+ _import_structure["modeling_outputs"] = []
473
+ _import_structure["modeling_rope_utils"] = ["ROPE_INIT_FUNCTIONS", "dynamic_rope_update"]
474
+ _import_structure["modeling_utils"] = ["PreTrainedModel", "AttentionInterface"]
475
+ _import_structure["masking_utils"] = ["AttentionMaskInterface"]
476
+ _import_structure["optimization"] = [
477
+ "Adafactor",
478
+ "get_constant_schedule",
479
+ "get_constant_schedule_with_warmup",
480
+ "get_cosine_schedule_with_warmup",
481
+ "get_cosine_with_hard_restarts_schedule_with_warmup",
482
+ "get_inverse_sqrt_schedule",
483
+ "get_linear_schedule_with_warmup",
484
+ "get_polynomial_decay_schedule_with_warmup",
485
+ "get_scheduler",
486
+ "get_wsd_schedule",
487
+ ]
488
+ _import_structure["pytorch_utils"] = [
489
+ "Conv1D",
490
+ "apply_chunking_to_forward",
491
+ "prune_layer",
492
+ "infer_device",
493
+ ]
494
+ _import_structure["sagemaker"] = []
495
+ _import_structure["time_series_utils"] = []
496
+ _import_structure["trainer"] = ["Trainer"]
497
+ _import_structure["trainer_pt_utils"] = ["torch_distributed_zero_first"]
498
+ _import_structure["trainer_seq2seq"] = ["Seq2SeqTrainer"]
499
+
500
+ # TensorFlow-backed objects
501
+ try:
502
+ if not is_tf_available():
503
+ raise OptionalDependencyNotAvailable()
504
+ except OptionalDependencyNotAvailable:
505
+ from .utils import dummy_tf_objects
506
+
507
+ _import_structure["utils.dummy_tf_objects"] = [name for name in dir(dummy_tf_objects) if not name.startswith("_")]
508
+ else:
509
+ _import_structure["activations_tf"] = []
510
+ _import_structure["generation"].extend(
511
+ [
512
+ "TFForcedBOSTokenLogitsProcessor",
513
+ "TFForcedEOSTokenLogitsProcessor",
514
+ "TFForceTokensLogitsProcessor",
515
+ "TFGenerationMixin",
516
+ "TFLogitsProcessor",
517
+ "TFLogitsProcessorList",
518
+ "TFLogitsWarper",
519
+ "TFMinLengthLogitsProcessor",
520
+ "TFNoBadWordsLogitsProcessor",
521
+ "TFNoRepeatNGramLogitsProcessor",
522
+ "TFRepetitionPenaltyLogitsProcessor",
523
+ "TFSuppressTokensAtBeginLogitsProcessor",
524
+ "TFSuppressTokensLogitsProcessor",
525
+ "TFTemperatureLogitsWarper",
526
+ "TFTopKLogitsWarper",
527
+ "TFTopPLogitsWarper",
528
+ ]
529
+ )
530
+ _import_structure["keras_callbacks"] = ["KerasMetricCallback", "PushToHubCallback"]
531
+ _import_structure["modeling_tf_outputs"] = []
532
+ _import_structure["modeling_tf_utils"] = [
533
+ "TFPreTrainedModel",
534
+ "TFSequenceSummary",
535
+ "TFSharedEmbeddings",
536
+ "shape_list",
537
+ ]
538
+ _import_structure["optimization_tf"] = [
539
+ "AdamWeightDecay",
540
+ "GradientAccumulator",
541
+ "WarmUp",
542
+ "create_optimizer",
543
+ ]
544
+ _import_structure["tf_utils"] = []
545
+
546
+
547
+ # FLAX-backed objects
548
+ try:
549
+ if not is_flax_available():
550
+ raise OptionalDependencyNotAvailable()
551
+ except OptionalDependencyNotAvailable:
552
+ from .utils import dummy_flax_objects
553
+
554
+ _import_structure["utils.dummy_flax_objects"] = [
555
+ name for name in dir(dummy_flax_objects) if not name.startswith("_")
556
+ ]
557
+ else:
558
+ _import_structure["generation"].extend(
559
+ [
560
+ "FlaxForcedBOSTokenLogitsProcessor",
561
+ "FlaxForcedEOSTokenLogitsProcessor",
562
+ "FlaxForceTokensLogitsProcessor",
563
+ "FlaxGenerationMixin",
564
+ "FlaxLogitsProcessor",
565
+ "FlaxLogitsProcessorList",
566
+ "FlaxLogitsWarper",
567
+ "FlaxMinLengthLogitsProcessor",
568
+ "FlaxTemperatureLogitsWarper",
569
+ "FlaxSuppressTokensAtBeginLogitsProcessor",
570
+ "FlaxSuppressTokensLogitsProcessor",
571
+ "FlaxTopKLogitsWarper",
572
+ "FlaxTopPLogitsWarper",
573
+ "FlaxWhisperTimeStampLogitsProcessor",
574
+ ]
575
+ )
576
+ _import_structure["modeling_flax_outputs"] = []
577
+ _import_structure["modeling_flax_utils"] = ["FlaxPreTrainedModel"]
578
+
579
+ # Direct imports for type-checking
580
+ if TYPE_CHECKING:
581
+ # All modeling imports
582
+ from .cache_utils import Cache as Cache
583
+ from .cache_utils import ChunkedSlidingLayer as ChunkedSlidingLayer
584
+ from .cache_utils import DynamicCache as DynamicCache
585
+ from .cache_utils import DynamicLayer as DynamicLayer
586
+ from .cache_utils import EncoderDecoderCache as EncoderDecoderCache
587
+ from .cache_utils import HQQQuantizedCache as HQQQuantizedCache
588
+ from .cache_utils import HQQQuantizedLayer as HQQQuantizedLayer
589
+ from .cache_utils import HybridCache as HybridCache
590
+ from .cache_utils import MambaCache as MambaCache
591
+ from .cache_utils import OffloadedCache as OffloadedCache
592
+ from .cache_utils import OffloadedStaticCache as OffloadedStaticCache
593
+ from .cache_utils import QuantizedCache as QuantizedCache
594
+ from .cache_utils import QuantoQuantizedCache as QuantoQuantizedCache
595
+ from .cache_utils import QuantoQuantizedLayer as QuantoQuantizedLayer
596
+ from .cache_utils import SinkCache as SinkCache
597
+ from .cache_utils import SlidingWindowCache as SlidingWindowCache
598
+ from .cache_utils import SlidingWindowLayer as SlidingWindowLayer
599
+ from .cache_utils import StaticCache as StaticCache
600
+ from .cache_utils import StaticLayer as StaticLayer
601
+ from .configuration_utils import PretrainedConfig as PretrainedConfig
602
+ from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS as SLOW_TO_FAST_CONVERTERS
603
+ from .convert_slow_tokenizer import convert_slow_tokenizer as convert_slow_tokenizer
604
+
605
+ # Data
606
+ from .data import DataProcessor as DataProcessor
607
+ from .data import InputExample as InputExample
608
+ from .data import InputFeatures as InputFeatures
609
+ from .data import SingleSentenceClassificationProcessor as SingleSentenceClassificationProcessor
610
+ from .data import SquadExample as SquadExample
611
+ from .data import SquadFeatures as SquadFeatures
612
+ from .data import SquadV1Processor as SquadV1Processor
613
+ from .data import SquadV2Processor as SquadV2Processor
614
+ from .data import glue_compute_metrics as glue_compute_metrics
615
+ from .data import glue_convert_examples_to_features as glue_convert_examples_to_features
616
+ from .data import glue_output_modes as glue_output_modes
617
+ from .data import glue_processors as glue_processors
618
+ from .data import glue_tasks_num_labels as glue_tasks_num_labels
619
+ from .data import squad_convert_examples_to_features as squad_convert_examples_to_features
620
+ from .data import xnli_compute_metrics as xnli_compute_metrics
621
+ from .data import xnli_output_modes as xnli_output_modes
622
+ from .data import xnli_processors as xnli_processors
623
+ from .data import xnli_tasks_num_labels as xnli_tasks_num_labels
624
+ from .data.data_collator import DataCollator as DataCollator
625
+ from .data.data_collator import DataCollatorForLanguageModeling as DataCollatorForLanguageModeling
626
+ from .data.data_collator import DataCollatorForMultipleChoice as DataCollatorForMultipleChoice
627
+ from .data.data_collator import (
628
+ DataCollatorForPermutationLanguageModeling as DataCollatorForPermutationLanguageModeling,
629
+ )
630
+ from .data.data_collator import DataCollatorForSeq2Seq as DataCollatorForSeq2Seq
631
+ from .data.data_collator import DataCollatorForSOP as DataCollatorForSOP
632
+ from .data.data_collator import DataCollatorForTokenClassification as DataCollatorForTokenClassification
633
+ from .data.data_collator import DataCollatorForWholeWordMask as DataCollatorForWholeWordMask
634
+ from .data.data_collator import DataCollatorWithFlattening as DataCollatorWithFlattening
635
+ from .data.data_collator import DataCollatorWithPadding as DataCollatorWithPadding
636
+ from .data.data_collator import DefaultDataCollator as DefaultDataCollator
637
+ from .data.data_collator import default_data_collator as default_data_collator
638
+ from .data.datasets import GlueDataset as GlueDataset
639
+ from .data.datasets import GlueDataTrainingArguments as GlueDataTrainingArguments
640
+ from .data.datasets import LineByLineTextDataset as LineByLineTextDataset
641
+ from .data.datasets import LineByLineWithRefDataset as LineByLineWithRefDataset
642
+ from .data.datasets import LineByLineWithSOPTextDataset as LineByLineWithSOPTextDataset
643
+ from .data.datasets import SquadDataset as SquadDataset
644
+ from .data.datasets import SquadDataTrainingArguments as SquadDataTrainingArguments
645
+ from .data.datasets import TextDataset as TextDataset
646
+ from .data.datasets import TextDatasetForNextSentencePrediction as TextDatasetForNextSentencePrediction
647
+ from .feature_extraction_sequence_utils import SequenceFeatureExtractor as SequenceFeatureExtractor
648
+
649
+ # Feature Extractor
650
+ from .feature_extraction_utils import BatchFeature as BatchFeature
651
+ from .feature_extraction_utils import FeatureExtractionMixin as FeatureExtractionMixin
652
+
653
+ # Generation
654
+ from .generation import AlternatingCodebooksLogitsProcessor as AlternatingCodebooksLogitsProcessor
655
+ from .generation import AsyncTextIteratorStreamer as AsyncTextIteratorStreamer
656
+ from .generation import BayesianDetectorConfig as BayesianDetectorConfig
657
+ from .generation import BayesianDetectorModel as BayesianDetectorModel
658
+ from .generation import BeamScorer as BeamScorer
659
+ from .generation import BeamSearchScorer as BeamSearchScorer
660
+ from .generation import ClassifierFreeGuidanceLogitsProcessor as ClassifierFreeGuidanceLogitsProcessor
661
+ from .generation import CompileConfig as CompileConfig
662
+ from .generation import ConstrainedBeamSearchScorer as ConstrainedBeamSearchScorer
663
+ from .generation import Constraint as Constraint
664
+ from .generation import ConstraintListState as ConstraintListState
665
+ from .generation import DisjunctiveConstraint as DisjunctiveConstraint
666
+ from .generation import EncoderNoRepeatNGramLogitsProcessor as EncoderNoRepeatNGramLogitsProcessor
667
+ from .generation import EncoderRepetitionPenaltyLogitsProcessor as EncoderRepetitionPenaltyLogitsProcessor
668
+ from .generation import EosTokenCriteria as EosTokenCriteria
669
+ from .generation import EpsilonLogitsWarper as EpsilonLogitsWarper
670
+ from .generation import EtaLogitsWarper as EtaLogitsWarper
671
+ from .generation import ExponentialDecayLengthPenalty as ExponentialDecayLengthPenalty
672
+ from .generation import FlaxForcedBOSTokenLogitsProcessor as FlaxForcedBOSTokenLogitsProcessor
673
+ from .generation import FlaxForcedEOSTokenLogitsProcessor as FlaxForcedEOSTokenLogitsProcessor
674
+ from .generation import FlaxForceTokensLogitsProcessor as FlaxForceTokensLogitsProcessor
675
+ from .generation import FlaxGenerationMixin as FlaxGenerationMixin
676
+ from .generation import FlaxLogitsProcessor as FlaxLogitsProcessor
677
+ from .generation import FlaxLogitsProcessorList as FlaxLogitsProcessorList
678
+ from .generation import FlaxLogitsWarper as FlaxLogitsWarper
679
+ from .generation import FlaxMinLengthLogitsProcessor as FlaxMinLengthLogitsProcessor
680
+ from .generation import FlaxSuppressTokensAtBeginLogitsProcessor as FlaxSuppressTokensAtBeginLogitsProcessor
681
+ from .generation import FlaxSuppressTokensLogitsProcessor as FlaxSuppressTokensLogitsProcessor
682
+ from .generation import FlaxTemperatureLogitsWarper as FlaxTemperatureLogitsWarper
683
+ from .generation import FlaxTopKLogitsWarper as FlaxTopKLogitsWarper
684
+ from .generation import FlaxTopPLogitsWarper as FlaxTopPLogitsWarper
685
+ from .generation import FlaxWhisperTimeStampLogitsProcessor as FlaxWhisperTimeStampLogitsProcessor
686
+ from .generation import ForcedBOSTokenLogitsProcessor as ForcedBOSTokenLogitsProcessor
687
+ from .generation import ForcedEOSTokenLogitsProcessor as ForcedEOSTokenLogitsProcessor
688
+ from .generation import GenerationConfig as GenerationConfig
689
+ from .generation import GenerationMixin as GenerationMixin
690
+ from .generation import HammingDiversityLogitsProcessor as HammingDiversityLogitsProcessor
691
+ from .generation import InfNanRemoveLogitsProcessor as InfNanRemoveLogitsProcessor
692
+ from .generation import LogitNormalization as LogitNormalization
693
+ from .generation import LogitsProcessor as LogitsProcessor
694
+ from .generation import LogitsProcessorList as LogitsProcessorList
695
+ from .generation import MaxLengthCriteria as MaxLengthCriteria
696
+ from .generation import MaxTimeCriteria as MaxTimeCriteria
697
+ from .generation import MinLengthLogitsProcessor as MinLengthLogitsProcessor
698
+ from .generation import MinNewTokensLengthLogitsProcessor as MinNewTokensLengthLogitsProcessor
699
+ from .generation import MinPLogitsWarper as MinPLogitsWarper
700
+ from .generation import NoBadWordsLogitsProcessor as NoBadWordsLogitsProcessor
701
+ from .generation import NoRepeatNGramLogitsProcessor as NoRepeatNGramLogitsProcessor
702
+ from .generation import PhrasalConstraint as PhrasalConstraint
703
+ from .generation import PrefixConstrainedLogitsProcessor as PrefixConstrainedLogitsProcessor
704
+ from .generation import RepetitionPenaltyLogitsProcessor as RepetitionPenaltyLogitsProcessor
705
+ from .generation import SequenceBiasLogitsProcessor as SequenceBiasLogitsProcessor
706
+ from .generation import StoppingCriteria as StoppingCriteria
707
+ from .generation import StoppingCriteriaList as StoppingCriteriaList
708
+ from .generation import StopStringCriteria as StopStringCriteria
709
+ from .generation import SuppressTokensAtBeginLogitsProcessor as SuppressTokensAtBeginLogitsProcessor
710
+ from .generation import SuppressTokensLogitsProcessor as SuppressTokensLogitsProcessor
711
+ from .generation import SynthIDTextWatermarkDetector as SynthIDTextWatermarkDetector
712
+ from .generation import SynthIDTextWatermarkingConfig as SynthIDTextWatermarkingConfig
713
+ from .generation import SynthIDTextWatermarkLogitsProcessor as SynthIDTextWatermarkLogitsProcessor
714
+ from .generation import TemperatureLogitsWarper as TemperatureLogitsWarper
715
+ from .generation import TextIteratorStreamer as TextIteratorStreamer
716
+ from .generation import TextStreamer as TextStreamer
717
+ from .generation import TFForcedBOSTokenLogitsProcessor as TFForcedBOSTokenLogitsProcessor
718
+ from .generation import TFForcedEOSTokenLogitsProcessor as TFForcedEOSTokenLogitsProcessor
719
+ from .generation import TFForceTokensLogitsProcessor as TFForceTokensLogitsProcessor
720
+ from .generation import TFGenerationMixin as TFGenerationMixin
721
+ from .generation import TFLogitsProcessor as TFLogitsProcessor
722
+ from .generation import TFLogitsProcessorList as TFLogitsProcessorList
723
+ from .generation import TFLogitsWarper as TFLogitsWarper
724
+ from .generation import TFMinLengthLogitsProcessor as TFMinLengthLogitsProcessor
725
+ from .generation import TFNoBadWordsLogitsProcessor as TFNoBadWordsLogitsProcessor
726
+ from .generation import TFNoRepeatNGramLogitsProcessor as TFNoRepeatNGramLogitsProcessor
727
+ from .generation import TFRepetitionPenaltyLogitsProcessor as TFRepetitionPenaltyLogitsProcessor
728
+ from .generation import TFSuppressTokensAtBeginLogitsProcessor as TFSuppressTokensAtBeginLogitsProcessor
729
+ from .generation import TFSuppressTokensLogitsProcessor as TFSuppressTokensLogitsProcessor
730
+ from .generation import TFTemperatureLogitsWarper as TFTemperatureLogitsWarper
731
+ from .generation import TFTopKLogitsWarper as TFTopKLogitsWarper
732
+ from .generation import TFTopPLogitsWarper as TFTopPLogitsWarper
733
+ from .generation import TopKLogitsWarper as TopKLogitsWarper
734
+ from .generation import TopPLogitsWarper as TopPLogitsWarper
735
+ from .generation import TypicalLogitsWarper as TypicalLogitsWarper
736
+ from .generation import (
737
+ UnbatchedClassifierFreeGuidanceLogitsProcessor as UnbatchedClassifierFreeGuidanceLogitsProcessor,
738
+ )
739
+ from .generation import WatermarkDetector as WatermarkDetector
740
+ from .generation import WatermarkingConfig as WatermarkingConfig
741
+ from .generation import WatermarkLogitsProcessor as WatermarkLogitsProcessor
742
+ from .generation import WhisperTimeStampLogitsProcessor as WhisperTimeStampLogitsProcessor
743
+ from .hf_argparser import HfArgumentParser as HfArgumentParser
744
+ from .image_processing_base import ImageProcessingMixin as ImageProcessingMixin
745
+ from .image_processing_utils import BaseImageProcessor as BaseImageProcessor
746
+ from .image_processing_utils_fast import BaseImageProcessorFast as BaseImageProcessorFast
747
+ from .image_utils import ImageFeatureExtractionMixin as ImageFeatureExtractionMixin
748
+
749
+ # Integrations
750
+ from .integrations import is_clearml_available as is_clearml_available
751
+ from .integrations import is_comet_available as is_comet_available
752
+ from .integrations import is_dvclive_available as is_dvclive_available
753
+ from .integrations import is_neptune_available as is_neptune_available
754
+ from .integrations import is_optuna_available as is_optuna_available
755
+ from .integrations import is_ray_available as is_ray_available
756
+ from .integrations import is_ray_tune_available as is_ray_tune_available
757
+ from .integrations import is_sigopt_available as is_sigopt_available
758
+ from .integrations import is_swanlab_available as is_swanlab_available
759
+ from .integrations import is_tensorboard_available as is_tensorboard_available
760
+ from .integrations import is_trackio_available as is_trackio_available
761
+ from .integrations import is_wandb_available as is_wandb_available
762
+ from .integrations.executorch import TorchExportableModuleWithStaticCache as TorchExportableModuleWithStaticCache
763
+ from .integrations.executorch import convert_and_export_with_cache as convert_and_export_with_cache
764
+ from .keras_callbacks import KerasMetricCallback as KerasMetricCallback
765
+ from .keras_callbacks import PushToHubCallback as PushToHubCallback
766
+ from .masking_utils import AttentionMaskInterface as AttentionMaskInterface
767
+ from .model_debugging_utils import model_addition_debugger_context as model_addition_debugger_context
768
+
769
+ # Model Cards
770
+ from .modelcard import ModelCard as ModelCard
771
+ from .modeling_flax_utils import FlaxPreTrainedModel as FlaxPreTrainedModel
772
+ from .modeling_layers import GradientCheckpointingLayer as GradientCheckpointingLayer
773
+ from .modeling_rope_utils import ROPE_INIT_FUNCTIONS as ROPE_INIT_FUNCTIONS
774
+ from .modeling_rope_utils import dynamic_rope_update as dynamic_rope_update
775
+
776
+ # TF 2.0 <=> PyTorch conversion utilities
777
+ from .modeling_tf_pytorch_utils import (
778
+ convert_tf_weight_name_to_pt_weight_name as convert_tf_weight_name_to_pt_weight_name,
779
+ )
780
+ from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model as load_pytorch_checkpoint_in_tf2_model
781
+ from .modeling_tf_pytorch_utils import load_pytorch_model_in_tf2_model as load_pytorch_model_in_tf2_model
782
+ from .modeling_tf_pytorch_utils import load_pytorch_weights_in_tf2_model as load_pytorch_weights_in_tf2_model
783
+ from .modeling_tf_pytorch_utils import load_tf2_checkpoint_in_pytorch_model as load_tf2_checkpoint_in_pytorch_model
784
+ from .modeling_tf_pytorch_utils import load_tf2_model_in_pytorch_model as load_tf2_model_in_pytorch_model
785
+ from .modeling_tf_pytorch_utils import load_tf2_weights_in_pytorch_model as load_tf2_weights_in_pytorch_model
786
+ from .modeling_tf_utils import TFPreTrainedModel as TFPreTrainedModel
787
+ from .modeling_tf_utils import TFSequenceSummary as TFSequenceSummary
788
+ from .modeling_tf_utils import TFSharedEmbeddings as TFSharedEmbeddings
789
+ from .modeling_tf_utils import shape_list as shape_list
790
+ from .modeling_utils import AttentionInterface as AttentionInterface
791
+ from .modeling_utils import PreTrainedModel as PreTrainedModel
792
+ from .models import *
793
+ from .models.timm_wrapper import TimmWrapperImageProcessor as TimmWrapperImageProcessor
794
+
795
+ # Optimization
796
+ from .optimization import Adafactor as Adafactor
797
+ from .optimization import get_constant_schedule as get_constant_schedule
798
+ from .optimization import get_constant_schedule_with_warmup as get_constant_schedule_with_warmup
799
+ from .optimization import get_cosine_schedule_with_warmup as get_cosine_schedule_with_warmup
800
+ from .optimization import (
801
+ get_cosine_with_hard_restarts_schedule_with_warmup as get_cosine_with_hard_restarts_schedule_with_warmup,
802
+ )
803
+ from .optimization import get_inverse_sqrt_schedule as get_inverse_sqrt_schedule
804
+ from .optimization import get_linear_schedule_with_warmup as get_linear_schedule_with_warmup
805
+ from .optimization import get_polynomial_decay_schedule_with_warmup as get_polynomial_decay_schedule_with_warmup
806
+ from .optimization import get_scheduler as get_scheduler
807
+ from .optimization import get_wsd_schedule as get_wsd_schedule
808
+
809
+ # Optimization
810
+ from .optimization_tf import AdamWeightDecay as AdamWeightDecay
811
+ from .optimization_tf import GradientAccumulator as GradientAccumulator
812
+ from .optimization_tf import WarmUp as WarmUp
813
+ from .optimization_tf import create_optimizer as create_optimizer
814
+
815
+ # Pipelines
816
+ from .pipelines import AudioClassificationPipeline as AudioClassificationPipeline
817
+ from .pipelines import AutomaticSpeechRecognitionPipeline as AutomaticSpeechRecognitionPipeline
818
+ from .pipelines import CsvPipelineDataFormat as CsvPipelineDataFormat
819
+ from .pipelines import DepthEstimationPipeline as DepthEstimationPipeline
820
+ from .pipelines import DocumentQuestionAnsweringPipeline as DocumentQuestionAnsweringPipeline
821
+ from .pipelines import FeatureExtractionPipeline as FeatureExtractionPipeline
822
+ from .pipelines import FillMaskPipeline as FillMaskPipeline
823
+ from .pipelines import ImageClassificationPipeline as ImageClassificationPipeline
824
+ from .pipelines import ImageFeatureExtractionPipeline as ImageFeatureExtractionPipeline
825
+ from .pipelines import ImageSegmentationPipeline as ImageSegmentationPipeline
826
+ from .pipelines import ImageTextToTextPipeline as ImageTextToTextPipeline
827
+ from .pipelines import ImageToImagePipeline as ImageToImagePipeline
828
+ from .pipelines import ImageToTextPipeline as ImageToTextPipeline
829
+ from .pipelines import JsonPipelineDataFormat as JsonPipelineDataFormat
830
+ from .pipelines import KeypointMatchingPipeline as KeypointMatchingPipeline
831
+ from .pipelines import MaskGenerationPipeline as MaskGenerationPipeline
832
+ from .pipelines import NerPipeline as NerPipeline
833
+ from .pipelines import ObjectDetectionPipeline as ObjectDetectionPipeline
834
+ from .pipelines import PipedPipelineDataFormat as PipedPipelineDataFormat
835
+ from .pipelines import Pipeline as Pipeline
836
+ from .pipelines import PipelineDataFormat as PipelineDataFormat
837
+ from .pipelines import QuestionAnsweringPipeline as QuestionAnsweringPipeline
838
+ from .pipelines import SummarizationPipeline as SummarizationPipeline
839
+ from .pipelines import TableQuestionAnsweringPipeline as TableQuestionAnsweringPipeline
840
+ from .pipelines import Text2TextGenerationPipeline as Text2TextGenerationPipeline
841
+ from .pipelines import TextClassificationPipeline as TextClassificationPipeline
842
+ from .pipelines import TextGenerationPipeline as TextGenerationPipeline
843
+ from .pipelines import TextToAudioPipeline as TextToAudioPipeline
844
+ from .pipelines import TokenClassificationPipeline as TokenClassificationPipeline
845
+ from .pipelines import TranslationPipeline as TranslationPipeline
846
+ from .pipelines import VideoClassificationPipeline as VideoClassificationPipeline
847
+ from .pipelines import VisualQuestionAnsweringPipeline as VisualQuestionAnsweringPipeline
848
+ from .pipelines import ZeroShotAudioClassificationPipeline as ZeroShotAudioClassificationPipeline
849
+ from .pipelines import ZeroShotClassificationPipeline as ZeroShotClassificationPipeline
850
+ from .pipelines import ZeroShotImageClassificationPipeline as ZeroShotImageClassificationPipeline
851
+ from .pipelines import ZeroShotObjectDetectionPipeline as ZeroShotObjectDetectionPipeline
852
+ from .pipelines import pipeline as pipeline
853
+ from .processing_utils import ProcessorMixin as ProcessorMixin
854
+ from .pytorch_utils import Conv1D as Conv1D
855
+ from .pytorch_utils import apply_chunking_to_forward as apply_chunking_to_forward
856
+ from .pytorch_utils import prune_layer as prune_layer
857
+
858
+ # Tokenization
859
+ from .tokenization_utils import PreTrainedTokenizer as PreTrainedTokenizer
860
+ from .tokenization_utils_base import AddedToken as AddedToken
861
+ from .tokenization_utils_base import BatchEncoding as BatchEncoding
862
+ from .tokenization_utils_base import CharSpan as CharSpan
863
+ from .tokenization_utils_base import PreTrainedTokenizerBase as PreTrainedTokenizerBase
864
+ from .tokenization_utils_base import SpecialTokensMixin as SpecialTokensMixin
865
+ from .tokenization_utils_base import TokenSpan as TokenSpan
866
+ from .tokenization_utils_fast import PreTrainedTokenizerFast as PreTrainedTokenizerFast
867
+
868
+ # Trainer
869
+ from .trainer import Trainer as Trainer
870
+
871
+ # Trainer
872
+ from .trainer_callback import DefaultFlowCallback as DefaultFlowCallback
873
+ from .trainer_callback import EarlyStoppingCallback as EarlyStoppingCallback
874
+ from .trainer_callback import PrinterCallback as PrinterCallback
875
+ from .trainer_callback import ProgressCallback as ProgressCallback
876
+ from .trainer_callback import TrainerCallback as TrainerCallback
877
+ from .trainer_callback import TrainerControl as TrainerControl
878
+ from .trainer_callback import TrainerState as TrainerState
879
+ from .trainer_pt_utils import torch_distributed_zero_first as torch_distributed_zero_first
880
+ from .trainer_seq2seq import Seq2SeqTrainer as Seq2SeqTrainer
881
+ from .trainer_utils import EvalPrediction as EvalPrediction
882
+ from .trainer_utils import IntervalStrategy as IntervalStrategy
883
+ from .trainer_utils import SchedulerType as SchedulerType
884
+ from .trainer_utils import enable_full_determinism as enable_full_determinism
885
+ from .trainer_utils import set_seed as set_seed
886
+ from .training_args import TrainingArguments as TrainingArguments
887
+ from .training_args_seq2seq import Seq2SeqTrainingArguments as Seq2SeqTrainingArguments
888
+ from .training_args_tf import TFTrainingArguments as TFTrainingArguments
889
+
890
+ # Files and general utilities
891
+ from .utils import CONFIG_NAME as CONFIG_NAME
892
+ from .utils import MODEL_CARD_NAME as MODEL_CARD_NAME
893
+ from .utils import PYTORCH_PRETRAINED_BERT_CACHE as PYTORCH_PRETRAINED_BERT_CACHE
894
+ from .utils import PYTORCH_TRANSFORMERS_CACHE as PYTORCH_TRANSFORMERS_CACHE
895
+ from .utils import SPIECE_UNDERLINE as SPIECE_UNDERLINE
896
+ from .utils import TF2_WEIGHTS_NAME as TF2_WEIGHTS_NAME
897
+ from .utils import TF_WEIGHTS_NAME as TF_WEIGHTS_NAME
898
+ from .utils import TRANSFORMERS_CACHE as TRANSFORMERS_CACHE
899
+ from .utils import WEIGHTS_NAME as WEIGHTS_NAME
900
+ from .utils import TensorType as TensorType
901
+ from .utils import add_end_docstrings as add_end_docstrings
902
+ from .utils import add_start_docstrings as add_start_docstrings
903
+ from .utils import is_apex_available as is_apex_available
904
+ from .utils import is_av_available as is_av_available
905
+ from .utils import is_datasets_available as is_datasets_available
906
+ from .utils import is_faiss_available as is_faiss_available
907
+ from .utils import is_matplotlib_available as is_matplotlib_available
908
+ from .utils import is_phonemizer_available as is_phonemizer_available
909
+ from .utils import is_psutil_available as is_psutil_available
910
+ from .utils import is_py3nvml_available as is_py3nvml_available
911
+ from .utils import is_pyctcdecode_available as is_pyctcdecode_available
912
+ from .utils import is_sacremoses_available as is_sacremoses_available
913
+ from .utils import is_safetensors_available as is_safetensors_available
914
+ from .utils import is_sklearn_available as is_sklearn_available
915
+ from .utils import is_torch_hpu_available as is_torch_hpu_available
916
+ from .utils import is_torch_mlu_available as is_torch_mlu_available
917
+ from .utils import is_torch_musa_available as is_torch_musa_available
918
+ from .utils import is_torch_neuroncore_available as is_torch_neuroncore_available
919
+ from .utils import is_torch_npu_available as is_torch_npu_available
920
+ from .utils import is_torch_xla_available as is_torch_xla_available
921
+ from .utils import is_torch_xpu_available as is_torch_xpu_available
922
+ from .utils import logging as logging
923
+
924
+ # bitsandbytes config
925
+ from .utils.quantization_config import AqlmConfig as AqlmConfig
926
+ from .utils.quantization_config import AutoRoundConfig as AutoRoundConfig
927
+ from .utils.quantization_config import AwqConfig as AwqConfig
928
+ from .utils.quantization_config import BitNetQuantConfig as BitNetQuantConfig
929
+ from .utils.quantization_config import BitsAndBytesConfig as BitsAndBytesConfig
930
+ from .utils.quantization_config import CompressedTensorsConfig as CompressedTensorsConfig
931
+ from .utils.quantization_config import EetqConfig as EetqConfig
932
+ from .utils.quantization_config import FbgemmFp8Config as FbgemmFp8Config
933
+ from .utils.quantization_config import FineGrainedFP8Config as FineGrainedFP8Config
934
+ from .utils.quantization_config import FPQuantConfig as FPQuantConfig
935
+ from .utils.quantization_config import GPTQConfig as GPTQConfig
936
+ from .utils.quantization_config import HiggsConfig as HiggsConfig
937
+ from .utils.quantization_config import HqqConfig as HqqConfig
938
+ from .utils.quantization_config import QuantoConfig as QuantoConfig
939
+ from .utils.quantization_config import QuarkConfig as QuarkConfig
940
+ from .utils.quantization_config import SpQRConfig as SpQRConfig
941
+ from .utils.quantization_config import TorchAoConfig as TorchAoConfig
942
+ from .utils.quantization_config import VptqConfig as VptqConfig
943
+ from .video_processing_utils import BaseVideoProcessor as BaseVideoProcessor
944
+
945
+ else:
946
+ import sys
947
+
948
+ _import_structure = {k: set(v) for k, v in _import_structure.items()}
949
+
950
+ import_structure = define_import_structure(Path(__file__).parent / "models", prefix="models")
951
+ import_structure[frozenset({})].update(_import_structure)
952
+
953
+ sys.modules[__name__] = _LazyModule(
954
+ __name__,
955
+ globals()["__file__"],
956
+ import_structure,
957
+ module_spec=__spec__,
958
+ extra_objects={"__version__": __version__},
959
+ )
960
+
961
+
962
+ if not is_tf_available() and not is_torch_available() and not is_flax_available():
963
+ logger.warning_advice(
964
+ "None of PyTorch, TensorFlow >= 2.0, or Flax have been found. "
965
+ "Models won't be available and only tokenizers, configuration "
966
+ "and file/data utilities can be used."
967
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/activations.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ import math
16
+ from collections import OrderedDict
17
+
18
+ import torch
19
+ from torch import Tensor, nn
20
+
21
+ from .utils import logging
22
+ from .utils.import_utils import is_torchdynamo_compiling
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class PytorchGELUTanh(nn.Module):
29
+ """
30
+ A fast C implementation of the tanh approximation of the GeLU activation function. See
31
+ https://huggingface.co/papers/1606.08415.
32
+
33
+ This implementation is equivalent to NewGELU and FastGELU but much faster. However, it is not an exact numerical
34
+ match due to rounding errors.
35
+ """
36
+
37
+ def forward(self, input: Tensor) -> Tensor:
38
+ return nn.functional.gelu(input, approximate="tanh")
39
+
40
+
41
+ class NewGELUActivation(nn.Module):
42
+ """
43
+ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
44
+ the Gaussian Error Linear Units paper: https://huggingface.co/papers/1606.08415
45
+ """
46
+
47
+ def forward(self, input: Tensor) -> Tensor:
48
+ return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0))))
49
+
50
+
51
+ class GELUActivation(nn.Module):
52
+ """
53
+ Original Implementation of the GELU activation function in Google BERT repo when initially created. For
54
+ information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 +
55
+ torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functional
56
+ Also see the Gaussian Error Linear Units paper: https://huggingface.co/papers/1606.08415
57
+ """
58
+
59
+ def __init__(self, use_gelu_python: bool = False):
60
+ super().__init__()
61
+ if use_gelu_python:
62
+ self.act = self._gelu_python
63
+ else:
64
+ self.act = nn.functional.gelu
65
+
66
+ def _gelu_python(self, input: Tensor) -> Tensor:
67
+ return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))
68
+
69
+ def forward(self, input: Tensor) -> Tensor:
70
+ return self.act(input)
71
+
72
+
73
+ class FastGELUActivation(nn.Module):
74
+ """
75
+ Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs
76
+ """
77
+
78
+ def forward(self, input: Tensor) -> Tensor:
79
+ return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input)))
80
+
81
+
82
+ class QuickGELUActivation(nn.Module):
83
+ """
84
+ Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
85
+ """
86
+
87
+ def forward(self, input: Tensor) -> Tensor:
88
+ return input * torch.sigmoid(1.702 * input)
89
+
90
+
91
+ class ClippedGELUActivation(nn.Module):
92
+ """
93
+ Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as
94
+ it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to
95
+ https://huggingface.co/papers/2004.09602.
96
+
97
+ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
98
+ initially created.
99
+
100
+ For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 +
101
+ torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://huggingface.co/papers/1606.08415
102
+ """
103
+
104
+ def __init__(self, min: float, max: float):
105
+ if min > max:
106
+ raise ValueError(f"min should be < max (got min: {min}, max: {max})")
107
+
108
+ super().__init__()
109
+ self.min = min
110
+ self.max = max
111
+
112
+ def forward(self, x: Tensor) -> Tensor:
113
+ return torch.clip(gelu(x), self.min, self.max)
114
+
115
+
116
+ class AccurateGELUActivation(nn.Module):
117
+ """
118
+ Applies GELU approximation that is faster than default and more accurate than QuickGELU. See:
119
+ https://github.com/hendrycks/GELUs
120
+
121
+ Implemented along with MEGA (Moving Average Equipped Gated Attention)
122
+ """
123
+
124
+ def __init__(self):
125
+ super().__init__()
126
+ self.precomputed_constant = math.sqrt(2 / math.pi)
127
+
128
+ def forward(self, input: Tensor) -> Tensor:
129
+ return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(input, 3))))
130
+
131
+
132
+ class MishActivation(nn.Module):
133
+ """
134
+ See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://huggingface.co/papers/1908.08681). Also
135
+ visit the official repository for the paper: https://github.com/digantamisra98/Mish
136
+ """
137
+
138
+ def __init__(self):
139
+ super().__init__()
140
+ self.act = nn.functional.mish
141
+
142
+ def _mish_python(self, input: Tensor) -> Tensor:
143
+ return input * torch.tanh(nn.functional.softplus(input))
144
+
145
+ def forward(self, input: Tensor) -> Tensor:
146
+ return self.act(input)
147
+
148
+
149
+ class LinearActivation(nn.Module):
150
+ """
151
+ Applies the linear activation function, i.e. forwarding input directly to output.
152
+ """
153
+
154
+ def forward(self, input: Tensor) -> Tensor:
155
+ return input
156
+
157
+
158
+ class LaplaceActivation(nn.Module):
159
+ """
160
+ Applies elementwise activation based on Laplace function, introduced in MEGA as an attention activation. See
161
+ https://huggingface.co/papers/2209.10655
162
+
163
+ Inspired by squared relu, but with bounded range and gradient for better stability
164
+ """
165
+
166
+ def forward(self, input, mu=0.707107, sigma=0.282095):
167
+ input = (input - mu).div(sigma * math.sqrt(2.0))
168
+ return 0.5 * (1.0 + torch.erf(input))
169
+
170
+
171
+ class ReLUSquaredActivation(nn.Module):
172
+ """
173
+ Applies the relu^2 activation introduced in https://huggingface.co/papers/2109.08668v2
174
+ """
175
+
176
+ def forward(self, input):
177
+ relu_applied = nn.functional.relu(input)
178
+ squared = torch.square(relu_applied)
179
+ return squared
180
+
181
+
182
+ class ClassInstantier(OrderedDict):
183
+ def __getitem__(self, key):
184
+ content = super().__getitem__(key)
185
+ cls, kwargs = content if isinstance(content, tuple) else (content, {})
186
+ return cls(**kwargs)
187
+
188
+
189
+ class XIELUActivation(nn.Module):
190
+ """
191
+ Applies the xIELU activation function introduced in https://arxiv.org/abs/2411.13010
192
+
193
+ If the user has installed the nickjbrowning/XIELU wheel, we import xIELU CUDA
194
+ Otherwise, we emit a single warning and use xIELU Python
195
+ """
196
+
197
+ def __init__(
198
+ self,
199
+ alpha_p_init=0.8,
200
+ alpha_n_init=0.8,
201
+ beta=0.5,
202
+ eps=-1e-6,
203
+ dtype=torch.bfloat16,
204
+ with_vector_loads=False,
205
+ ):
206
+ super().__init__()
207
+ self.alpha_p = nn.Parameter(torch.log(torch.exp(torch.tensor(alpha_p_init, dtype=dtype)) - 1).unsqueeze(0))
208
+ self.alpha_n = nn.Parameter(
209
+ torch.log(torch.exp(torch.tensor(alpha_n_init - beta, dtype=dtype)) - 1).unsqueeze(0)
210
+ )
211
+ self.register_buffer("beta", torch.tensor(beta, dtype=dtype))
212
+ self.register_buffer("eps", torch.tensor(eps, dtype=dtype))
213
+ self.with_vector_loads = with_vector_loads
214
+ # Temporary until xIELU CUDA fully implemented
215
+ self._beta_scalar = float(self.beta.detach().cpu().float().item())
216
+ self._eps_scalar = float(self.eps.detach().cpu().float().item())
217
+
218
+ self._xielu_cuda_obj = None
219
+ try:
220
+ import xielu.ops # noqa: F401
221
+
222
+ self._xielu_cuda_obj = torch.classes.xielu.XIELU()
223
+ msg = "Using experimental xIELU CUDA."
224
+ try:
225
+ from torch._dynamo import allow_in_graph
226
+
227
+ self._xielu_cuda_fn = allow_in_graph(self._xielu_cuda)
228
+ msg += " Enabled torch._dynamo for xIELU CUDA."
229
+ except Exception as err:
230
+ msg += f" Could not enable torch._dynamo for xIELU ({err}) - this may result in slower performance."
231
+ self._xielu_cuda_fn = self._xielu_cuda
232
+ logger.warning_once(msg)
233
+ except Exception as err:
234
+ logger.warning_once(
235
+ "CUDA-fused xIELU not available (%s) – falling back to a Python version.\n"
236
+ "For CUDA xIELU (experimental), `pip install git+https://github.com/nickjbrowning/XIELU`",
237
+ str(err),
238
+ )
239
+
240
+ def _xielu_python(self, x: Tensor) -> Tensor:
241
+ alpha_p = nn.functional.softplus(self.alpha_p)
242
+ alpha_n = self.beta + nn.functional.softplus(self.alpha_n)
243
+ return torch.where(
244
+ x > 0,
245
+ alpha_p * x * x + self.beta * x,
246
+ (torch.expm1(torch.min(x, self.eps)) - x) * alpha_n + self.beta * x,
247
+ )
248
+
249
+ def _xielu_cuda(self, x: Tensor) -> Tensor:
250
+ """Firewall function to prevent torch.compile from seeing .item() calls"""
251
+ original_shape = x.shape
252
+ # CUDA kernel expects 3D tensors, reshape if needed
253
+ while x.dim() < 3:
254
+ x = x.unsqueeze(0)
255
+ if x.dim() > 3:
256
+ x = x.view(-1, 1, x.size(-1))
257
+ if original_shape != x.shape:
258
+ logger.warning_once(
259
+ "Warning: xIELU input tensor expects 3 dimensions but got (shape: %s). Reshaping to (shape: %s).",
260
+ original_shape,
261
+ x.shape,
262
+ )
263
+ result = self._xielu_cuda_obj.forward(
264
+ x,
265
+ self.alpha_p,
266
+ self.alpha_n,
267
+ # Temporary until xIELU CUDA fully implemented -> self.{beta,eps}.item()
268
+ self._beta_scalar,
269
+ self._eps_scalar,
270
+ self.with_vector_loads,
271
+ )
272
+ return result.view(original_shape)
273
+
274
+ def forward(self, input: Tensor) -> Tensor:
275
+ if self._xielu_cuda_obj is not None and input.is_cuda:
276
+ if not is_torchdynamo_compiling():
277
+ return self._xielu_cuda_fn(input)
278
+ else:
279
+ logger.warning_once("torch._dynamo is compiling, using Python version of xIELU.")
280
+ return self._xielu_python(input)
281
+
282
+
283
+ ACT2CLS = {
284
+ "gelu": GELUActivation,
285
+ "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}),
286
+ "gelu_fast": FastGELUActivation,
287
+ "gelu_new": NewGELUActivation,
288
+ "gelu_python": (GELUActivation, {"use_gelu_python": True}),
289
+ "gelu_pytorch_tanh": PytorchGELUTanh,
290
+ "gelu_accurate": AccurateGELUActivation,
291
+ "laplace": LaplaceActivation,
292
+ "leaky_relu": nn.LeakyReLU,
293
+ "linear": LinearActivation,
294
+ "mish": MishActivation,
295
+ "quick_gelu": QuickGELUActivation,
296
+ "relu": nn.ReLU,
297
+ "relu2": ReLUSquaredActivation,
298
+ "relu6": nn.ReLU6,
299
+ "sigmoid": nn.Sigmoid,
300
+ "silu": nn.SiLU,
301
+ "swish": nn.SiLU,
302
+ "tanh": nn.Tanh,
303
+ "prelu": nn.PReLU,
304
+ "xielu": XIELUActivation,
305
+ }
306
+ ACT2FN = ClassInstantier(ACT2CLS)
307
+
308
+
309
+ def get_activation(activation_string):
310
+ if activation_string in ACT2FN:
311
+ return ACT2FN[activation_string]
312
+ else:
313
+ raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
314
+
315
+
316
+ # For backwards compatibility with: from activations import gelu_python
317
+ gelu_python = get_activation("gelu_python")
318
+ gelu_new = get_activation("gelu_new")
319
+ gelu = get_activation("gelu")
320
+ gelu_fast = get_activation("gelu_fast")
321
+ quick_gelu = get_activation("quick_gelu")
322
+ silu = get_activation("silu")
323
+ mish = get_activation("mish")
324
+ linear_act = get_activation("linear")
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/activations_tf.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ import math
16
+
17
+ import tensorflow as tf
18
+ from packaging.version import parse
19
+
20
+
21
+ try:
22
+ import tf_keras as keras
23
+ except (ModuleNotFoundError, ImportError):
24
+ import keras
25
+
26
+ if parse(keras.__version__).major > 2:
27
+ raise ValueError(
28
+ "Your currently installed version of Keras is Keras 3, but this is not yet supported in "
29
+ "Transformers. Please install the backwards-compatible tf-keras package with "
30
+ "`pip install tf-keras`."
31
+ )
32
+
33
+
34
+ def _gelu(x):
35
+ """
36
+ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
37
+ initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
38
+ 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see
39
+ https://huggingface.co/papers/1606.08415
40
+ """
41
+ x = tf.convert_to_tensor(x)
42
+ cdf = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0), x.dtype)))
43
+
44
+ return x * cdf
45
+
46
+
47
+ def _gelu_new(x):
48
+ """
49
+ Gaussian Error Linear Unit. This is a smoother version of the GELU. Original paper: https://huggingface.co/papers/1606.0841
50
+
51
+ Args:
52
+ x: float Tensor to perform activation
53
+
54
+ Returns:
55
+ `x` with the GELU activation applied.
56
+ """
57
+ x = tf.convert_to_tensor(x)
58
+ pi = tf.cast(math.pi, x.dtype)
59
+ coeff = tf.cast(0.044715, x.dtype)
60
+ cdf = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi) * (x + coeff * tf.pow(x, 3))))
61
+
62
+ return x * cdf
63
+
64
+
65
+ def mish(x):
66
+ x = tf.convert_to_tensor(x)
67
+
68
+ return x * tf.tanh(tf.math.softplus(x))
69
+
70
+
71
+ def gelu_fast(x):
72
+ x = tf.convert_to_tensor(x)
73
+ coeff1 = tf.cast(0.044715, x.dtype)
74
+ coeff2 = tf.cast(0.7978845608, x.dtype)
75
+
76
+ return 0.5 * x * (1.0 + tf.tanh(x * coeff2 * (1.0 + coeff1 * x * x)))
77
+
78
+
79
+ def quick_gelu(x):
80
+ x = tf.convert_to_tensor(x)
81
+ coeff = tf.cast(1.702, x.dtype)
82
+ return x * tf.math.sigmoid(coeff * x)
83
+
84
+
85
+ def gelu_10(x):
86
+ """
87
+ Clip the range of possible GeLU outputs between [-10, 10]. This is especially useful for quantization purpose, as
88
+ it allows mapping 2 negatives values in the GeLU spectrum. For more information on this trick, please refer to
89
+ https://huggingface.co/papers/2004.09602
90
+
91
+ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
92
+ initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
93
+ 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see
94
+ https://huggingface.co/papers/1606.08415 :param x: :return:
95
+ """
96
+ return tf.clip_by_value(_gelu(x), -10, 10)
97
+
98
+
99
+ def glu(x, axis=-1):
100
+ """
101
+ Gated Linear Unit. Implementation as defined in the original paper (see https://huggingface.co/papers/1612.08083), where
102
+ the input `x` is split in two halves across a dimension (`axis`), A and B, returning A * sigmoid(B).
103
+
104
+ Args:
105
+ `x`: float Tensor to perform activation
106
+ `axis`: dimension across which `x` be split in half
107
+
108
+ Returns:
109
+ `x` with the GLU activation applied (with its size halved across the dimension `axis`).
110
+ """
111
+ a, b = tf.split(x, 2, axis=axis)
112
+ return a * tf.math.sigmoid(b)
113
+
114
+
115
+ if parse(tf.version.VERSION) >= parse("2.4"):
116
+
117
+ def approximate_gelu_wrap(x):
118
+ return keras.activations.gelu(x, approximate=True)
119
+
120
+ gelu = keras.activations.gelu
121
+ gelu_new = approximate_gelu_wrap
122
+ else:
123
+ gelu = _gelu
124
+ gelu_new = _gelu_new
125
+
126
+
127
+ ACT2FN = {
128
+ "gelu": gelu,
129
+ "gelu_10": gelu_10,
130
+ "gelu_fast": gelu_fast,
131
+ "gelu_new": gelu_new,
132
+ "glu": glu,
133
+ "mish": mish,
134
+ "quick_gelu": quick_gelu,
135
+ "relu": keras.activations.relu,
136
+ "sigmoid": keras.activations.sigmoid,
137
+ "silu": keras.activations.swish,
138
+ "swish": keras.activations.swish,
139
+ "tanh": keras.activations.tanh,
140
+ }
141
+
142
+
143
+ def get_tf_activation(activation_string):
144
+ if activation_string in ACT2FN:
145
+ return ACT2FN[activation_string]
146
+ else:
147
+ raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/audio_utils.py ADDED
@@ -0,0 +1,1224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team and the librosa & torchaudio 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
+ Audio processing functions to extract features from audio waveforms. This code is pure numpy to support all frameworks
16
+ and remove unnecessary dependencies.
17
+ """
18
+
19
+ import base64
20
+ import importlib
21
+ import io
22
+ import os
23
+ import warnings
24
+ from io import BytesIO
25
+ from typing import Any, Optional, Sequence, Union
26
+
27
+ import numpy as np
28
+ import requests
29
+ from packaging import version
30
+
31
+ from .utils import (
32
+ is_librosa_available,
33
+ is_numpy_array,
34
+ is_soundfile_available,
35
+ is_torch_tensor,
36
+ is_torchcodec_available,
37
+ requires_backends,
38
+ )
39
+
40
+
41
+ if is_soundfile_available():
42
+ import soundfile as sf
43
+
44
+ if is_librosa_available():
45
+ import librosa
46
+
47
+ # TODO: @eustlb, we actually don't need librosa but soxr is installed with librosa
48
+ import soxr
49
+
50
+ if is_torchcodec_available():
51
+ TORCHCODEC_VERSION = version.parse(importlib.metadata.version("torchcodec"))
52
+
53
+ AudioInput = Union[np.ndarray, "torch.Tensor", Sequence[np.ndarray], Sequence["torch.Tensor"]] # noqa: F821
54
+
55
+
56
+ def load_audio(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray:
57
+ """
58
+ Loads `audio` to an np.ndarray object.
59
+
60
+ Args:
61
+ audio (`str` or `np.ndarray`):
62
+ The audio to be loaded to the numpy array format.
63
+ sampling_rate (`int`, *optional*, defaults to 16000):
64
+ The sampling rate to be used when loading the audio. It should be same as the
65
+ sampling rate the model you will be using further was trained with.
66
+ timeout (`float`, *optional*):
67
+ The timeout value in seconds for the URL request.
68
+
69
+ Returns:
70
+ `np.ndarray`: A numpy array representing the audio.
71
+ """
72
+ if isinstance(audio, str):
73
+ # Try to load with `torchcodec` but do not enforce users to install it. If not found
74
+ # fallback to `librosa`. If using an audio-only model, most probably `torchcodec` won't be
75
+ # needed. Do not raise any errors if not installed or versions do not match
76
+ if is_torchcodec_available() and TORCHCODEC_VERSION >= version.parse("0.3.0"):
77
+ audio = load_audio_torchcodec(audio, sampling_rate=sampling_rate)
78
+ else:
79
+ audio = load_audio_librosa(audio, sampling_rate=sampling_rate, timeout=timeout)
80
+ elif isinstance(audio, np.ndarray):
81
+ audio = audio
82
+ else:
83
+ raise TypeError(
84
+ "Incorrect format used for `audio`. Should be an url linking to an audio, a local path, or numpy array."
85
+ )
86
+ return audio
87
+
88
+
89
+ def load_audio_torchcodec(audio: Union[str, np.ndarray], sampling_rate=16000) -> np.ndarray:
90
+ """
91
+ Loads `audio` to an np.ndarray object using `torchcodec`.
92
+
93
+ Args:
94
+ audio (`str` or `np.ndarray`):
95
+ The audio to be loaded to the numpy array format.
96
+ sampling_rate (`int`, *optional*, defaults to 16000):
97
+ The sampling rate to be used when loading the audio. It should be same as the
98
+ sampling rate the model you will be using further was trained with.
99
+
100
+ Returns:
101
+ `np.ndarray`: A numpy array representing the audio.
102
+ """
103
+ # Lazy import so that issues in torchcodec compatibility don't crash the whole library
104
+ requires_backends(load_audio_torchcodec, ["torchcodec"])
105
+ from torchcodec.decoders import AudioDecoder
106
+
107
+ # Set `num_channels` to `1` which is what most models expects and the default in librosa
108
+ decoder = AudioDecoder(audio, sample_rate=sampling_rate, num_channels=1)
109
+ audio = decoder.get_all_samples().data[0].numpy() # NOTE: feature extractors don't accept torch tensors
110
+ return audio
111
+
112
+
113
+ def load_audio_librosa(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray:
114
+ """
115
+ Loads `audio` to an np.ndarray object using `librosa`.
116
+
117
+ Args:
118
+ audio (`str` or `np.ndarray`):
119
+ The audio to be loaded to the numpy array format.
120
+ sampling_rate (`int`, *optional*, defaults to 16000):
121
+ The sampling rate to be used when loading the audio. It should be same as the
122
+ sampling rate the model you will be using further was trained with.
123
+ timeout (`float`, *optional*):
124
+ The timeout value in seconds for the URL request.
125
+
126
+ Returns:
127
+ `np.ndarray`: A numpy array representing the audio.
128
+ """
129
+ requires_backends(load_audio_librosa, ["librosa"])
130
+
131
+ # Load audio from URL (e.g https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/translate_to_chinese.wav)
132
+ if audio.startswith("http://") or audio.startswith("https://"):
133
+ audio = librosa.load(BytesIO(requests.get(audio, timeout=timeout).content), sr=sampling_rate)[0]
134
+ elif os.path.isfile(audio):
135
+ audio = librosa.load(audio, sr=sampling_rate)[0]
136
+ return audio
137
+
138
+
139
+ def load_audio_as(
140
+ audio: str,
141
+ return_format: str,
142
+ timeout: Optional[int] = None,
143
+ force_mono: bool = False,
144
+ sampling_rate: Optional[int] = None,
145
+ ) -> Union[str, dict[str, Any], io.BytesIO, None]:
146
+ """
147
+ Load audio from either a local file path or URL and return in specified format.
148
+
149
+ Args:
150
+ audio (`str`): Either a local file path or a URL to an audio file
151
+ return_format (`str`): Format to return the audio in:
152
+ - "base64": Base64 encoded string
153
+ - "dict": Dictionary with data and format
154
+ - "buffer": BytesIO object
155
+ timeout (`int`, *optional*): Timeout for URL requests in seconds
156
+ force_mono (`bool`): Whether to convert stereo audio to mono
157
+ sampling_rate (`int`, *optional*): If provided, the audio will be resampled to the specified sampling rate.
158
+
159
+ Returns:
160
+ `Union[str, Dict[str, Any], io.BytesIO, None]`:
161
+ - `str`: Base64 encoded audio data (if return_format="base64")
162
+ - `dict`: Dictionary with 'data' (base64 encoded audio data) and 'format' keys (if return_format="dict")
163
+ - `io.BytesIO`: BytesIO object containing audio data (if return_format="buffer")
164
+ """
165
+ # TODO: @eustlb, we actually don't need librosa but soxr is installed with librosa
166
+ requires_backends(load_audio_as, ["librosa"])
167
+
168
+ if return_format not in ["base64", "dict", "buffer"]:
169
+ raise ValueError(f"Invalid return_format: {return_format}. Must be 'base64', 'dict', or 'buffer'")
170
+
171
+ try:
172
+ # Load audio bytes from URL or file
173
+ audio_bytes = None
174
+ if audio.startswith(("http://", "https://")):
175
+ response = requests.get(audio, timeout=timeout)
176
+ response.raise_for_status()
177
+ audio_bytes = response.content
178
+ elif os.path.isfile(audio):
179
+ with open(audio, "rb") as audio_file:
180
+ audio_bytes = audio_file.read()
181
+ else:
182
+ raise ValueError(f"File not found: {audio}")
183
+
184
+ # Process audio data
185
+ with io.BytesIO(audio_bytes) as audio_file:
186
+ with sf.SoundFile(audio_file) as f:
187
+ audio_array = f.read(dtype="float32")
188
+ original_sr = f.samplerate
189
+ audio_format = f.format
190
+ if sampling_rate is not None and sampling_rate != original_sr:
191
+ # Resample audio to target sampling rate
192
+ audio_array = soxr.resample(audio_array, original_sr, sampling_rate, quality="HQ")
193
+ else:
194
+ sampling_rate = original_sr
195
+
196
+ # Convert to mono if needed
197
+ if force_mono and audio_array.ndim != 1:
198
+ audio_array = audio_array.mean(axis=1)
199
+
200
+ buffer = io.BytesIO()
201
+ sf.write(buffer, audio_array, sampling_rate, format=audio_format.upper())
202
+ buffer.seek(0)
203
+
204
+ if return_format == "buffer":
205
+ return buffer
206
+ elif return_format == "base64":
207
+ return base64.b64encode(buffer.read()).decode("utf-8")
208
+ elif return_format == "dict":
209
+ return {
210
+ "data": base64.b64encode(buffer.read()).decode("utf-8"),
211
+ "format": audio_format.lower(),
212
+ }
213
+
214
+ except Exception as e:
215
+ raise ValueError(f"Error loading audio: {e}")
216
+
217
+
218
+ def is_valid_audio(audio):
219
+ return is_numpy_array(audio) or is_torch_tensor(audio)
220
+
221
+
222
+ def is_valid_list_of_audio(audio):
223
+ return audio and all(is_valid_audio(audio_i) for audio_i in audio)
224
+
225
+
226
+ def make_list_of_audio(
227
+ audio: Union[list[AudioInput], AudioInput],
228
+ ) -> AudioInput:
229
+ """
230
+ Ensure that the output is a list of audio.
231
+ Args:
232
+ audio (`Union[list[AudioInput], AudioInput]`):
233
+ The input audio.
234
+ Returns:
235
+ list: A list of audio.
236
+ """
237
+ # If it's a list of audios, it's already in the right format
238
+ if isinstance(audio, (list, tuple)) and is_valid_list_of_audio(audio):
239
+ return audio
240
+
241
+ # If it's a single audio, convert it to a list of
242
+ if is_valid_audio(audio):
243
+ return [audio]
244
+
245
+ raise ValueError("Invalid input type. Must be a single audio or a list of audio")
246
+
247
+
248
+ def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]:
249
+ """
250
+ Convert frequency from hertz to mels.
251
+
252
+ Args:
253
+ freq (`float` or `np.ndarray`):
254
+ The frequency, or multiple frequencies, in hertz (Hz).
255
+ mel_scale (`str`, *optional*, defaults to `"htk"`):
256
+ The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
257
+
258
+ Returns:
259
+ `float` or `np.ndarray`: The frequencies on the mel scale.
260
+ """
261
+
262
+ if mel_scale not in ["slaney", "htk", "kaldi"]:
263
+ raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".')
264
+
265
+ if mel_scale == "htk":
266
+ return 2595.0 * np.log10(1.0 + (freq / 700.0))
267
+ elif mel_scale == "kaldi":
268
+ return 1127.0 * np.log(1.0 + (freq / 700.0))
269
+
270
+ min_log_hertz = 1000.0
271
+ min_log_mel = 15.0
272
+ logstep = 27.0 / np.log(6.4)
273
+ mels = 3.0 * freq / 200.0
274
+
275
+ if isinstance(freq, np.ndarray):
276
+ log_region = freq >= min_log_hertz
277
+ mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep
278
+ elif freq >= min_log_hertz:
279
+ mels = min_log_mel + np.log(freq / min_log_hertz) * logstep
280
+
281
+ return mels
282
+
283
+
284
+ def mel_to_hertz(mels: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]:
285
+ """
286
+ Convert frequency from mels to hertz.
287
+
288
+ Args:
289
+ mels (`float` or `np.ndarray`):
290
+ The frequency, or multiple frequencies, in mels.
291
+ mel_scale (`str`, *optional*, `"htk"`):
292
+ The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
293
+
294
+ Returns:
295
+ `float` or `np.ndarray`: The frequencies in hertz.
296
+ """
297
+
298
+ if mel_scale not in ["slaney", "htk", "kaldi"]:
299
+ raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".')
300
+
301
+ if mel_scale == "htk":
302
+ return 700.0 * (np.power(10, mels / 2595.0) - 1.0)
303
+ elif mel_scale == "kaldi":
304
+ return 700.0 * (np.exp(mels / 1127.0) - 1.0)
305
+
306
+ min_log_hertz = 1000.0
307
+ min_log_mel = 15.0
308
+ logstep = np.log(6.4) / 27.0
309
+ freq = 200.0 * mels / 3.0
310
+
311
+ if isinstance(mels, np.ndarray):
312
+ log_region = mels >= min_log_mel
313
+ freq[log_region] = min_log_hertz * np.exp(logstep * (mels[log_region] - min_log_mel))
314
+ elif mels >= min_log_mel:
315
+ freq = min_log_hertz * np.exp(logstep * (mels - min_log_mel))
316
+
317
+ return freq
318
+
319
+
320
+ def hertz_to_octave(
321
+ freq: Union[float, np.ndarray], tuning: Optional[float] = 0.0, bins_per_octave: Optional[int] = 12
322
+ ):
323
+ """
324
+ Convert frequency from hertz to fractional octave numbers.
325
+ Adapted from *librosa*.
326
+
327
+ Args:
328
+ freq (`float` or `np.ndarray`):
329
+ The frequency, or multiple frequencies, in hertz (Hz).
330
+ tuning (`float`, defaults to `0.`):
331
+ Tuning deviation from the Stuttgart pitch (A440) in (fractional) bins per octave.
332
+ bins_per_octave (`int`, defaults to `12`):
333
+ Number of bins per octave.
334
+
335
+ Returns:
336
+ `float` or `np.ndarray`: The frequencies on the octave scale.
337
+ """
338
+ stuttgart_pitch = 440.0 * 2.0 ** (tuning / bins_per_octave)
339
+ octave = np.log2(freq / (float(stuttgart_pitch) / 16))
340
+ return octave
341
+
342
+
343
+ def _create_triangular_filter_bank(fft_freqs: np.ndarray, filter_freqs: np.ndarray) -> np.ndarray:
344
+ """
345
+ Creates a triangular filter bank.
346
+
347
+ Adapted from *torchaudio* and *librosa*.
348
+
349
+ Args:
350
+ fft_freqs (`np.ndarray` of shape `(num_frequency_bins,)`):
351
+ Discrete frequencies of the FFT bins in Hz.
352
+ filter_freqs (`np.ndarray` of shape `(num_mel_filters,)`):
353
+ Center frequencies of the triangular filters to create, in Hz.
354
+
355
+ Returns:
356
+ `np.ndarray` of shape `(num_frequency_bins, num_mel_filters)`
357
+ """
358
+ filter_diff = np.diff(filter_freqs)
359
+ slopes = np.expand_dims(filter_freqs, 0) - np.expand_dims(fft_freqs, 1)
360
+ down_slopes = -slopes[:, :-2] / filter_diff[:-1]
361
+ up_slopes = slopes[:, 2:] / filter_diff[1:]
362
+ return np.maximum(np.zeros(1), np.minimum(down_slopes, up_slopes))
363
+
364
+
365
+ def chroma_filter_bank(
366
+ num_frequency_bins: int,
367
+ num_chroma: int,
368
+ sampling_rate: int,
369
+ tuning: float = 0.0,
370
+ power: Optional[float] = 2.0,
371
+ weighting_parameters: Optional[tuple[float, float]] = (5.0, 2.0),
372
+ start_at_c_chroma: Optional[bool] = True,
373
+ ):
374
+ """
375
+ Creates a chroma filter bank, i.e a linear transformation to project spectrogram bins onto chroma bins.
376
+
377
+ Adapted from *librosa*.
378
+
379
+ Args:
380
+ num_frequency_bins (`int`):
381
+ Number of frequencies used to compute the spectrogram (should be the same as in `stft`).
382
+ num_chroma (`int`):
383
+ Number of chroma bins (i.e pitch classes).
384
+ sampling_rate (`float`):
385
+ Sample rate of the audio waveform.
386
+ tuning (`float`):
387
+ Tuning deviation from A440 in fractions of a chroma bin.
388
+ power (`float`, *optional*, defaults to 2.0):
389
+ If 12.0, normalizes each column with their L2 norm. If 1.0, normalizes each column with their L1 norm.
390
+ weighting_parameters (`tuple[float, float]`, *optional*, defaults to `(5., 2.)`):
391
+ If specified, apply a Gaussian weighting parameterized by the first element of the tuple being the center and
392
+ the second element being the Gaussian half-width.
393
+ start_at_c_chroma (`float`, *optional*, defaults to `True`):
394
+ If True, the filter bank will start at the 'C' pitch class. Otherwise, it will start at 'A'.
395
+ Returns:
396
+ `np.ndarray` of shape `(num_frequency_bins, num_chroma)`
397
+ """
398
+ # Get the FFT bins, not counting the DC component
399
+ frequencies = np.linspace(0, sampling_rate, num_frequency_bins, endpoint=False)[1:]
400
+
401
+ freq_bins = num_chroma * hertz_to_octave(frequencies, tuning=tuning, bins_per_octave=num_chroma)
402
+
403
+ # make up a value for the 0 Hz bin = 1.5 octaves below bin 1
404
+ # (so chroma is 50% rotated from bin 1, and bin width is broad)
405
+ freq_bins = np.concatenate(([freq_bins[0] - 1.5 * num_chroma], freq_bins))
406
+
407
+ bins_width = np.concatenate((np.maximum(freq_bins[1:] - freq_bins[:-1], 1.0), [1]))
408
+
409
+ chroma_filters = np.subtract.outer(freq_bins, np.arange(0, num_chroma, dtype="d")).T
410
+
411
+ num_chroma2 = np.round(float(num_chroma) / 2)
412
+
413
+ # Project into range -num_chroma/2 .. num_chroma/2
414
+ # add on fixed offset of 10*num_chroma to ensure all values passed to
415
+ # rem are positive
416
+ chroma_filters = np.remainder(chroma_filters + num_chroma2 + 10 * num_chroma, num_chroma) - num_chroma2
417
+
418
+ # Gaussian bumps - 2*D to make them narrower
419
+ chroma_filters = np.exp(-0.5 * (2 * chroma_filters / np.tile(bins_width, (num_chroma, 1))) ** 2)
420
+
421
+ # normalize each column
422
+ if power is not None:
423
+ chroma_filters = chroma_filters / np.sum(chroma_filters**power, axis=0, keepdims=True) ** (1.0 / power)
424
+
425
+ # Maybe apply scaling for fft bins
426
+ if weighting_parameters is not None:
427
+ center, half_width = weighting_parameters
428
+ chroma_filters *= np.tile(
429
+ np.exp(-0.5 * (((freq_bins / num_chroma - center) / half_width) ** 2)),
430
+ (num_chroma, 1),
431
+ )
432
+
433
+ if start_at_c_chroma:
434
+ chroma_filters = np.roll(chroma_filters, -3 * (num_chroma // 12), axis=0)
435
+
436
+ # remove aliasing columns, copy to ensure row-contiguity
437
+ return np.ascontiguousarray(chroma_filters[:, : int(1 + num_frequency_bins / 2)])
438
+
439
+
440
+ def mel_filter_bank(
441
+ num_frequency_bins: int,
442
+ num_mel_filters: int,
443
+ min_frequency: float,
444
+ max_frequency: float,
445
+ sampling_rate: int,
446
+ norm: Optional[str] = None,
447
+ mel_scale: str = "htk",
448
+ triangularize_in_mel_space: bool = False,
449
+ ) -> np.ndarray:
450
+ """
451
+ Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and
452
+ various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters
453
+ are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these
454
+ features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.
455
+
456
+ Different banks of mel filters were introduced in the literature. The following variations are supported:
457
+
458
+ - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHz and a speech
459
+ bandwidth of `[0, 4600]` Hz.
460
+ - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech
461
+ bandwidth of `[0, 8000]` Hz. This assumes sampling rate ≥ 16 kHz.
462
+ - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHz and
463
+ speech bandwidth of `[133, 6854]` Hz. This version also includes area normalization.
464
+ - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes a sampling rate of
465
+ 12.5 kHz and speech bandwidth of `[0, 6250]` Hz.
466
+
467
+ This code is adapted from *torchaudio* and *librosa*. Note that the default parameters of torchaudio's
468
+ `melscale_fbanks` implement the `"htk"` filters while librosa uses the `"slaney"` implementation.
469
+
470
+ Args:
471
+ num_frequency_bins (`int`):
472
+ Number of frequency bins (should be the same as `n_fft // 2 + 1` where `n_fft` is the size of the Fourier Transform used to compute the spectrogram).
473
+ num_mel_filters (`int`):
474
+ Number of mel filters to generate.
475
+ min_frequency (`float`):
476
+ Lowest frequency of interest in Hz.
477
+ max_frequency (`float`):
478
+ Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.
479
+ sampling_rate (`int`):
480
+ Sample rate of the audio waveform.
481
+ norm (`str`, *optional*):
482
+ If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization).
483
+ mel_scale (`str`, *optional*, defaults to `"htk"`):
484
+ The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
485
+ triangularize_in_mel_space (`bool`, *optional*, defaults to `False`):
486
+ If this option is enabled, the triangular filter is applied in mel space rather than frequency space. This
487
+ should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.
488
+
489
+ Returns:
490
+ `np.ndarray` of shape (`num_frequency_bins`, `num_mel_filters`): Triangular filter bank matrix. This is a
491
+ projection matrix to go from a spectrogram to a mel spectrogram.
492
+ """
493
+ if norm is not None and norm != "slaney":
494
+ raise ValueError('norm must be one of None or "slaney"')
495
+
496
+ if num_frequency_bins < 2:
497
+ raise ValueError(f"Require num_frequency_bins: {num_frequency_bins} >= 2")
498
+
499
+ if min_frequency > max_frequency:
500
+ raise ValueError(f"Require min_frequency: {min_frequency} <= max_frequency: {max_frequency}")
501
+
502
+ # center points of the triangular mel filters
503
+ mel_min = hertz_to_mel(min_frequency, mel_scale=mel_scale)
504
+ mel_max = hertz_to_mel(max_frequency, mel_scale=mel_scale)
505
+ mel_freqs = np.linspace(mel_min, mel_max, num_mel_filters + 2)
506
+ filter_freqs = mel_to_hertz(mel_freqs, mel_scale=mel_scale)
507
+
508
+ if triangularize_in_mel_space:
509
+ # frequencies of FFT bins in Hz, but filters triangularized in mel space
510
+ fft_bin_width = sampling_rate / ((num_frequency_bins - 1) * 2)
511
+ fft_freqs = hertz_to_mel(fft_bin_width * np.arange(num_frequency_bins), mel_scale=mel_scale)
512
+ filter_freqs = mel_freqs
513
+ else:
514
+ # frequencies of FFT bins in Hz
515
+ fft_freqs = np.linspace(0, sampling_rate // 2, num_frequency_bins)
516
+
517
+ mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs)
518
+
519
+ if norm is not None and norm == "slaney":
520
+ # Slaney-style mel is scaled to be approx constant energy per channel
521
+ enorm = 2.0 / (filter_freqs[2 : num_mel_filters + 2] - filter_freqs[:num_mel_filters])
522
+ mel_filters *= np.expand_dims(enorm, 0)
523
+
524
+ if (mel_filters.max(axis=0) == 0.0).any():
525
+ warnings.warn(
526
+ "At least one mel filter has all zero values. "
527
+ f"The value for `num_mel_filters` ({num_mel_filters}) may be set too high. "
528
+ f"Or, the value for `num_frequency_bins` ({num_frequency_bins}) may be set too low."
529
+ )
530
+
531
+ return mel_filters
532
+
533
+
534
+ def optimal_fft_length(window_length: int) -> int:
535
+ """
536
+ Finds the best FFT input size for a given `window_length`. This function takes a given window length and, if not
537
+ already a power of two, rounds it up to the next power or two.
538
+
539
+ The FFT algorithm works fastest when the length of the input is a power of two, which may be larger than the size
540
+ of the window or analysis frame. For example, if the window is 400 samples, using an FFT input size of 512 samples
541
+ is more optimal than an FFT size of 400 samples. Using a larger FFT size does not affect the detected frequencies,
542
+ it simply gives a higher frequency resolution (i.e. the frequency bins are smaller).
543
+ """
544
+ return 2 ** int(np.ceil(np.log2(window_length)))
545
+
546
+
547
+ def window_function(
548
+ window_length: int,
549
+ name: str = "hann",
550
+ periodic: bool = True,
551
+ frame_length: Optional[int] = None,
552
+ center: bool = True,
553
+ ) -> np.ndarray:
554
+ """
555
+ Returns an array containing the specified window. This window is intended to be used with `stft`.
556
+
557
+ The following window types are supported:
558
+
559
+ - `"boxcar"`: a rectangular window
560
+ - `"hamming"`: the Hamming window
561
+ - `"hann"`: the Hann window
562
+ - `"povey"`: the Povey window
563
+
564
+ Args:
565
+ window_length (`int`):
566
+ The length of the window in samples.
567
+ name (`str`, *optional*, defaults to `"hann"`):
568
+ The name of the window function.
569
+ periodic (`bool`, *optional*, defaults to `True`):
570
+ Whether the window is periodic or symmetric.
571
+ frame_length (`int`, *optional*):
572
+ The length of the analysis frames in samples. Provide a value for `frame_length` if the window is smaller
573
+ than the frame length, so that it will be zero-padded.
574
+ center (`bool`, *optional*, defaults to `True`):
575
+ Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
576
+
577
+ Returns:
578
+ `np.ndarray` of shape `(window_length,)` or `(frame_length,)` containing the window.
579
+ """
580
+ length = window_length + 1 if periodic else window_length
581
+
582
+ if name == "boxcar":
583
+ window = np.ones(length)
584
+ elif name in ["hamming", "hamming_window"]:
585
+ window = np.hamming(length)
586
+ elif name in ["hann", "hann_window"]:
587
+ window = np.hanning(length)
588
+ elif name in ["povey"]:
589
+ window = np.power(np.hanning(length), 0.85)
590
+ else:
591
+ raise ValueError(f"Unknown window function '{name}'")
592
+
593
+ if periodic:
594
+ window = window[:-1]
595
+
596
+ if frame_length is None:
597
+ return window
598
+
599
+ if window_length > frame_length:
600
+ raise ValueError(
601
+ f"Length of the window ({window_length}) may not be larger than frame_length ({frame_length})"
602
+ )
603
+
604
+ padded_window = np.zeros(frame_length)
605
+ offset = (frame_length - window_length) // 2 if center else 0
606
+ padded_window[offset : offset + window_length] = window
607
+ return padded_window
608
+
609
+
610
+ # TODO This method does not support batching yet as we are mainly focused on inference.
611
+ def spectrogram(
612
+ waveform: np.ndarray,
613
+ window: np.ndarray,
614
+ frame_length: int,
615
+ hop_length: int,
616
+ fft_length: Optional[int] = None,
617
+ power: Optional[float] = 1.0,
618
+ center: bool = True,
619
+ pad_mode: str = "reflect",
620
+ onesided: bool = True,
621
+ dither: float = 0.0,
622
+ preemphasis: Optional[float] = None,
623
+ mel_filters: Optional[np.ndarray] = None,
624
+ mel_floor: float = 1e-10,
625
+ log_mel: Optional[str] = None,
626
+ reference: float = 1.0,
627
+ min_value: float = 1e-10,
628
+ db_range: Optional[float] = None,
629
+ remove_dc_offset: Optional[bool] = None,
630
+ dtype: np.dtype = np.float32,
631
+ ) -> np.ndarray:
632
+ """
633
+ Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
634
+
635
+ This function can create the following kinds of spectrograms:
636
+
637
+ - amplitude spectrogram (`power = 1.0`)
638
+ - power spectrogram (`power = 2.0`)
639
+ - complex-valued spectrogram (`power = None`)
640
+ - log spectrogram (use `log_mel` argument)
641
+ - mel spectrogram (provide `mel_filters`)
642
+ - log-mel spectrogram (provide `mel_filters` and `log_mel`)
643
+
644
+ How this works:
645
+
646
+ 1. The input waveform is split into frames of size `frame_length` that are partially overlapping by `frame_length
647
+ - hop_length` samples.
648
+ 2. Each frame is multiplied by the window and placed into a buffer of size `fft_length`.
649
+ 3. The DFT is taken of each windowed frame.
650
+ 4. The results are stacked into a spectrogram.
651
+
652
+ We make a distinction between the following "blocks" of sample data, each of which may have a different lengths:
653
+
654
+ - The analysis frame. This is the size of the time slices that the input waveform is split into.
655
+ - The window. Each analysis frame is multiplied by the window to avoid spectral leakage.
656
+ - The FFT input buffer. The length of this determines how many frequency bins are in the spectrogram.
657
+
658
+ In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. A
659
+ padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
660
+ typically the next power of two.
661
+
662
+ Note: This function is not optimized for speed yet. It should be mostly compatible with `librosa.stft` and
663
+ `torchaudio.functional.transforms.Spectrogram`, although it is more flexible due to the different ways spectrograms
664
+ can be constructed.
665
+
666
+ Args:
667
+ waveform (`np.ndarray` of shape `(length,)`):
668
+ The input waveform. This must be a single real-valued, mono waveform.
669
+ window (`np.ndarray` of shape `(frame_length,)`):
670
+ The windowing function to apply, including zero-padding if necessary. The actual window length may be
671
+ shorter than `frame_length`, but we're assuming the array has already been zero-padded.
672
+ frame_length (`int`):
673
+ The length of the analysis frames in samples. With librosa this is always equal to `fft_length` but we also
674
+ allow smaller sizes.
675
+ hop_length (`int`):
676
+ The stride between successive analysis frames in samples.
677
+ fft_length (`int`, *optional*):
678
+ The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.
679
+ For optimal speed, this should be a power of two. If `None`, uses `frame_length`.
680
+ power (`float`, *optional*, defaults to 1.0):
681
+ If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `None`, returns
682
+ complex numbers.
683
+ center (`bool`, *optional*, defaults to `True`):
684
+ Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame
685
+ `t` will start at time `t * hop_length`.
686
+ pad_mode (`str`, *optional*, defaults to `"reflect"`):
687
+ Padding mode used when `center` is `True`. Possible values are: `"constant"` (pad with zeros), `"edge"`
688
+ (pad with edge values), `"reflect"` (pads with mirrored values).
689
+ onesided (`bool`, *optional*, defaults to `True`):
690
+ If True, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`
691
+ frequency bins. If False, also computes the negative frequencies and returns `fft_length` frequency bins.
692
+ dither (`float`, *optional*, defaults to 0.0):
693
+ Adds dithering. In other words, adds a small Gaussian noise to each frame.
694
+ E.g. use 4.0 to add dithering with a normal distribution centered
695
+ around 0.0 with standard deviation 4.0, 0.0 means no dithering.
696
+ Dithering has similar effect as `mel_floor`. It reduces the high log_mel_fbank
697
+ values for signals with hard-zero sections, when VAD cutoff is present in the signal.
698
+ preemphasis (`float`, *optional*)
699
+ Coefficient for a low-pass filter that applies pre-emphasis before the DFT.
700
+ mel_filters (`np.ndarray` of shape `(num_freq_bins, num_mel_filters)`, *optional*):
701
+ The mel filter bank. If supplied, applies a this filter bank to create a mel spectrogram.
702
+ mel_floor (`float`, *optional*, defaults to 1e-10):
703
+ Minimum value of mel frequency banks.
704
+ log_mel (`str`, *optional*):
705
+ How to convert the spectrogram to log scale. Possible options are: `None` (don't convert), `"log"` (take
706
+ the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). Can only be
707
+ used when `power` is not `None`.
708
+ reference (`float`, *optional*, defaults to 1.0):
709
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
710
+ the loudest part to 0 dB. Must be greater than zero.
711
+ min_value (`float`, *optional*, defaults to `1e-10`):
712
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
713
+ `log(0)`. For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an
714
+ amplitude spectrogram, the value `1e-5` corresponds to -100 dB. Must be greater than zero.
715
+ db_range (`float`, *optional*):
716
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
717
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
718
+ remove_dc_offset (`bool`, *optional*):
719
+ Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in
720
+ order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.
721
+ dtype (`np.dtype`, *optional*, defaults to `np.float32`):
722
+ Data type of the spectrogram tensor. If `power` is None, this argument is ignored and the dtype will be
723
+ `np.complex64`.
724
+
725
+ Returns:
726
+ `nd.array` containing a spectrogram of shape `(num_frequency_bins, length)` for a regular spectrogram or shape
727
+ `(num_mel_filters, length)` for a mel spectrogram.
728
+ """
729
+ window_length = len(window)
730
+
731
+ if fft_length is None:
732
+ fft_length = frame_length
733
+
734
+ if frame_length > fft_length:
735
+ raise ValueError(f"frame_length ({frame_length}) may not be larger than fft_length ({fft_length})")
736
+
737
+ if window_length != frame_length:
738
+ raise ValueError(f"Length of the window ({window_length}) must equal frame_length ({frame_length})")
739
+
740
+ if hop_length <= 0:
741
+ raise ValueError("hop_length must be greater than zero")
742
+
743
+ if waveform.ndim != 1:
744
+ raise ValueError(f"Input waveform must have only one dimension, shape is {waveform.shape}")
745
+
746
+ if np.iscomplexobj(waveform):
747
+ raise ValueError("Complex-valued input waveforms are not currently supported")
748
+
749
+ if power is None and mel_filters is not None:
750
+ raise ValueError(
751
+ "You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram."
752
+ "Specify `power` to fix this issue."
753
+ )
754
+
755
+ # center pad the waveform
756
+ if center:
757
+ padding = [(int(frame_length // 2), int(frame_length // 2))]
758
+ waveform = np.pad(waveform, padding, mode=pad_mode)
759
+
760
+ # promote to float64, since np.fft uses float64 internally
761
+ waveform = waveform.astype(np.float64)
762
+ window = window.astype(np.float64)
763
+
764
+ # split waveform into frames of frame_length size
765
+ num_frames = int(1 + np.floor((waveform.size - frame_length) / hop_length))
766
+
767
+ num_frequency_bins = (fft_length // 2) + 1 if onesided else fft_length
768
+ spectrogram = np.empty((num_frames, num_frequency_bins), dtype=np.complex64)
769
+
770
+ # rfft is faster than fft
771
+ fft_func = np.fft.rfft if onesided else np.fft.fft
772
+ buffer = np.zeros(fft_length)
773
+
774
+ timestep = 0
775
+ for frame_idx in range(num_frames):
776
+ buffer[:frame_length] = waveform[timestep : timestep + frame_length]
777
+
778
+ if dither != 0.0:
779
+ buffer[:frame_length] += dither * np.random.randn(frame_length)
780
+
781
+ if remove_dc_offset:
782
+ buffer[:frame_length] = buffer[:frame_length] - buffer[:frame_length].mean()
783
+
784
+ if preemphasis is not None:
785
+ buffer[1:frame_length] -= preemphasis * buffer[: frame_length - 1]
786
+ buffer[0] *= 1 - preemphasis
787
+
788
+ buffer[:frame_length] *= window
789
+
790
+ spectrogram[frame_idx] = fft_func(buffer)
791
+ timestep += hop_length
792
+
793
+ # note: ** is much faster than np.power
794
+ if power is not None:
795
+ spectrogram = np.abs(spectrogram, dtype=np.float64) ** power
796
+
797
+ spectrogram = spectrogram.T
798
+
799
+ if mel_filters is not None:
800
+ spectrogram = np.maximum(mel_floor, np.dot(mel_filters.T, spectrogram))
801
+
802
+ if power is not None and log_mel is not None:
803
+ if log_mel == "log":
804
+ spectrogram = np.log(spectrogram)
805
+ elif log_mel == "log10":
806
+ spectrogram = np.log10(spectrogram)
807
+ elif log_mel == "dB":
808
+ if power == 1.0:
809
+ spectrogram = amplitude_to_db(spectrogram, reference, min_value, db_range)
810
+ elif power == 2.0:
811
+ spectrogram = power_to_db(spectrogram, reference, min_value, db_range)
812
+ else:
813
+ raise ValueError(f"Cannot use log_mel option '{log_mel}' with power {power}")
814
+ else:
815
+ raise ValueError(f"Unknown log_mel option: {log_mel}")
816
+
817
+ spectrogram = np.asarray(spectrogram, dtype)
818
+
819
+ return spectrogram
820
+
821
+
822
+ def spectrogram_batch(
823
+ waveform_list: list[np.ndarray],
824
+ window: np.ndarray,
825
+ frame_length: int,
826
+ hop_length: int,
827
+ fft_length: Optional[int] = None,
828
+ power: Optional[float] = 1.0,
829
+ center: bool = True,
830
+ pad_mode: str = "reflect",
831
+ onesided: bool = True,
832
+ dither: float = 0.0,
833
+ preemphasis: Optional[float] = None,
834
+ mel_filters: Optional[np.ndarray] = None,
835
+ mel_floor: float = 1e-10,
836
+ log_mel: Optional[str] = None,
837
+ reference: float = 1.0,
838
+ min_value: float = 1e-10,
839
+ db_range: Optional[float] = None,
840
+ remove_dc_offset: Optional[bool] = None,
841
+ dtype: np.dtype = np.float32,
842
+ ) -> list[np.ndarray]:
843
+ """
844
+ Calculates spectrograms for a list of waveforms using the Short-Time Fourier Transform, optimized for batch processing.
845
+ This function extends the capabilities of the `spectrogram` function to handle multiple waveforms efficiently by leveraging broadcasting.
846
+
847
+ It supports generating various types of spectrograms:
848
+
849
+ - amplitude spectrogram (`power = 1.0`)
850
+ - power spectrogram (`power = 2.0`)
851
+ - complex-valued spectrogram (`power = None`)
852
+ - log spectrogram (use `log_mel` argument)
853
+ - mel spectrogram (provide `mel_filters`)
854
+ - log-mel spectrogram (provide `mel_filters` and `log_mel`)
855
+
856
+ How this works:
857
+
858
+ 1. The input waveform is split into frames of size `frame_length` that are partially overlapping by `frame_length
859
+ - hop_length` samples.
860
+ 2. Each frame is multiplied by the window and placed into a buffer of size `fft_length`.
861
+ 3. The DFT is taken of each windowed frame.
862
+ 4. The results are stacked into a spectrogram.
863
+
864
+ We make a distinction between the following "blocks" of sample data, each of which may have a different lengths:
865
+
866
+ - The analysis frame. This is the size of the time slices that the input waveform is split into.
867
+ - The window. Each analysis frame is multiplied by the window to avoid spectral leakage.
868
+ - The FFT input buffer. The length of this determines how many frequency bins are in the spectrogram.
869
+
870
+ In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. A
871
+ padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
872
+ typically the next power of two.
873
+
874
+ Note: This function is designed for efficient batch processing of multiple waveforms but retains compatibility with individual waveform processing methods like `librosa.stft`.
875
+
876
+ Args:
877
+ waveform_list (`list[np.ndarray]` with arrays of shape `(length,)`):
878
+ The list of input waveforms, each a single-channel (mono) signal.
879
+ window (`np.ndarray` of shape `(frame_length,)`):
880
+ The windowing function to apply, including zero-padding if necessary.
881
+ frame_length (`int`):
882
+ The length of each frame for analysis.
883
+ hop_length (`int`):
884
+ The step size between successive frames.
885
+ fft_length (`int`, *optional*):
886
+ The size of the FFT buffer, defining frequency bin resolution.
887
+ power (`float`, *optional*, defaults to 1.0):
888
+ Determines the type of spectrogram: 1.0 for amplitude, 2.0 for power, None for complex.
889
+ center (`bool`, *optional*, defaults to `True`):
890
+ Whether to center-pad the waveform frames.
891
+ pad_mode (`str`, *optional*, defaults to `"reflect"`):
892
+ The padding strategy when `center` is `True`.
893
+ onesided (`bool`, *optional*, defaults to `True`):
894
+ If True, returns a one-sided spectrogram for real input signals.
895
+ dither (`float`, *optional*, defaults to 0.0):
896
+ Adds dithering. In other words, adds a small Gaussian noise to each frame.
897
+ E.g. use 4.0 to add dithering with a normal distribution centered
898
+ around 0.0 with standard deviation 4.0, 0.0 means no dithering.
899
+ preemphasis (`float`, *optional*):
900
+ Applies a pre-emphasis filter to each frame.
901
+ mel_filters (`np.ndarray`, *optional*):
902
+ Mel filter bank for converting to mel spectrogram.
903
+ mel_floor (`float`, *optional*, defaults to 1e-10):
904
+ Floor value for mel spectrogram to avoid log(0).
905
+ log_mel (`str`, *optional*):
906
+ Specifies log scaling strategy; options are None, "log", "log10", "dB".
907
+ reference (`float`, *optional*, defaults to 1.0):
908
+ Reference value for dB conversion in log_mel.
909
+ min_value (`float`, *optional*, defaults to 1e-10):
910
+ Minimum floor value for log scale conversions.
911
+ db_range (`float`, *optional*):
912
+ Dynamic range for dB scale spectrograms.
913
+ remove_dc_offset (`bool`, *optional*):
914
+ Whether to remove the DC offset from each frame.
915
+ dtype (`np.dtype`, *optional*, defaults to `np.float32`):
916
+ Data type of the output spectrogram.
917
+
918
+ Returns:
919
+ list[`np.ndarray`]: A list of spectrogram arrays, one for each input waveform.
920
+ """
921
+ window_length = len(window)
922
+
923
+ if fft_length is None:
924
+ fft_length = frame_length
925
+
926
+ if frame_length > fft_length:
927
+ raise ValueError(f"frame_length ({frame_length}) may not be larger than fft_length ({fft_length})")
928
+
929
+ if window_length != frame_length:
930
+ raise ValueError(f"Length of the window ({window_length}) must equal frame_length ({frame_length})")
931
+
932
+ if hop_length <= 0:
933
+ raise ValueError("hop_length must be greater than zero")
934
+
935
+ # Check the dimensions of the waveform , and if waveform is complex
936
+ for waveform in waveform_list:
937
+ if waveform.ndim != 1:
938
+ raise ValueError(f"Input waveform must have only one dimension, shape is {waveform.shape}")
939
+ if np.iscomplexobj(waveform):
940
+ raise ValueError("Complex-valued input waveforms are not currently supported")
941
+ # Center pad the waveform
942
+ if center:
943
+ padding = [(int(frame_length // 2), int(frame_length // 2))]
944
+ waveform_list = [
945
+ np.pad(
946
+ waveform,
947
+ padding,
948
+ mode=pad_mode,
949
+ )
950
+ for waveform in waveform_list
951
+ ]
952
+ original_waveform_lengths = [
953
+ len(waveform) for waveform in waveform_list
954
+ ] # these lengths will be used to remove padding later
955
+
956
+ # Batch pad the waveform
957
+ max_length = max(original_waveform_lengths)
958
+ padded_waveform_batch = np.array(
959
+ [
960
+ np.pad(waveform, (0, max_length - len(waveform)), mode="constant", constant_values=0)
961
+ for waveform in waveform_list
962
+ ],
963
+ dtype=dtype,
964
+ )
965
+
966
+ # Promote to float64, since np.fft uses float64 internally
967
+ padded_waveform_batch = padded_waveform_batch.astype(np.float64)
968
+ window = window.astype(np.float64)
969
+
970
+ # Split waveform into frames of frame_length size
971
+ num_frames = int(1 + np.floor((padded_waveform_batch.shape[1] - frame_length) / hop_length))
972
+ # these lengths will be used to remove padding later
973
+ true_num_frames = [int(1 + np.floor((length - frame_length) / hop_length)) for length in original_waveform_lengths]
974
+ num_batches = padded_waveform_batch.shape[0]
975
+
976
+ num_frequency_bins = (fft_length // 2) + 1 if onesided else fft_length
977
+ spectrogram = np.empty((num_batches, num_frames, num_frequency_bins), dtype=np.complex64)
978
+
979
+ # rfft is faster than fft
980
+ fft_func = np.fft.rfft if onesided else np.fft.fft
981
+ buffer = np.zeros((num_batches, fft_length))
982
+
983
+ for frame_idx in range(num_frames):
984
+ timestep = frame_idx * hop_length
985
+ buffer[:, :frame_length] = padded_waveform_batch[:, timestep : timestep + frame_length]
986
+
987
+ if dither != 0.0:
988
+ buffer[:, :frame_length] += dither * np.random.randn(*buffer[:, :frame_length].shape)
989
+
990
+ if remove_dc_offset:
991
+ buffer[:, :frame_length] -= buffer[:, :frame_length].mean(axis=1, keepdims=True)
992
+
993
+ if preemphasis is not None:
994
+ buffer[:, 1:frame_length] -= preemphasis * buffer[:, : frame_length - 1]
995
+ buffer[:, 0] *= 1 - preemphasis
996
+
997
+ buffer[:, :frame_length] *= window
998
+
999
+ spectrogram[:, frame_idx] = fft_func(buffer)
1000
+
1001
+ # Note: ** is much faster than np.power
1002
+ if power is not None:
1003
+ spectrogram = np.abs(spectrogram, dtype=np.float64) ** power
1004
+
1005
+ # Apply mel filters if provided
1006
+ if mel_filters is not None:
1007
+ result = np.tensordot(spectrogram, mel_filters.T, axes=([2], [1]))
1008
+ spectrogram = np.maximum(mel_floor, result)
1009
+
1010
+ # Convert to log scale if specified
1011
+ if power is not None and log_mel is not None:
1012
+ if log_mel == "log":
1013
+ spectrogram = np.log(spectrogram)
1014
+ elif log_mel == "log10":
1015
+ spectrogram = np.log10(spectrogram)
1016
+ elif log_mel == "dB":
1017
+ if power == 1.0:
1018
+ spectrogram = amplitude_to_db_batch(spectrogram, reference, min_value, db_range)
1019
+ elif power == 2.0:
1020
+ spectrogram = power_to_db_batch(spectrogram, reference, min_value, db_range)
1021
+ else:
1022
+ raise ValueError(f"Cannot use log_mel option '{log_mel}' with power {power}")
1023
+ else:
1024
+ raise ValueError(f"Unknown log_mel option: {log_mel}")
1025
+
1026
+ spectrogram = np.asarray(spectrogram, dtype)
1027
+
1028
+ spectrogram_list = [spectrogram[i, : true_num_frames[i], :].T for i in range(len(true_num_frames))]
1029
+
1030
+ return spectrogram_list
1031
+
1032
+
1033
+ def power_to_db(
1034
+ spectrogram: np.ndarray,
1035
+ reference: float = 1.0,
1036
+ min_value: float = 1e-10,
1037
+ db_range: Optional[float] = None,
1038
+ ) -> np.ndarray:
1039
+ """
1040
+ Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`, using basic
1041
+ logarithm properties for numerical stability.
1042
+
1043
+ The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
1044
+ linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
1045
+ This means that large variations in energy may not sound all that different if the sound is loud to begin with.
1046
+ This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
1047
+
1048
+ Based on the implementation of `librosa.power_to_db`.
1049
+
1050
+ Args:
1051
+ spectrogram (`np.ndarray`):
1052
+ The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!
1053
+ reference (`float`, *optional*, defaults to 1.0):
1054
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
1055
+ the loudest part to 0 dB. Must be greater than zero.
1056
+ min_value (`float`, *optional*, defaults to `1e-10`):
1057
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
1058
+ `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
1059
+ db_range (`float`, *optional*):
1060
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
1061
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
1062
+
1063
+ Returns:
1064
+ `np.ndarray`: the spectrogram in decibels
1065
+ """
1066
+ if reference <= 0.0:
1067
+ raise ValueError("reference must be greater than zero")
1068
+ if min_value <= 0.0:
1069
+ raise ValueError("min_value must be greater than zero")
1070
+
1071
+ reference = max(min_value, reference)
1072
+
1073
+ spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
1074
+ spectrogram = 10.0 * (np.log10(spectrogram) - np.log10(reference))
1075
+
1076
+ if db_range is not None:
1077
+ if db_range <= 0.0:
1078
+ raise ValueError("db_range must be greater than zero")
1079
+ spectrogram = np.clip(spectrogram, a_min=spectrogram.max() - db_range, a_max=None)
1080
+
1081
+ return spectrogram
1082
+
1083
+
1084
+ def power_to_db_batch(
1085
+ spectrogram: np.ndarray,
1086
+ reference: float = 1.0,
1087
+ min_value: float = 1e-10,
1088
+ db_range: Optional[float] = None,
1089
+ ) -> np.ndarray:
1090
+ """
1091
+ Converts a batch of power spectrograms to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
1092
+ using basic logarithm properties for numerical stability.
1093
+
1094
+ This function supports batch processing, where each item in the batch is an individual power (mel) spectrogram.
1095
+
1096
+ Args:
1097
+ spectrogram (`np.ndarray`):
1098
+ The input batch of power (mel) spectrograms. Expected shape is (batch_size, *spectrogram_shape).
1099
+ Note that a power spectrogram has the amplitudes squared!
1100
+ reference (`float`, *optional*, defaults to 1.0):
1101
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
1102
+ the loudest part to 0 dB. Must be greater than zero.
1103
+ min_value (`float`, *optional*, defaults to `1e-10`):
1104
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
1105
+ `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
1106
+ db_range (`float`, *optional*):
1107
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
1108
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
1109
+
1110
+ Returns:
1111
+ `np.ndarray`: the batch of spectrograms in decibels
1112
+ """
1113
+ if reference <= 0.0:
1114
+ raise ValueError("reference must be greater than zero")
1115
+ if min_value <= 0.0:
1116
+ raise ValueError("min_value must be greater than zero")
1117
+
1118
+ reference = max(min_value, reference)
1119
+
1120
+ spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
1121
+ spectrogram = 10.0 * (np.log10(spectrogram) - np.log10(reference))
1122
+
1123
+ if db_range is not None:
1124
+ if db_range <= 0.0:
1125
+ raise ValueError("db_range must be greater than zero")
1126
+ # Apply db_range clipping per batch item
1127
+ max_values = spectrogram.max(axis=(1, 2), keepdims=True)
1128
+ spectrogram = np.clip(spectrogram, a_min=max_values - db_range, a_max=None)
1129
+
1130
+ return spectrogram
1131
+
1132
+
1133
+ def amplitude_to_db(
1134
+ spectrogram: np.ndarray,
1135
+ reference: float = 1.0,
1136
+ min_value: float = 1e-5,
1137
+ db_range: Optional[float] = None,
1138
+ ) -> np.ndarray:
1139
+ """
1140
+ Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`, using
1141
+ basic logarithm properties for numerical stability.
1142
+
1143
+ The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
1144
+ linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
1145
+ This means that large variations in energy may not sound all that different if the sound is loud to begin with.
1146
+ This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
1147
+
1148
+ Args:
1149
+ spectrogram (`np.ndarray`):
1150
+ The input amplitude (mel) spectrogram.
1151
+ reference (`float`, *optional*, defaults to 1.0):
1152
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
1153
+ the loudest part to 0 dB. Must be greater than zero.
1154
+ min_value (`float`, *optional*, defaults to `1e-5`):
1155
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
1156
+ `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
1157
+ db_range (`float`, *optional*):
1158
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
1159
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
1160
+
1161
+ Returns:
1162
+ `np.ndarray`: the spectrogram in decibels
1163
+ """
1164
+ if reference <= 0.0:
1165
+ raise ValueError("reference must be greater than zero")
1166
+ if min_value <= 0.0:
1167
+ raise ValueError("min_value must be greater than zero")
1168
+
1169
+ reference = max(min_value, reference)
1170
+
1171
+ spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
1172
+ spectrogram = 20.0 * (np.log10(spectrogram) - np.log10(reference))
1173
+
1174
+ if db_range is not None:
1175
+ if db_range <= 0.0:
1176
+ raise ValueError("db_range must be greater than zero")
1177
+ spectrogram = np.clip(spectrogram, a_min=spectrogram.max() - db_range, a_max=None)
1178
+
1179
+ return spectrogram
1180
+
1181
+
1182
+ def amplitude_to_db_batch(
1183
+ spectrogram: np.ndarray, reference: float = 1.0, min_value: float = 1e-5, db_range: Optional[float] = None
1184
+ ) -> np.ndarray:
1185
+ """
1186
+ Converts a batch of amplitude spectrograms to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
1187
+ using basic logarithm properties for numerical stability.
1188
+
1189
+ The function supports batch processing, where each item in the batch is an individual amplitude (mel) spectrogram.
1190
+
1191
+ Args:
1192
+ spectrogram (`np.ndarray`):
1193
+ The input batch of amplitude (mel) spectrograms. Expected shape is (batch_size, *spectrogram_shape).
1194
+ reference (`float`, *optional*, defaults to 1.0):
1195
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
1196
+ the loudest part to 0 dB. Must be greater than zero.
1197
+ min_value (`float`, *optional*, defaults to `1e-5`):
1198
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
1199
+ `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
1200
+ db_range (`float`, *optional*):
1201
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
1202
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
1203
+
1204
+ Returns:
1205
+ `np.ndarray`: the batch of spectrograms in decibels
1206
+ """
1207
+ if reference <= 0.0:
1208
+ raise ValueError("reference must be greater than zero")
1209
+ if min_value <= 0.0:
1210
+ raise ValueError("min_value must be greater than zero")
1211
+
1212
+ reference = max(min_value, reference)
1213
+
1214
+ spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
1215
+ spectrogram = 20.0 * (np.log10(spectrogram) - np.log10(reference))
1216
+
1217
+ if db_range is not None:
1218
+ if db_range <= 0.0:
1219
+ raise ValueError("db_range must be greater than zero")
1220
+ # Apply db_range clipping per batch item
1221
+ max_values = spectrogram.max(axis=(1, 2), keepdims=True)
1222
+ spectrogram = np.clip(spectrogram, a_min=max_values - db_range, a_max=None)
1223
+
1224
+ return spectrogram
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/cache_utils.py ADDED
@@ -0,0 +1,1516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Iterable
3
+ from typing import Any, Optional
4
+
5
+ import torch
6
+
7
+ from .configuration_utils import PretrainedConfig
8
+ from .utils import (
9
+ is_hqq_available,
10
+ is_quanto_greater,
11
+ is_torch_greater_or_equal,
12
+ is_torchdynamo_compiling,
13
+ logging,
14
+ )
15
+
16
+
17
+ if is_hqq_available():
18
+ from hqq.core.quantize import Quantizer as HQQQuantizer
19
+
20
+ _is_torch_greater_or_equal_than_2_7 = is_torch_greater_or_equal("2.7", accept_dev=True)
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class CacheLayerMixin(ABC):
27
+ """Base, abstract class for a single layer's cache."""
28
+
29
+ is_compileable = False
30
+
31
+ def __init__(self):
32
+ self.keys, self.values = None, None
33
+
34
+ def __repr__(self):
35
+ return f"{self.__class__.__name__}"
36
+
37
+ @abstractmethod
38
+ def lazy_initialization(self, key_states: torch.Tensor): ...
39
+
40
+ @abstractmethod
41
+ def update(
42
+ self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None
43
+ ) -> tuple[torch.Tensor, torch.Tensor]: ...
44
+
45
+ @abstractmethod
46
+ def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: ...
47
+
48
+ @abstractmethod
49
+ def get_seq_length(self) -> int: ...
50
+
51
+ @abstractmethod
52
+ def get_max_cache_shape(self) -> int: ...
53
+
54
+ def offload(self):
55
+ """Offload this layer's data to CPU device."""
56
+ if self.keys is not None:
57
+ self.keys = self.keys.to("cpu", non_blocking=True)
58
+ self.values = self.values.to("cpu", non_blocking=True)
59
+
60
+ def prefetch(self):
61
+ """In case of layer offloading, this allows to move the data back to the layer's device ahead of time."""
62
+ if self.keys is not None and self.keys.device != self.device:
63
+ self.keys = self.keys.to(self.device, non_blocking=True)
64
+ self.values = self.values.to(self.device, non_blocking=True)
65
+
66
+ def reset(self) -> None:
67
+ """Resets the cache values while preserving the objects"""
68
+ if self.keys is not None:
69
+ self.keys.zero_()
70
+ self.values.zero_()
71
+ # This attribute is set on several Layers
72
+ if hasattr(self, "cumulative_length"):
73
+ self.cumulative_length = 0
74
+
75
+ def reorder_cache(self, beam_idx: torch.LongTensor) -> None:
76
+ """Reorders this layer's cache for beam search."""
77
+ if self.get_seq_length() > 0:
78
+ self.keys = self.keys.index_select(0, beam_idx.to(self.keys.device))
79
+ self.values = self.values.index_select(0, beam_idx.to(self.values.device))
80
+
81
+
82
+ class DynamicLayer(CacheLayerMixin):
83
+ """
84
+ A cache layer that grows dynamically as more tokens are generated. This is the default for generative models.
85
+ It stores the key and value states as tensors of shape `[batch_size, num_heads, seq_len, head_dim]`.
86
+ """
87
+
88
+ is_sliding = False
89
+
90
+ def lazy_initialization(self, key_states: torch.Tensor):
91
+ self.dtype, self.device = key_states.dtype, key_states.device
92
+ self.keys = torch.tensor([], dtype=self.dtype, device=self.device)
93
+ self.values = torch.tensor([], dtype=self.dtype, device=self.device)
94
+
95
+ def update(
96
+ self,
97
+ key_states: torch.Tensor,
98
+ value_states: torch.Tensor,
99
+ cache_kwargs: Optional[dict[str, Any]] = None,
100
+ ) -> tuple[torch.Tensor, torch.Tensor]:
101
+ """
102
+ Update the key and value caches in-place, and return the necessary keys and value states.
103
+
104
+ Args:
105
+ key_states (`torch.Tensor`): The new key states to cache.
106
+ value_states (`torch.Tensor`): The new value states to cache.
107
+ cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
108
+
109
+ Returns:
110
+ tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
111
+ """
112
+ # Lazy initialization
113
+ if self.keys is None:
114
+ self.lazy_initialization(key_states)
115
+
116
+ self.keys = torch.cat([self.keys, key_states], dim=-2)
117
+ self.values = torch.cat([self.values, value_states], dim=-2)
118
+ return self.keys, self.values
119
+
120
+ def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]:
121
+ """Return the length and offset of the cache, used to generate the mask"""
122
+ kv_offset = 0
123
+ query_length = cache_position.shape[0]
124
+ past_seen_tokens = self.get_seq_length()
125
+ kv_length = query_length + past_seen_tokens
126
+ return kv_length, kv_offset
127
+
128
+ def get_seq_length(self) -> int:
129
+ """Returns the sequence length of the cached states."""
130
+ if self.keys is None or self.keys.numel() == 0:
131
+ return 0
132
+ return self.keys.shape[-2]
133
+
134
+ def get_max_cache_shape(self) -> int:
135
+ """Returns the maximum sequence length of the cache object. DynamicLayer does not have a maximum length."""
136
+ return -1
137
+
138
+ def crop(self, max_length: int) -> None:
139
+ """
140
+ Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be negative
141
+ to remove `max_length` tokens.
142
+ """
143
+ if max_length < 0:
144
+ max_length = self.get_seq_length() - abs(max_length)
145
+
146
+ if self.get_seq_length() <= max_length:
147
+ return
148
+
149
+ self.keys = self.keys[..., :max_length, :]
150
+ self.values = self.values[..., :max_length, :]
151
+
152
+ def batch_repeat_interleave(self, repeats: int) -> None:
153
+ """Repeat the cache `repeats` times in the batch dimension."""
154
+ if self.get_seq_length() > 0:
155
+ self.keys = self.keys.repeat_interleave(repeats, dim=0)
156
+ self.values = self.values.repeat_interleave(repeats, dim=0)
157
+
158
+ def batch_select_indices(self, indices: torch.Tensor) -> None:
159
+ """Only keep the `indices` in the batch dimension of the cache."""
160
+ if self.get_seq_length() > 0:
161
+ self.keys = self.keys[indices, ...]
162
+ self.values = self.values[indices, ...]
163
+
164
+
165
+ class DynamicSlidingWindowLayer(DynamicLayer):
166
+ """
167
+ A cache layer that grows dynamically as more tokens are generated, up until the sliding window size.
168
+ It stores the key and value states as tensors of shape `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
169
+ """
170
+
171
+ is_sliding = True
172
+
173
+ def __init__(self, sliding_window: int):
174
+ super().__init__()
175
+ self.sliding_window = sliding_window
176
+ self.cumulative_length = 0
177
+
178
+ def update(
179
+ self,
180
+ key_states: torch.Tensor,
181
+ value_states: torch.Tensor,
182
+ cache_kwargs: Optional[dict[str, Any]] = None,
183
+ ) -> tuple[torch.Tensor, torch.Tensor]:
184
+ """
185
+ Update the key and value caches in-place, and return the necessary keys and value states.
186
+
187
+ Args:
188
+ key_states (`torch.Tensor`): The new key states to cache.
189
+ value_states (`torch.Tensor`): The new value states to cache.
190
+ cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
191
+
192
+ Returns:
193
+ tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
194
+ """
195
+ # Lazy initialization
196
+ if self.keys is None:
197
+ self.lazy_initialization(key_states)
198
+
199
+ self.cumulative_length += key_states.shape[-2]
200
+
201
+ # Compute the full states
202
+ full_key_states = torch.cat([self.keys, key_states], dim=-2)
203
+ full_value_states = torch.cat([self.values, value_states], dim=-2)
204
+ # Only cache the last `self.sliding_window - 1` tokens (or all of them if lower than that)
205
+ self.keys = full_key_states[:, :, -self.sliding_window + 1 :, :]
206
+ self.values = full_value_states[:, :, -self.sliding_window + 1 :, :]
207
+
208
+ # Return the full states
209
+ return full_key_states, full_value_states
210
+
211
+ def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]:
212
+ """Return the length and offset of the cache, used to generate the attention mask"""
213
+ query_length = cache_position.shape[0]
214
+ first_cache_position = cache_position[0]
215
+
216
+ kv_offset = torch.clamp(first_cache_position - self.sliding_window + 1, min=0)
217
+
218
+ if self.get_seq_length() >= self.sliding_window:
219
+ kv_length = self.sliding_window - 1 + query_length
220
+ else:
221
+ kv_length = self.get_seq_length() + query_length
222
+
223
+ return kv_length, kv_offset
224
+
225
+ def get_seq_length(self) -> int:
226
+ """Returns the sequence length of the cached states."""
227
+ return self.cumulative_length
228
+
229
+ def get_max_cache_shape(self) -> int:
230
+ """Return the maximum cache shape of the cache"""
231
+ return self.sliding_window
232
+
233
+ def crop(self, max_length: int) -> None:
234
+ """
235
+ Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
236
+ negative to remove `max_length` tokens.
237
+ """
238
+ if self.get_seq_length() >= self.sliding_window:
239
+ raise ValueError(
240
+ "Cannot `crop` a `DynamicSlidingWindowLayer` after it has seen more tokens than its"
241
+ "sliding window (otherwise some states are lost)"
242
+ )
243
+ super().crop(max_length)
244
+ self.cumulative_length = self.keys.shape[-2]
245
+
246
+
247
+ class StaticLayer(CacheLayerMixin):
248
+ """
249
+ A static cache layer that stores the key and value states as static tensors of shape `[batch_size, num_heads, max_cache_len), head_dim]`.
250
+ It lazily allocates its full backing tensors, and then mutates them in-place. Built for `torch.compile` support.
251
+
252
+ Args:
253
+ max_cache_len (`int`):
254
+ Maximum number of tokens that can be stored, used for tensor preallocation.
255
+ """
256
+
257
+ is_compileable = True
258
+ is_sliding = False
259
+
260
+ def __init__(self, max_cache_len: int):
261
+ super().__init__()
262
+ self.max_cache_len = max_cache_len
263
+
264
+ def lazy_initialization(self, key_states: torch.Tensor):
265
+ """
266
+ Lazy initialization of the keys and values tensors. This allows to get all properties (dtype, device,
267
+ num_heads in case of TP etc...) at runtime directly, which is extremely practical as it avoids moving
268
+ devices, dtypes etc later on for each `update` (which could break the static dynamo addresses as well).
269
+
270
+ If this is unwanted, one can call `early_initialization(...)` on the Cache directly, which will call this
271
+ function ahead-of-time (this is required for `torch.export` for example). Note that for `compile`, as we
272
+ internally don't compile the prefill, this is guaranteed to have been called already when compiling.
273
+ If compiling the prefill as well, e.g. calling `model.compile(...)` before `generate` with a static cache,
274
+ it is still supported in general, but without guarantees depending on the compilation options (e.g. cuda graphs,
275
+ i.e. `mode="reduce-overhead"` is known to fail). But it will in general work correctly, and prefill should
276
+ not be compiled anyway for performances!
277
+ """
278
+ self.max_batch_size, self.num_heads, _, self.head_dim = key_states.shape
279
+ self.dtype, self.device = key_states.dtype, key_states.device
280
+
281
+ self.keys = torch.zeros(
282
+ (self.max_batch_size, self.num_heads, self.max_cache_len, self.head_dim),
283
+ dtype=self.dtype,
284
+ device=self.device,
285
+ )
286
+ self.values = torch.zeros(
287
+ (self.max_batch_size, self.num_heads, self.max_cache_len, self.head_dim),
288
+ dtype=self.dtype,
289
+ device=self.device,
290
+ )
291
+ # Note: `mark_static_address` is used to tag the cache as a fixed data pointer, preventing compiled graph
292
+ # breaks when updating the cache. However, it is not supported when tracing the graph, so we skip it in this case.
293
+ # As prefill should never be compiled, this is not an issue and it will still be run (except when users compile
294
+ # prefill explicitly, but this should be avoided!)
295
+ if not is_torchdynamo_compiling():
296
+ torch._dynamo.mark_static_address(self.keys)
297
+ torch._dynamo.mark_static_address(self.values)
298
+
299
+ def update(
300
+ self,
301
+ key_states: torch.Tensor,
302
+ value_states: torch.Tensor,
303
+ cache_kwargs: Optional[dict[str, Any]] = None,
304
+ ) -> tuple[torch.Tensor, torch.Tensor]:
305
+ """
306
+ Update the key and value caches in-place, and return the necessary keys and value states.
307
+
308
+ Args:
309
+ key_states (`torch.Tensor`): The new key states to cache.
310
+ value_states (`torch.Tensor`): The new value states to cache.
311
+ cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
312
+
313
+ Returns:
314
+ tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
315
+ """
316
+ # Lazy initialization
317
+ if self.keys is None:
318
+ self.lazy_initialization(key_states)
319
+
320
+ # Some old models give None for `cache_position` or even omit passing `cache_kwargs` when used as cross-attention,
321
+ # in which case we should copy the whole Layer (key_states.shape[-2] == self.max_cache_len)
322
+ cache_position = cache_kwargs.get("cache_position") if cache_kwargs is not None else None
323
+ cache_position = (
324
+ cache_position if cache_position is not None else torch.arange(key_states.shape[-2], device=self.device)
325
+ )
326
+
327
+ # Update the cache
328
+ try:
329
+ self.keys.index_copy_(2, cache_position, key_states)
330
+ self.values.index_copy_(2, cache_position, value_states)
331
+ except NotImplementedError:
332
+ # Fallback for devices like MPS where index_copy_ might not be supported.
333
+ self.keys[:, :, cache_position] = key_states
334
+ self.values[:, :, cache_position] = value_states
335
+ return self.keys, self.values
336
+
337
+ def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]:
338
+ """Return the length and offset of the cache, used to generate the attention mask"""
339
+ kv_offset = 0
340
+ kv_length = self.max_cache_len
341
+ return kv_length, kv_offset
342
+
343
+ def get_seq_length(self) -> int:
344
+ """Returns the sequence length of the cached states."""
345
+ # Occupied cache == any slot in the 3rd dim (sequence length) holds a non-zero value. To save on compute, let's
346
+ # limit the check to the first batch member and head dimension.
347
+ return (self.keys[0, 0].any(dim=-1)).sum() if self.keys is not None else 0
348
+
349
+ def get_max_cache_shape(self) -> int:
350
+ """Return the maximum cache shape of the cache"""
351
+ return self.max_cache_len
352
+
353
+
354
+ class SlidingWindowLayer(StaticLayer):
355
+ """
356
+ A static cache layer that stores the key and value states as static tensors of shape
357
+ `[batch_size, num_heads, min(max_cache_len, sliding_window), head_dim]`. It lazily allocates its full backing
358
+ tensors, and then mutates them in-place. Built for `torch.compile` support.
359
+
360
+ Args:
361
+ max_cache_len (`int`):
362
+ Maximum number of tokens that can be stored, used for tensor preallocation.
363
+ sliding_window (`int`):
364
+ The size of the sliding window.
365
+ """
366
+
367
+ is_sliding = True
368
+
369
+ def __init__(self, max_cache_len: int, sliding_window: int):
370
+ effective_max_cache_len = min(sliding_window, max_cache_len)
371
+ super().__init__(max_cache_len=effective_max_cache_len)
372
+ self.cumulative_length = 0
373
+
374
+ def update(
375
+ self,
376
+ key_states: torch.Tensor,
377
+ value_states: torch.Tensor,
378
+ cache_kwargs: Optional[dict[str, Any]] = None,
379
+ ) -> tuple[torch.Tensor, torch.Tensor]:
380
+ """
381
+ Update the key and value caches in-place, and return the necessary keys and value states.
382
+
383
+ Args:
384
+ key_states (`torch.Tensor`): The new key states to cache.
385
+ value_states (`torch.Tensor`): The new value states to cache.
386
+ cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
387
+
388
+ Returns:
389
+ tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
390
+ """
391
+ # Lazy initialization
392
+ if self.keys is None:
393
+ self.lazy_initialization(key_states)
394
+
395
+ cache_position = cache_kwargs.get("cache_position")
396
+
397
+ is_full = self.cumulative_length >= self.max_cache_len
398
+ # Update it now that we saved the value above
399
+ self.cumulative_length += key_states.shape[-2]
400
+
401
+ # Handle prefill phase when prompt length > sliding_window_size.
402
+ # Note that we store cropped key/value states in the cache but return the full key/value states.
403
+ if cache_position.shape[0] > self.max_cache_len:
404
+ self.keys.copy_(key_states[:, :, -self.max_cache_len :, :])
405
+ self.values.copy_(value_states[:, :, -self.max_cache_len :, :])
406
+ # Return the full states here
407
+ return key_states, value_states
408
+
409
+ # Here we only assume decoding stage, i.e. 1 token at a time
410
+ if is_full:
411
+ # Roll all values to the left by 1 position
412
+ new_keys = self.keys.roll(-1, dims=-2)
413
+ new_values = self.values.roll(-1, dims=-2)
414
+ # Overwrite the last position with new states
415
+ # (note: very important to use a tensor to index here, see https://github.com/pytorch/pytorch/issues/159855)
416
+ index = torch.tensor([-1], dtype=int, device=self.device)
417
+ new_keys[:, :, index] = key_states
418
+ new_values[:, :, index] = value_states
419
+
420
+ # Copy back into `self` (do not just assign again) in order to keep the static dynamo address
421
+ self.keys.copy_(new_keys)
422
+ self.values.copy_(new_values)
423
+ else:
424
+ try:
425
+ self.keys.index_copy_(2, cache_position, key_states)
426
+ self.values.index_copy_(2, cache_position, value_states)
427
+ except NotImplementedError:
428
+ self.keys[:, :, cache_position] = key_states
429
+ self.values[:, :, cache_position] = value_states
430
+
431
+ return self.keys, self.values
432
+
433
+ def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]:
434
+ """Return the length and offset of the cache, used to generate the attention mask"""
435
+ query_length = cache_position.shape[0]
436
+ first_cache_position = cache_position[0]
437
+
438
+ kv_offset = torch.clamp(first_cache_position - self.max_cache_len + 1, min=0)
439
+ # This is not general (see HybridChunkedCache for the whole general case), but it's what the cache returns
440
+ kv_length = max(query_length, self.max_cache_len)
441
+ return kv_length, kv_offset
442
+
443
+ def get_seq_length(self) -> int:
444
+ """Returns the sequence length of the cached states."""
445
+ return self.cumulative_length
446
+
447
+
448
+ class ChunkedSlidingLayer(SlidingWindowLayer):
449
+ """
450
+ An extended SlidingWindowLayer that supports prefill chunking, originally implemented for Llama 4.
451
+ """
452
+
453
+ def update(
454
+ self,
455
+ key_states: torch.Tensor,
456
+ value_states: torch.Tensor,
457
+ cache_kwargs: Optional[dict[str, Any]] = None,
458
+ ) -> tuple[torch.Tensor, torch.Tensor]:
459
+ """
460
+ Update the key and value caches in-place, and return the necessary keys and value states.
461
+
462
+ Args:
463
+ key_states (`torch.Tensor`): The new key states to cache.
464
+ value_states (`torch.Tensor`): The new value states to cache.
465
+ cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
466
+
467
+ Returns:
468
+ tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
469
+ """
470
+ # Lazy initialization
471
+ if self.keys is None:
472
+ self.lazy_initialization(key_states)
473
+
474
+ cache_position = cache_kwargs.get("cache_position")
475
+
476
+ cumulative_length = self.cumulative_length
477
+ is_full = cumulative_length >= self.max_cache_len
478
+ # Update it now that we saved the value above
479
+ self.cumulative_length += key_states.shape[-2]
480
+
481
+ if is_full:
482
+ full_key_states = torch.cat((self.keys[:, :, 1:, :], key_states), dim=-2)
483
+ full_value_states = torch.cat((self.values[:, :, 1:, :], value_states), dim=-2)
484
+ # Fast decoding path -> here as the effective size is still sliding window, it is extremely important
485
+ # to return `self.key_cache[layer_idx]` and `self.value_cache[layer_idx]`, as they have the fixed address
486
+ # in memory (the values are the same as the full states, but not the address!!)
487
+ if key_states.shape[-2] == 1:
488
+ self.keys.copy_(full_key_states)
489
+ self.values.copy_(full_value_states)
490
+ return self.keys, self.values
491
+ elif not is_full and cumulative_length + key_states.shape[2] > self.max_cache_len:
492
+ # Fast prefill path, no need to cat() in this case, as the cache is currently empty
493
+ if cumulative_length == 0:
494
+ full_key_states = key_states
495
+ full_value_states = value_states
496
+ else:
497
+ full_key_states = torch.cat((self.keys[:, :, :cumulative_length, :], key_states), dim=-2)
498
+ full_value_states = torch.cat((self.values[:, :, :cumulative_length, :], value_states), dim=-2)
499
+ else:
500
+ try:
501
+ self.keys.index_copy_(2, cache_position, key_states)
502
+ self.values.index_copy_(2, cache_position, value_states)
503
+ except NotImplementedError:
504
+ self.keys[:, :, cache_position] = key_states
505
+ self.values[:, :, cache_position] = value_states
506
+ return self.keys, self.values
507
+
508
+ self.keys.copy_(full_key_states[:, :, -self.max_cache_len :, :])
509
+ self.values.copy_(full_value_states[:, :, -self.max_cache_len :, :])
510
+ # we should return the whole states instead of `self.keys/values` here, as otherwise we lose some context
511
+ # which is outside the window
512
+ return full_key_states, full_value_states
513
+
514
+ def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]:
515
+ """Return the length and offset of the cache, used to generate the attention mask"""
516
+ query_length = cache_position.shape[0]
517
+ first_cache_position = cache_position[0]
518
+ sliding_window = self.max_cache_len
519
+
520
+ kv_offset = torch.clamp(first_cache_position - sliding_window + 1, min=0)
521
+ # This is the true general case for any Cache using local attention (sliding or chunked)
522
+ if first_cache_position >= sliding_window:
523
+ # Here the Cache is already full
524
+ kv_length = sliding_window + query_length - 1
525
+ elif first_cache_position < sliding_window and first_cache_position + query_length > sliding_window:
526
+ # Here the Cache becomes full with the new input
527
+ kv_length = first_cache_position + query_length
528
+ else:
529
+ # Here the Cache is still smaller than the local size, but we return the local size as it's static
530
+ kv_length = sliding_window
531
+ return kv_length, kv_offset
532
+
533
+
534
+ class QuantizedLayer(DynamicLayer):
535
+ """
536
+ A quantized layer similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750).
537
+ It allows the model to generate longer sequence length without allocating too much memory for the key and value caches by
538
+ applying quantization.
539
+
540
+ The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length`
541
+ is set as a maximum capacity for the original precision cache. When the length goes beyond maximum capacity, the original
542
+ precision cache is discarded and moved into the quantized cache. The quantization is done per-channel with a set `q_group_size`
543
+ for both Keys and Values, in contrast to what was described in the paper.
544
+ """
545
+
546
+ def __init__(
547
+ self,
548
+ nbits: int = 4,
549
+ axis_key: int = 0,
550
+ axis_value: int = 0,
551
+ q_group_size: int = 64,
552
+ residual_length: int = 128,
553
+ ):
554
+ super().__init__()
555
+ self.nbits = nbits
556
+ self.axis_key = axis_key
557
+ self.axis_value = axis_value
558
+ self.q_group_size = q_group_size
559
+ self.residual_length = residual_length
560
+ self.cumulative_length = 0
561
+
562
+ def update(
563
+ self,
564
+ key_states: torch.Tensor,
565
+ value_states: torch.Tensor,
566
+ cache_kwargs: Optional[dict[str, Any]] = None,
567
+ ) -> tuple[torch.Tensor, torch.Tensor]:
568
+ """
569
+ Update the key and value caches in-place, and return the necessary keys and value states.
570
+
571
+ Args:
572
+ key_states (`torch.Tensor`): The new key states to cache.
573
+ value_states (`torch.Tensor`): The new value states to cache.
574
+ cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
575
+
576
+ Returns:
577
+ tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
578
+ """
579
+ self.cumulative_length += key_states.shape[-2]
580
+
581
+ # Lazy initialization
582
+ if self.keys is None:
583
+ self.lazy_initialization(key_states)
584
+ self._quantized_keys = self._quantize(key_states.contiguous(), axis=self.axis_key)
585
+ self._quantized_values = self._quantize(value_states.contiguous(), axis=self.axis_value)
586
+ return key_states, value_states
587
+
588
+ dequant_keys = self._dequantize(self._quantized_keys)
589
+ dequant_values = self._dequantize(self._quantized_values)
590
+ keys_to_return = torch.cat([dequant_keys, self.keys, key_states], dim=-2)
591
+ values_to_return = torch.cat([dequant_values, self.values, value_states], dim=-2)
592
+ if self.keys.dim() == 4 and self.keys.shape[-2] + 1 >= self.residual_length:
593
+ self._quantized_keys = self._quantize(keys_to_return.contiguous(), axis=self.axis_key)
594
+ self._quantized_values = self._quantize(values_to_return.contiguous(), axis=self.axis_value)
595
+ self.keys = torch.tensor([], dtype=key_states.dtype, device=key_states.device)
596
+ self.values = torch.tensor([], dtype=key_states.dtype, device=key_states.device)
597
+ else:
598
+ self.keys = torch.cat([self.keys, key_states], dim=-2)
599
+ self.values = torch.cat([self.values, value_states], dim=-2)
600
+
601
+ return keys_to_return, values_to_return
602
+
603
+ @abstractmethod
604
+ def _quantize(self, tensor, axis): ...
605
+
606
+ @abstractmethod
607
+ def _dequantize(self, q_tensor): ...
608
+
609
+ def get_seq_length(self) -> int:
610
+ """Returns the sequence length of the cached states."""
611
+ return self.cumulative_length
612
+
613
+
614
+ class QuantoQuantizedLayer(QuantizedLayer):
615
+ def __init__(
616
+ self,
617
+ nbits: int = 4,
618
+ axis_key: int = 0,
619
+ axis_value: int = 0,
620
+ q_group_size: int = 64,
621
+ residual_length: int = 128,
622
+ ):
623
+ super().__init__(
624
+ nbits=nbits,
625
+ axis_key=axis_key,
626
+ axis_value=axis_value,
627
+ q_group_size=q_group_size,
628
+ residual_length=residual_length,
629
+ )
630
+
631
+ # We need to import quanto here to avoid circular imports due to optimum/quanto/models/transformers_models.py
632
+ if is_quanto_greater("0.2.5", accept_dev=True):
633
+ from optimum.quanto import MaxOptimizer, qint2, qint4
634
+ else:
635
+ raise ImportError(
636
+ "You need optimum-quanto package version to be greater or equal than 0.2.5 to use `QuantoQuantizedCache`. "
637
+ )
638
+
639
+ if self.nbits not in [2, 4]:
640
+ raise ValueError(f"`nbits` for `quanto` backend has to be one of [`2`, `4`] but got {self.nbits}")
641
+
642
+ if self.axis_key not in [0, -1]:
643
+ raise ValueError(f"`axis_key` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_key}")
644
+
645
+ if self.axis_value not in [0, -1]:
646
+ raise ValueError(
647
+ f"`axis_value` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_value}"
648
+ )
649
+
650
+ self.qtype = qint4 if self.nbits == 4 else qint2
651
+ self.optimizer = MaxOptimizer() # hardcode as it's the only one for per-channel quantization
652
+
653
+ def _quantize(self, tensor, axis):
654
+ from optimum.quanto import quantize_weight
655
+
656
+ scale, zeropoint = self.optimizer(tensor, self.qtype, axis, self.q_group_size)
657
+ qtensor = quantize_weight(tensor, self.qtype, axis, scale, zeropoint, self.q_group_size)
658
+ return qtensor
659
+
660
+ def _dequantize(self, qtensor):
661
+ return qtensor.dequantize()
662
+
663
+
664
+ class HQQQuantizedLayer(QuantizedLayer):
665
+ def __init__(
666
+ self,
667
+ nbits: int = 4,
668
+ axis_key: int = 0,
669
+ axis_value: int = 0,
670
+ q_group_size: int = 64,
671
+ residual_length: int = 128,
672
+ ):
673
+ super().__init__(
674
+ nbits=nbits,
675
+ axis_key=axis_key,
676
+ axis_value=axis_value,
677
+ q_group_size=q_group_size,
678
+ residual_length=residual_length,
679
+ )
680
+
681
+ if not is_hqq_available():
682
+ raise ImportError("You need to install `hqq` to use `HQQQuantizedLayer`")
683
+
684
+ if self.nbits not in [1, 2, 3, 4, 8]:
685
+ raise ValueError(
686
+ f"`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got {self.nbits}"
687
+ )
688
+
689
+ if self.axis_key not in [0, 1]:
690
+ raise ValueError(f"`axis_key` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_key}")
691
+
692
+ if self.axis_value not in [0, 1]:
693
+ raise ValueError(f"`axis_value` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_value}")
694
+
695
+ self.quantizer = HQQQuantizer
696
+
697
+ def _quantize(self, tensor, axis):
698
+ qtensor, meta = self.quantizer.quantize(
699
+ tensor,
700
+ axis=axis,
701
+ device=self.keys.device,
702
+ compute_dtype=self.keys.dtype,
703
+ nbits=self.nbits,
704
+ group_size=self.q_group_size,
705
+ )
706
+ meta["compute_dtype"] = self.keys.dtype
707
+ self.quantizer.cuda(qtensor, meta=meta, device=self.keys.device) # Move to device and cast to dtype
708
+ meta["scale"] = meta["scale"].to(qtensor.device)
709
+ meta["zero"] = meta["zero"].to(qtensor.device)
710
+ return qtensor, meta
711
+
712
+ def _dequantize(self, qtensor):
713
+ quant_tensor, meta = qtensor
714
+ tensor = self.quantizer.dequantize(quant_tensor, meta)
715
+ return tensor
716
+
717
+
718
+ class Cache:
719
+ """
720
+ A `Cache` is mostly a list of `CacheLayerMixin` objects, one per model layer. It serves as a container for
721
+ the Cache of each layer.
722
+
723
+ Args:
724
+ layers (`Optional`, *optional*):
725
+ A list of pre-created `CacheLayerMixin`. If omitted (`None`), then `layer_class_to_replicate` will
726
+ be used.
727
+ layer_class_to_replicate (`type[CacheLayerMixin]`, *optional*):
728
+ Only used if `layers` is omitted (`None`), in which case it will be used as the base class for each layer,
729
+ and the layers will be added lazily as soon as `update` is called with a `layer_idx` greater than the current
730
+ list of layers.
731
+ offloading (`bool`, *optional*, defaults to `False`):
732
+ Whether to perform offloading of the layers to `cpu`, to save GPU memory.
733
+ offload_only_non_sliding (`bool`, *optional*, defaults to `True`):
734
+ If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because
735
+ usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).
736
+ """
737
+
738
+ def __init__(
739
+ self,
740
+ layers: Optional[list[CacheLayerMixin]] = None,
741
+ layer_class_to_replicate: Optional[type[CacheLayerMixin]] = None,
742
+ offloading: bool = False,
743
+ offload_only_non_sliding: bool = True,
744
+ ):
745
+ if layers is not None and layer_class_to_replicate is not None:
746
+ raise ValueError(
747
+ "You can construct a Cache either from a list `layers` of all the predefined `CacheLayer`, or from a "
748
+ "`layer_class_to_replicate`, in which case the Cache will append a new layer corresponding to "
749
+ "`layer_class_to_replicate` for each new call to `update` with an idx not already in the Cache."
750
+ )
751
+ if layers is None and layer_class_to_replicate is None:
752
+ raise ValueError(
753
+ "You should provide exactly one of `layers` or `layer_class_to_replicate` to initialize a Cache."
754
+ )
755
+ self.layers = layers if layers is not None else []
756
+ self.layer_class_to_replicate = layer_class_to_replicate
757
+ self.offloading = offloading
758
+ if self.offloading:
759
+ self.only_non_sliding = offload_only_non_sliding
760
+ self.prefetch_stream = torch.Stream() if _is_torch_greater_or_equal_than_2_7 else torch.cuda.Stream()
761
+
762
+ def __repr__(self):
763
+ return f"{self.__class__.__name__}(layers={self.layers})"
764
+
765
+ def prefetch(self, layer_idx: int, only_non_sliding: bool = True):
766
+ """
767
+ Prefetch a given layer on its device. If `only_non_sliding` is True, it will try to prefetch only the layers
768
+ which are non-sliding. If the `layer_idx` is outside the range, this will circle back to the first layers.
769
+ Note that we use a non-default stream for this, to avoid blocking.
770
+ """
771
+ if only_non_sliding:
772
+ # Try to find next non-sliding, starting at `layer_idx`
773
+ try:
774
+ layer_idx = layer_idx + self.is_sliding[layer_idx:].index(False)
775
+ # In this case, we need to circle back to the beginning
776
+ except ValueError:
777
+ layer_idx = self.is_sliding.index(False)
778
+ else:
779
+ layer_idx = layer_idx if layer_idx < len(self.layers) else 0
780
+
781
+ # Prefetch
782
+ with self.prefetch_stream if _is_torch_greater_or_equal_than_2_7 else torch.cuda.stream(self.prefetch_stream):
783
+ self.layers[layer_idx].prefetch()
784
+
785
+ def offload(self, layer_idx: int, only_non_sliding: bool = True):
786
+ """
787
+ Offload a given `layer_idx`. If `only_non_sliding` is True, it will offload `layer_idx` only if it is a
788
+ non-sliding layer. Note that we do it on the default stream, so that we ensure all earlier
789
+ computation in the layer's `update` methods are finished.
790
+ """
791
+ if not (only_non_sliding and self.is_sliding[layer_idx]):
792
+ self.layers[layer_idx].offload()
793
+
794
+ def update(
795
+ self,
796
+ key_states: torch.Tensor,
797
+ value_states: torch.Tensor,
798
+ layer_idx: int,
799
+ cache_kwargs: Optional[dict[str, Any]] = None,
800
+ ) -> tuple[torch.Tensor, torch.Tensor]:
801
+ """
802
+ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
803
+
804
+ Parameters:
805
+ key_states (`torch.Tensor`):
806
+ The new key states to cache.
807
+ value_states (`torch.Tensor`):
808
+ The new value states to cache.
809
+ layer_idx (`int`):
810
+ The index of the layer to cache the states for.
811
+ cache_kwargs (`dict[str, Any]`, *optional*):
812
+ Additional arguments for the cache subclass. These are specific to each subclass and allow new types of
813
+ cache to be created.
814
+
815
+ Return:
816
+ A tuple containing the updated key and value states.
817
+ """
818
+ # In this case, the `layers` were not provided, and we must append as much as `layer_idx`
819
+ if self.layer_class_to_replicate is not None:
820
+ while len(self.layers) <= layer_idx:
821
+ self.layers.append(self.layer_class_to_replicate())
822
+
823
+ if self.offloading:
824
+ # Wait for the stream to finish if needed, and start prefetching the next layer
825
+ torch.cuda.default_stream(key_states.device).wait_stream(self.prefetch_stream)
826
+ self.prefetch(layer_idx + 1, self.only_non_sliding)
827
+
828
+ keys, values = self.layers[layer_idx].update(key_states, value_states, cache_kwargs)
829
+
830
+ if self.offloading:
831
+ self.offload(layer_idx, self.only_non_sliding)
832
+
833
+ return keys, values
834
+
835
+ def early_initialization(
836
+ self, batch_size: int, num_heads: int, head_dim: int, dtype: torch.dtype, device: torch.device
837
+ ):
838
+ """
839
+ Initialize all the layers in advance (it's otherwise lazily initialized on the first `update` call).
840
+ This is useful for our `export` recipes, as `export` needs everything in advance.
841
+ """
842
+ # Note that the initialization needs all dimensions (except -2), as well as device and dtype, so we use
843
+ # this fake tensor approach. It has size 0 on the -2 dimension, so it does not allocate any data (it only
844
+ # creates an empty tensor with correct shape, dtype and device), which is very efficient and practical
845
+ fake_keys_tensor = torch.zeros((batch_size, num_heads, 0, head_dim), dtype=dtype, device=device)
846
+ # Init all layers
847
+ for layer in self.layers:
848
+ layer.lazy_initialization(fake_keys_tensor)
849
+
850
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
851
+ """Returns the sequence length of the cache for the given layer."""
852
+ if layer_idx >= len(self.layers):
853
+ return 0
854
+ return self.layers[layer_idx].get_seq_length()
855
+
856
+ def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
857
+ """
858
+ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
859
+ the given layer at `layer_idx`.
860
+ The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
861
+ """
862
+ # For DynamicCache, where the layers are created at runtime -> if it was not yet created, the size is
863
+ # simply the shape of `cache_position`
864
+ if layer_idx >= len(self.layers):
865
+ return cache_position.shape[0], 0
866
+ return self.layers[layer_idx].get_mask_sizes(cache_position)
867
+
868
+ def get_max_cache_shape(self, layer_idx: int = 0) -> int:
869
+ """Returns maximum sequence length of the cache object. Dynamic caches do not have a maximum length."""
870
+ # For DynamicCache, where the layers are created at runtime -> if it was not yet created, return -1
871
+ # as DynamicLayer does
872
+ if layer_idx >= len(self.layers):
873
+ return -1
874
+ return self.layers[layer_idx].get_max_cache_shape()
875
+
876
+ def reset(self):
877
+ """Recursively reset all layers tensors"""
878
+ for layer_idx in range(len(self.layers)):
879
+ self.layers[layer_idx].reset()
880
+
881
+ def reorder_cache(self, beam_idx: torch.LongTensor):
882
+ """Reorder the cache for beam search"""
883
+ for layer_idx in range(len(self.layers)):
884
+ self.layers[layer_idx].reorder_cache(beam_idx)
885
+
886
+ def crop(self, max_length: int):
887
+ """Crop the cache to the given length"""
888
+ for layer_idx in range(len(self.layers)):
889
+ self.layers[layer_idx].crop(max_length)
890
+
891
+ def batch_repeat_interleave(self, repeats: int):
892
+ """Repeat and interleave the cache"""
893
+ for layer_idx in range(len(self.layers)):
894
+ self.layers[layer_idx].batch_repeat_interleave(repeats)
895
+
896
+ def batch_select_indices(self, indices: torch.Tensor):
897
+ """Select indices from the cache"""
898
+ for layer_idx in range(len(self.layers)):
899
+ self.layers[layer_idx].batch_select_indices(indices)
900
+
901
+ @property
902
+ def max_batch_size(self) -> int:
903
+ """Return the maximum batch size of the cache"""
904
+ values = [layer.max_batch_size for layer in self.layers]
905
+ if len(set(values)) > 1:
906
+ raise ValueError(f"Max batch size is not consistent across layers: {values}")
907
+ return values[0]
908
+
909
+ @property
910
+ def max_cache_len(self) -> int:
911
+ """Return the maximum cache length of the cache"""
912
+ values = [layer.max_cache_len for layer in self.layers]
913
+ return max(values)
914
+
915
+ @property
916
+ def is_compileable(self) -> bool:
917
+ """Return whether the cache is compileable"""
918
+ # For DynamicCache dispatching the layers lazily (otherwise, all([]) is True)
919
+ if len(self.layers) == 0:
920
+ return False
921
+ return all(layer.is_compileable for layer in self.layers)
922
+
923
+ @property
924
+ def is_sliding(self) -> list[bool]:
925
+ """Return whether the layers of the cache are sliding window"""
926
+ return [getattr(layer, "is_sliding", False) for layer in self.layers]
927
+
928
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
929
+ """
930
+ Support for backwards-compatible `past_key_values` indexing, e.g. `past_key_values[0][0].shape[2]` to get the
931
+ sequence length.
932
+ """
933
+ if layer_idx < len(self.layers):
934
+ return self.layers[layer_idx].keys, self.layers[layer_idx].values
935
+ # elif len(self.layers) == 0:
936
+ # return None, None
937
+ else:
938
+ raise KeyError(
939
+ f"Cache only has {len(self.layers)} layers, attempted to access layer with index {layer_idx}"
940
+ )
941
+
942
+ def __iter__(self):
943
+ """
944
+ Support for backwards-compatible `past_key_values` iteration, e.g. `for x in past_key_values:` to iterate over
945
+ keys and values
946
+ """
947
+ for layer_idx in range(len(self)):
948
+ yield (self.layers[layer_idx].keys, self.layers[layer_idx].values)
949
+
950
+ def __len__(self):
951
+ """
952
+ This value corresponds to the number of layers in the model.
953
+ """
954
+ # Note: for DynamicCache, layers are initialized lazily, so this will not be accurate before the first
955
+ # forward through all the layers
956
+ return len(self.layers)
957
+
958
+
959
+ class DynamicCache(Cache):
960
+ """
961
+ A cache that grows dynamically as more tokens are generated. This is the default for generative models.
962
+ It stores the key and value states as a list of `CacheLayer`, one for each layer. The expected shape for each tensor
963
+ in the `CacheLayer`s is `[batch_size, num_heads, seq_len, head_dim]`.
964
+ If a config is passed, it will additionally check for sliding or hybrid cache structure, greatly reducing the
965
+ memory requirement of the cached tensors to `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
966
+
967
+ See `Cache` for details on common methods that are implemented by all cache classes.
968
+
969
+ Args:
970
+ ddp_cache_data (`Iterable[tuple[torch.Tensor, torch.Tensor]]`, *optional*):
971
+ It was originally added for compatibility with `torch.distributed` (DDP). In a nutshell, it is
972
+ `map(gather_map, zip(*caches))`, i.e. each item in the iterable contains the key and value states
973
+ for a layer gathered across replicas by torch.distributed (shape=[global batch size, num_heads, seq_len, head_dim]).
974
+ Note: it needs to be the 1st arg as well to work correctly
975
+ config (`PretrainedConfig`, *optional*):
976
+ The config of the model for which this Cache will be used. If passed, it will be used to check for sliding
977
+ or hybrid layer structure, greatly reducing the memory requirement of the cached tensors to
978
+ `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
979
+ offloading (`bool`, *optional*, defaults to `False`):
980
+ Whether to perform offloading of the layers to `cpu`, to save GPU memory.
981
+ offload_only_non_sliding (`bool`, *optional*, defaults to `False`):
982
+ If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because
983
+ usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).
984
+
985
+ Example:
986
+
987
+ ```python
988
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache
989
+
990
+ >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
991
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
992
+
993
+ >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
994
+
995
+ >>> # Prepare a cache class and pass it to model's forward
996
+ >>> past_key_values = DynamicCache(config=model.config)
997
+ >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
998
+ >>> outputs.past_key_values # access cache filled with key/values from generation
999
+ ```
1000
+ """
1001
+
1002
+ def __init__(
1003
+ self,
1004
+ ddp_cache_data: Optional[Iterable[tuple[torch.Tensor, torch.Tensor]]] = None,
1005
+ config: Optional[PretrainedConfig] = None,
1006
+ offloading: bool = False,
1007
+ offload_only_non_sliding: bool = False,
1008
+ ):
1009
+ layers = []
1010
+ # If a config is passed, use it to infer the layer types and initialize accordingly
1011
+ if config is not None:
1012
+ config = config.get_text_config()
1013
+ sliding_window = getattr(config, "sliding_window", None) or getattr(config, "attention_chunk_size", None)
1014
+ layer_types = getattr(config, "layer_types", None)
1015
+ if layer_types is None:
1016
+ layer_types = [
1017
+ "sliding_attention" if sliding_window is not None else "full_attention"
1018
+ for _ in range(config.num_hidden_layers)
1019
+ ]
1020
+ # Some models have shared layers thus no cache is needed for them (e.g. Gemma3n)
1021
+ if hasattr(config, "num_kv_shared_layers"):
1022
+ layer_types = layer_types[: -config.num_kv_shared_layers]
1023
+
1024
+ for layer_type in layer_types:
1025
+ if layer_type in ("sliding_attention", "chunked_attention"):
1026
+ layers.append(DynamicSlidingWindowLayer(sliding_window=sliding_window))
1027
+ else:
1028
+ layers.append(DynamicLayer())
1029
+
1030
+ # In this case, use the passed data to already fill in the Cache
1031
+ if ddp_cache_data is not None:
1032
+ # Init all the layers with the data
1033
+ for layer_idx, (key_states, value_states) in enumerate(ddp_cache_data):
1034
+ # If the config was not passed above, initialize a DynamicLayer for each entry of the ddp_data
1035
+ if config is None:
1036
+ layers.append(DynamicLayer())
1037
+ # Update the layer with the data
1038
+ _, _ = layers[layer_idx].update(key_states, value_states)
1039
+
1040
+ # If neither of config nor ddp_data was passed, then simply lazy init a full cache of DynamicLayer
1041
+ if len(layers) == 0:
1042
+ super().__init__(
1043
+ layer_class_to_replicate=DynamicLayer,
1044
+ offloading=offloading,
1045
+ offload_only_non_sliding=offload_only_non_sliding,
1046
+ )
1047
+ else:
1048
+ super().__init__(layers=layers, offloading=offloading, offload_only_non_sliding=offload_only_non_sliding)
1049
+
1050
+ def to_legacy_cache(self) -> tuple[tuple[torch.Tensor, torch.Tensor]]:
1051
+ """
1052
+ Converts the `Cache` instance into the its equivalent in the legacy cache format. Used for
1053
+ backward compatibility.
1054
+ """
1055
+ legacy_cache = ()
1056
+ for layer in self.layers:
1057
+ legacy_cache += ((layer.keys, layer.values),)
1058
+ return legacy_cache
1059
+
1060
+ @classmethod
1061
+ def from_legacy_cache(cls, past_key_values: tuple[tuple[torch.Tensor, torch.Tensor]]) -> "DynamicCache":
1062
+ """
1063
+ Converts a cache in the legacy cache format into an equivalent `Cache`. Used for
1064
+ backward compatibility.
1065
+ """
1066
+ cache = cls()
1067
+ if past_key_values is None:
1068
+ logger.warning_once("past_key_values should not be None in from_legacy_cache()")
1069
+ if past_key_values is not None:
1070
+ for layer_idx in range(len(past_key_values)):
1071
+ key_states, value_states = past_key_values[layer_idx]
1072
+ cache.update(key_states, value_states, layer_idx)
1073
+ return cache
1074
+
1075
+
1076
+ class StaticCache(Cache):
1077
+ """
1078
+ Static Cache class to be used with `torch.compile(model)` and `torch.export()`. It will check the `config`
1079
+ for potential hybrid cache structure, and initialize each layer accordingly.
1080
+
1081
+ See `Cache` for details on common methods that are implemented by all cache classes.
1082
+
1083
+ Args:
1084
+ config (`PretrainedConfig`):
1085
+ The config of the model for which this Cache will be used. It will be used to check for sliding
1086
+ or hybrid layer structure, and initialize each layer accordingly.
1087
+ max_cache_len (`int`):
1088
+ The maximum number of tokens that this Cache should hold.
1089
+ offloading (`bool`, *optional*, defaults to `False`):
1090
+ Whether to perform offloading of the layers to `cpu`, to save GPU memory.
1091
+ offload_only_non_sliding (`bool`, *optional*, defaults to `True`):
1092
+ If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because
1093
+ usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).
1094
+
1095
+ Example:
1096
+
1097
+ ```python
1098
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache
1099
+
1100
+ >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
1101
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
1102
+
1103
+ >>> inputs = tokenizer(text="My name is Llama", return_tensors="pt")
1104
+
1105
+ >>> # Prepare a cache class and pass it to model's forward
1106
+ >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
1107
+ >>> max_generated_length = inputs.input_ids.shape[1] + 10
1108
+ >>> past_key_values = StaticCache(config=model.config, max_cache_len=max_generated_length)
1109
+ >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
1110
+ >>> outputs.past_key_values # access cache filled with key/values from generation
1111
+ StaticCache()
1112
+ ```
1113
+ """
1114
+
1115
+ # Pass-in kwargs as well to avoid crashing for BC (it used more arguments before)
1116
+ def __init__(
1117
+ self,
1118
+ config: PretrainedConfig,
1119
+ max_cache_len: int,
1120
+ offloading: bool = False,
1121
+ offload_only_non_sliding: bool = True,
1122
+ **kwargs,
1123
+ ):
1124
+ config = config.get_text_config()
1125
+ layer_types = getattr(config, "layer_types", None)
1126
+ # If `layer_types` is not explicitly provided, infer if the model is fully sliding
1127
+ if layer_types is None:
1128
+ if getattr(config, "sliding_window", None) is not None:
1129
+ layer_types = ["sliding_attention" for _ in range(config.num_hidden_layers)]
1130
+ elif getattr(config, "attention_chunk_size", None) is not None:
1131
+ layer_types = ["chunked_attention" for _ in range(config.num_hidden_layers)]
1132
+ else:
1133
+ layer_types = ["full_attention" for _ in range(config.num_hidden_layers)]
1134
+ # Some models have shared layers thus no cache is needed for them (e.g. Gemma3n)
1135
+ if hasattr(config, "num_kv_shared_layers"):
1136
+ layer_types = layer_types[: -config.num_kv_shared_layers]
1137
+
1138
+ layers = []
1139
+ for layer_type in layer_types:
1140
+ if layer_type == "sliding_attention":
1141
+ layer = SlidingWindowLayer(max_cache_len=max_cache_len, sliding_window=config.sliding_window)
1142
+ elif layer_type == "chunked_attention":
1143
+ layer = ChunkedSlidingLayer(max_cache_len=max_cache_len, sliding_window=config.attention_chunk_size)
1144
+ else:
1145
+ layer = StaticLayer(max_cache_len=max_cache_len)
1146
+ layers.append(layer)
1147
+
1148
+ super().__init__(layers=layers, offloading=offloading, offload_only_non_sliding=offload_only_non_sliding)
1149
+
1150
+
1151
+ class QuantizedCache(Cache):
1152
+ """
1153
+ A quantizer cache similar to what is described in the
1154
+ [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750).
1155
+ It allows the model to generate longer sequence length without allocating too much memory for keys and values
1156
+ by applying quantization.
1157
+ The cache has two types of storage, one for original precision and one for the
1158
+ quantized cache. A `residual length` is set as a maximum capacity for the original precision cache. When the
1159
+ length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache.
1160
+ The quantization is done per-channel with a set `q_group_size` for both keys and values, in contrast to what was
1161
+ described in the paper.
1162
+
1163
+ See `Cache` for details on common methods that are implemented by all cache classes.
1164
+
1165
+ Args:
1166
+ backend (`str`):
1167
+ The quantization backend to use. One of `("quanto", "hqq").
1168
+ config (`PretrainedConfig`):
1169
+ The config of the model for which this Cache will be used.
1170
+ nbits (`int`, *optional*, defaults to 4):
1171
+ The number of bits for quantization.
1172
+ axis_key (`int`, *optional*, defaults to 0):
1173
+ The axis on which to quantize the keys.
1174
+ axis_value (`int`, *optional*, defaults to 0):
1175
+ The axis on which to quantize the values.
1176
+ q_group_size (`int`, *optional*, defaults to 64):
1177
+ Quantization is done per-channel according to a set `q_group_size` for both keys and values.
1178
+ residual_length (`int`, *optional*, defaults to 128):
1179
+ Maximum capacity for the original precision cache
1180
+ """
1181
+
1182
+ def __init__(
1183
+ self,
1184
+ backend: str,
1185
+ config: PretrainedConfig,
1186
+ nbits: int = 4,
1187
+ axis_key: int = 0,
1188
+ axis_value: int = 0,
1189
+ q_group_size: int = 64,
1190
+ residual_length: int = 128,
1191
+ ):
1192
+ if backend == "quanto":
1193
+ layer_class = QuantoQuantizedLayer
1194
+ elif backend == "hqq":
1195
+ layer_class = HQQQuantizedLayer
1196
+ else:
1197
+ raise ValueError(f"Unknown quantization backend `{backend}`")
1198
+
1199
+ config = config.get_text_config(decoder=True)
1200
+ layers = [
1201
+ layer_class(nbits, axis_key, axis_value, q_group_size, residual_length)
1202
+ for _ in range(config.num_hidden_layers)
1203
+ ]
1204
+ super().__init__(layers=layers)
1205
+
1206
+
1207
+ class EncoderDecoderCache(Cache):
1208
+ """
1209
+ Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and
1210
+ cross-attention caches.
1211
+
1212
+ See `Cache` for details on common methods that are implemented by all cache classes.
1213
+
1214
+ Args:
1215
+ caches (`Iterable`):
1216
+ Usually an iterable of length 2, containing 2 `Cache` objects, the first one for self-attention, the
1217
+ second one for cross-attention. Can optionally also be an iterable of length 1, containing a
1218
+ `tuple[tuple[torch.Tensor]]` (usually used for compatibility with torch dp and ddp).
1219
+
1220
+ Example:
1221
+
1222
+ ```python
1223
+ >>> from transformers import AutoProcessor, AutoModelForCausalLM, DynamicCache, EncoderDecoderCache
1224
+
1225
+ >>> model = AutoModelForCausalLM.from_pretrained("openai/whisper-small")
1226
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-small")
1227
+
1228
+ >>> inputs = processor(audio=YOUR-AUDIO, return_tensors="pt")
1229
+
1230
+ >>> # Prepare cache classes for encoder and decoder and pass it to model's forward
1231
+ >>> self_attention_cache = DynamicCache(config=self.config)
1232
+ >>> cross_attention_cache = DynamicCache(config=self.config)
1233
+ >>> past_key_values = EncoderDecoderCache(self_attention_cache, cross_attention_cache)
1234
+ >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
1235
+ >>> outputs.past_key_values # access cache filled with key/values from generation
1236
+ EncoderDecoderCache()
1237
+ ```
1238
+ """
1239
+
1240
+ def __init__(self, *caches) -> None:
1241
+ # For dp and ddp support, if only one argument is passed, it should be an iterable of tuples of tensors
1242
+ if len(caches) == 1:
1243
+ self.self_attention_cache = DynamicCache()
1244
+ self.cross_attention_cache = DynamicCache()
1245
+ # Populate cache from the iterable
1246
+ for layer_idx, key_value_states in enumerate(caches[0]):
1247
+ key_states, value_states = key_value_states[:2]
1248
+ self.self_attention_cache.update(key_states, value_states, layer_idx)
1249
+ if len(key_value_states) > 2:
1250
+ key_states, value_states = key_value_states[2:]
1251
+ self.cross_attention_cache.update(key_states, value_states, layer_idx)
1252
+ # Otherwise, we should get two arguments, a self-attention cache and a cross-attention cache
1253
+ elif len(caches) == 2:
1254
+ if not isinstance(caches[0], Cache) or not isinstance(caches[1], Cache):
1255
+ raise TypeError(f"One of the two arguments is not a Cache: {type(caches[0]) = }, {type(caches[1]) = }")
1256
+ self.self_attention_cache = caches[0]
1257
+ self.cross_attention_cache = caches[1]
1258
+ # Error case
1259
+ else:
1260
+ raise ValueError(f"Expected 1 or 2 arguments, got {len(caches)}")
1261
+
1262
+ self.is_updated = {}
1263
+ for layer_idx in range(len(self.cross_attention_cache)):
1264
+ self.is_updated[layer_idx] = bool(self.cross_attention_cache.get_seq_length(layer_idx) > 0)
1265
+
1266
+ def __repr__(self) -> str:
1267
+ return (
1268
+ f"{self.__class__.__name__}(self_attention_cache={self.self_attention_cache}, cross_attention_cache="
1269
+ f"{self.cross_attention_cache})"
1270
+ )
1271
+
1272
+ def __iter__(self):
1273
+ """
1274
+ Support for backwards-compatible `past_key_values` iteration, e.g. `for x in past_key_values:` to iterate over
1275
+ keys and values
1276
+ """
1277
+ for layer_idx in range(len(self)):
1278
+ yield (
1279
+ self.self_attention_cache.layers[layer_idx].keys,
1280
+ self.self_attention_cache.layers[layer_idx].values,
1281
+ self.cross_attention_cache.layers[layer_idx].keys,
1282
+ self.cross_attention_cache.layers[layer_idx].values,
1283
+ )
1284
+
1285
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
1286
+ """
1287
+ Support for backwards-compatible `past_key_values` indexing, e.g. `past_key_values[0][0].shape[2]` to get the
1288
+ sequence length.
1289
+ """
1290
+ if layer_idx < len(self):
1291
+ return (
1292
+ self.self_attention_cache.layers[layer_idx].keys,
1293
+ self.self_attention_cache.layers[layer_idx].values,
1294
+ self.cross_attention_cache.layers[layer_idx].keys,
1295
+ self.cross_attention_cache.layers[layer_idx].values,
1296
+ )
1297
+ else:
1298
+ raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
1299
+
1300
+ def __len__(self):
1301
+ """
1302
+ Support for backwards-compatible `past_key_values` length, e.g. `len(past_key_values)`. This value corresponds
1303
+ to the number of layers in the model.
1304
+ """
1305
+ return len(self.self_attention_cache)
1306
+
1307
+ def to_legacy_cache(self) -> tuple[tuple[torch.Tensor]]:
1308
+ """Converts the `EncoderDecoderCache` instance into its equivalent in the legacy cache format."""
1309
+ legacy_cache = ()
1310
+ if len(self.cross_attention_cache) > 0:
1311
+ for self_attn, cross_attn in zip(
1312
+ self.self_attention_cache.to_legacy_cache(), self.cross_attention_cache.to_legacy_cache()
1313
+ ):
1314
+ legacy_cache += (self_attn + cross_attn,)
1315
+ else:
1316
+ legacy_cache = self.self_attention_cache.to_legacy_cache()
1317
+ return legacy_cache
1318
+
1319
+ @classmethod
1320
+ def from_legacy_cache(
1321
+ cls, past_key_values: Optional[Iterable[tuple[torch.FloatTensor, ...]]]
1322
+ ) -> "EncoderDecoderCache":
1323
+ """Converts a cache in the legacy cache format into an equivalent `EncoderDecoderCache`."""
1324
+ cache = cls(DynamicCache(), DynamicCache())
1325
+ if past_key_values is None:
1326
+ logger.warning_once("past_key_values should not be None in from_legacy_cache()")
1327
+ else:
1328
+ for layer_idx, key_value_states in enumerate(past_key_values):
1329
+ key_states, value_states = key_value_states[:2]
1330
+ cache.self_attention_cache.update(key_states, value_states, layer_idx)
1331
+ if len(key_value_states) > 2:
1332
+ key_states, value_states = key_value_states[2:]
1333
+ cache.cross_attention_cache.update(key_states, value_states, layer_idx)
1334
+ cache.is_updated[layer_idx] = True
1335
+ return cache
1336
+
1337
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
1338
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
1339
+ return self.self_attention_cache.get_seq_length(layer_idx)
1340
+
1341
+ def reset(self):
1342
+ self.self_attention_cache.reset()
1343
+ self.cross_attention_cache.reset()
1344
+ for layer_idx in self.is_updated:
1345
+ self.is_updated[layer_idx] = False
1346
+
1347
+ def reorder_cache(self, beam_idx: torch.LongTensor):
1348
+ """Reorders the cache for beam search, given the selected beam indices."""
1349
+ self.self_attention_cache.reorder_cache(beam_idx)
1350
+ self.cross_attention_cache.reorder_cache(beam_idx)
1351
+
1352
+ def check_dynamic_cache(self, method: str):
1353
+ if not (
1354
+ isinstance(self.self_attention_cache, DynamicCache)
1355
+ and isinstance(self.cross_attention_cache, DynamicCache)
1356
+ ):
1357
+ raise ValueError(
1358
+ f"`{method}` is only defined for dynamic cache, got {self.self_attention_cache.__str__()} for the self "
1359
+ f"attention cache and {self.cross_attention_cache.__str__()} for the cross attention cache."
1360
+ )
1361
+
1362
+ # TODO(gante, sanchit-gandhi): move following functionality into `.generate`
1363
+ def crop(self, maximum_length: int):
1364
+ """
1365
+ Crop the past key values up to a new `maximum_length` in terms of tokens. `maximum_length` can also be
1366
+ negative to remove `maximum_length` tokens. This is used in assisted decoding and contrastive search (on the Hub).
1367
+ """
1368
+ self.check_dynamic_cache(self.crop.__name__)
1369
+ self.self_attention_cache.crop(maximum_length)
1370
+
1371
+ def batch_split(self, full_batch_size: int, split_size: int) -> "list[EncoderDecoderCache]":
1372
+ """
1373
+ Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
1374
+ `_split_model_inputs()` in `generation.utils`
1375
+ """
1376
+ self.check_dynamic_cache(self.batch_split.__name__)
1377
+ self_attention_cache = self.self_attention_cache.batch_split(full_batch_size, split_size)
1378
+ cross_attention_cache = self.cross_attention_cache.batch_split(full_batch_size, split_size)
1379
+
1380
+ out = []
1381
+ for self_attn, cross_attn in zip(self_attention_cache, cross_attention_cache):
1382
+ out.append(EncoderDecoderCache(self_attn, cross_attn))
1383
+ return out
1384
+
1385
+ def batch_repeat_interleave(self, repeats: int):
1386
+ """Repeat the cache `repeats` times in the batch dimension. Used in contrastive search (on the Hub)."""
1387
+ self.check_dynamic_cache(self.batch_repeat_interleave.__name__)
1388
+ self.self_attention_cache.batch_repeat_interleave(repeats)
1389
+ self.cross_attention_cache.batch_repeat_interleave(repeats)
1390
+
1391
+ def batch_select_indices(self, indices: torch.Tensor):
1392
+ """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search (on the Hub)."""
1393
+ self.check_dynamic_cache(self.batch_select_indices.__name__)
1394
+ self.self_attention_cache.batch_select_indices(indices)
1395
+ self.cross_attention_cache.batch_select_indices(indices)
1396
+
1397
+ def get_max_cache_shape(self) -> int:
1398
+ """Returns the maximum sequence length (i.e. max capacity) of the cache object"""
1399
+ return self.self_attention_cache.get_max_cache_shape()
1400
+
1401
+ def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
1402
+ return self.self_attention_cache.get_mask_sizes(cache_position, layer_idx)
1403
+
1404
+ @property
1405
+ def is_sliding(self):
1406
+ return self.self_attention_cache.is_sliding
1407
+
1408
+ @property
1409
+ def is_compileable(self) -> bool:
1410
+ return self.self_attention_cache.is_compileable
1411
+
1412
+
1413
+ ### Deprecated classes
1414
+
1415
+
1416
+ class OffloadedCache(DynamicCache):
1417
+ def __init__(self) -> None:
1418
+ logger.warning_once(
1419
+ "`OffloadedCache` is deprecated and will be removed in version v4.59 "
1420
+ "Use `DynamicCache(offloading=True)` instead"
1421
+ )
1422
+ super().__init__(offloading=True)
1423
+
1424
+
1425
+ class OffloadedStaticCache(StaticCache):
1426
+ def __init__(self, config: PretrainedConfig, max_cache_len: int, *args, **kwargs):
1427
+ logger.warning_once(
1428
+ "`OffloadedStaticCache` is deprecated and will be removed in version v4.59 "
1429
+ "Use `StaticCache(..., offloading=True)` instead"
1430
+ )
1431
+ super().__init__(config=config, max_cache_len=max_cache_len, offloading=True)
1432
+
1433
+
1434
+ class SlidingWindowCache(StaticCache):
1435
+ def __init__(self, config: PretrainedConfig, max_cache_len: int, *args, **kwargs):
1436
+ logger.warning_once(
1437
+ "`SlidingWindowCache` is deprecated and will be removed in version v4.59 "
1438
+ "Use `StaticCache(...)` instead which will correctly infer the type of each layer."
1439
+ )
1440
+ super().__init__(config=config, max_cache_len=max_cache_len)
1441
+
1442
+
1443
+ class HybridCache(StaticCache):
1444
+ def __init__(self, config: PretrainedConfig, max_cache_len: int, *args, **kwargs):
1445
+ logger.warning_once(
1446
+ "`HybridCache` is deprecated and will be removed in version v4.59 "
1447
+ "Use `StaticCache(...)` instead which will correctly infer the type of each layer."
1448
+ )
1449
+ super().__init__(config=config, max_cache_len=max_cache_len)
1450
+
1451
+
1452
+ class HybridChunkedCache(StaticCache):
1453
+ def __init__(self, config: PretrainedConfig, max_cache_len: int, *args, **kwargs):
1454
+ logger.warning_once(
1455
+ "`HybridChunkedCache` is deprecated and will be removed in version v4.59 "
1456
+ "Use `StaticCache(...)` instead which will correctly infer the type of each layer."
1457
+ )
1458
+ super().__init__(config=config, max_cache_len=max_cache_len)
1459
+
1460
+
1461
+ class OffloadedHybridCache(StaticCache):
1462
+ def __init__(self, config: PretrainedConfig, max_cache_len: int, *args, **kwargs):
1463
+ logger.warning_once(
1464
+ "`OffloadedHybridCache` is deprecated and will be removed in version v4.59 "
1465
+ "Use `StaticCache(..., offload=True)` instead which will correctly infer the type of each layer."
1466
+ )
1467
+ super().__init__(config=config, max_cache_len=max_cache_len, offloading=True)
1468
+
1469
+
1470
+ class QuantoQuantizedCache(QuantizedCache):
1471
+ def __init__(
1472
+ self,
1473
+ config: PretrainedConfig,
1474
+ nbits: int = 4,
1475
+ axis_key: int = 0,
1476
+ axis_value: int = 0,
1477
+ q_group_size: int = 64,
1478
+ residual_length: int = 128,
1479
+ ):
1480
+ logger.warning_once(
1481
+ "`QuantoQuantizedCache` is deprecated and will be removed in version v4.59 "
1482
+ "Use `QuantizedCache(backend='quanto', ...)` instead."
1483
+ )
1484
+ super().__init__("quanto", config, nbits, axis_key, axis_value, q_group_size, residual_length)
1485
+
1486
+
1487
+ class HQQQuantizedCache(QuantizedCache):
1488
+ def __init__(
1489
+ self,
1490
+ config: PretrainedConfig,
1491
+ nbits: int = 4,
1492
+ axis_key: int = 0,
1493
+ axis_value: int = 0,
1494
+ q_group_size: int = 64,
1495
+ residual_length: int = 128,
1496
+ ):
1497
+ logger.warning_once(
1498
+ "`HQQQuantizedCache` is deprecated and will be removed in version v4.59 "
1499
+ "Use `QuantizedCache(backend='hqq', ...)` instead."
1500
+ )
1501
+ super().__init__("hqq", config, nbits, axis_key, axis_value, q_group_size, residual_length)
1502
+
1503
+
1504
+ class SinkCache(Cache):
1505
+ """
1506
+ It is now a `custom_generate` repository on the Hub: https://huggingface.co/transformers-community/sink_cache.
1507
+ See [these docs](https://huggingface.co/docs/transformers/generation_strategies#custom-decoding-methods) for
1508
+ general `custom_generate`usage.
1509
+ """
1510
+
1511
+ # TODO (joao, manuel): Remove this class in v4.59.0
1512
+ def __init__(self, **kwargs) -> None:
1513
+ raise NotImplementedError(
1514
+ "`SinkCache` has been moved as a `custom_generate` repository on the Hub: "
1515
+ "https://huggingface.co/transformers-community/sink_cache. See the repository for usage examples."
1516
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ from abc import ABC, abstractmethod
16
+ from argparse import ArgumentParser
17
+
18
+
19
+ class BaseTransformersCLICommand(ABC):
20
+ @staticmethod
21
+ @abstractmethod
22
+ def register_subcommand(parser: ArgumentParser):
23
+ raise NotImplementedError()
24
+
25
+ @abstractmethod
26
+ def run(self):
27
+ raise NotImplementedError()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/add_fast_image_processor.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ import os
16
+ import re
17
+ from argparse import ArgumentParser, Namespace
18
+ from datetime import date
19
+ from pathlib import Path
20
+
21
+ from ..utils import logging
22
+ from . import BaseTransformersCLICommand
23
+
24
+
25
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
26
+
27
+
28
+ CURRENT_YEAR = date.today().year
29
+ TRANSFORMERS_PATH = Path(__file__).parent.parent
30
+ REPO_PATH = TRANSFORMERS_PATH.parent.parent
31
+
32
+
33
+ def add_fast_image_processor_to_model_init(
34
+ fast_image_processing_module_file: str, fast_image_processor_name, model_name: str
35
+ ):
36
+ """
37
+ Add the fast image processor to the __init__.py file of the model.
38
+ """
39
+ with open(TRANSFORMERS_PATH / "models" / model_name / "__init__.py", "r", encoding="utf-8") as f:
40
+ content = f.read()
41
+
42
+ fast_image_processing_module_file = fast_image_processing_module_file.split(os.sep)[-1].replace(".py", "")
43
+
44
+ if "import *" in content:
45
+ # we have an init file in the updated format
46
+ # get the indented block after if TYPE_CHECKING: and before else:, append the new import, sort the imports and write the updated content
47
+ # Step 1: Find the block
48
+ block_regex = re.compile(
49
+ r"if TYPE_CHECKING:\n(?P<if_block>.*?)(?=\s*else:)",
50
+ re.DOTALL,
51
+ )
52
+ match = block_regex.search(content)
53
+
54
+ if not match:
55
+ raise ValueError("Couldn't find the 'if TYPE_CHECKING' block.")
56
+
57
+ block_content = match.group("if_block") # The captured import block
58
+
59
+ # Step 2: Parse existing entries
60
+ entries = block_content.split("\n")
61
+ indent = " " * (len(entries[0]) - len(entries[0].lstrip()))
62
+ new_entry = f"{indent}from .{fast_image_processing_module_file} import *"
63
+ if new_entry not in entries:
64
+ entries.append(new_entry)
65
+ entries.sort()
66
+ updated_block = "\n".join(entry for entry in entries)
67
+
68
+ # Replace the original block in the content
69
+ updated_content = content[: match.start("if_block")] + updated_block + content[match.end("if_block") :]
70
+ else:
71
+ # we have an init file in the old format
72
+
73
+ # add "is_torchvision_available" import to from ...utils import (
74
+ # Regex to match import statements from transformers.utils
75
+ pattern = r"""
76
+ from\s+\.\.\.utils\s+import\s+
77
+ (?: # Non-capturing group for either:
78
+ ([\w, ]+) # 1. Single-line imports (e.g., 'a, b')
79
+ | # OR
80
+ \((.*?)\) # 2. Multi-line imports (e.g., '(a, ... b)')
81
+ )
82
+ """
83
+ regex = re.compile(pattern, re.VERBOSE | re.DOTALL)
84
+
85
+ def replacement_function(match):
86
+ # Extract existing imports
87
+ imports = (match.group(1) or match.group(2)).split(",")
88
+ imports = imports[:-1] if imports[-1] == "\n" else imports
89
+ imports = [imp.strip() for imp in imports]
90
+
91
+ # Add the new import if not already present
92
+ if "is_torchvision_available" not in imports:
93
+ imports.append("is_torchvision_available")
94
+ imports.sort()
95
+
96
+ # Convert to multi-line import in all cases
97
+ updated_imports = "(\n " + ",\n ".join(imports) + ",\n)"
98
+
99
+ return f"from ...utils import {updated_imports}"
100
+
101
+ # Replace all matches in the file content
102
+ updated_content = regex.sub(replacement_function, content)
103
+
104
+ vision_import_structure_block = f' _import_structure["{fast_image_processing_module_file[:-5]}"] = ["{fast_image_processor_name[:-4]}"]\n'
105
+
106
+ added_import_structure_block = (
107
+ "try:\n if not is_torchvision_available():\n"
108
+ " raise OptionalDependencyNotAvailable()\n"
109
+ "except OptionalDependencyNotAvailable:\n"
110
+ " pass\n"
111
+ "else:\n"
112
+ f' _import_structure["{fast_image_processing_module_file}"] = ["{fast_image_processor_name}"]\n'
113
+ )
114
+
115
+ if vision_import_structure_block not in updated_content:
116
+ raise ValueError("Couldn't find the 'vision _import_structure block' block.")
117
+
118
+ if added_import_structure_block not in updated_content:
119
+ updated_content = updated_content.replace(
120
+ vision_import_structure_block, vision_import_structure_block + "\n" + added_import_structure_block
121
+ )
122
+
123
+ vision_import_statement_block = (
124
+ f" from .{fast_image_processing_module_file[:-5]} import {fast_image_processor_name[:-4]}\n"
125
+ )
126
+
127
+ added_import_statement_block = (
128
+ " try:\n if not is_torchvision_available():\n"
129
+ " raise OptionalDependencyNotAvailable()\n"
130
+ " except OptionalDependencyNotAvailable:\n"
131
+ " pass\n"
132
+ " else:\n"
133
+ f" from .{fast_image_processing_module_file} import {fast_image_processor_name}\n"
134
+ )
135
+
136
+ if vision_import_statement_block not in updated_content:
137
+ raise ValueError("Couldn't find the 'vision _import_structure block' block.")
138
+
139
+ if added_import_statement_block not in updated_content:
140
+ updated_content = updated_content.replace(
141
+ vision_import_statement_block, vision_import_statement_block + "\n" + added_import_statement_block
142
+ )
143
+
144
+ # write the updated content
145
+ with open(TRANSFORMERS_PATH / "models" / model_name / "__init__.py", "w", encoding="utf-8") as f:
146
+ f.write(updated_content)
147
+
148
+
149
+ def add_fast_image_processor_to_auto(image_processor_name: str, fast_image_processor_name: str):
150
+ """
151
+ Add the fast image processor to the auto module.
152
+ """
153
+ with open(TRANSFORMERS_PATH / "models" / "auto" / "image_processing_auto.py", "r", encoding="utf-8") as f:
154
+ content = f.read()
155
+
156
+ # get all lines containing the image processor name
157
+ updated_content = content.replace(
158
+ f'("{image_processor_name}",)', f'("{image_processor_name}", "{fast_image_processor_name}")'
159
+ )
160
+
161
+ # write the updated content
162
+ with open(TRANSFORMERS_PATH / "models" / "auto" / "image_processing_auto.py", "w", encoding="utf-8") as f:
163
+ f.write(updated_content)
164
+
165
+
166
+ def add_fast_image_processor_to_doc(fast_image_processor_name: str, model_name: str):
167
+ """
168
+ Add the fast image processor to the model's doc file.
169
+ """
170
+ doc_source = REPO_PATH / "docs" / "source"
171
+ # find the doc files
172
+ doc_files = list(doc_source.glob(f"*/model_doc/{model_name}.md"))
173
+ if not doc_files:
174
+ # try again with "-"
175
+ doc_files = list(doc_source.glob(f"*/model_doc/{model_name.replace('_', '-')}.md"))
176
+ if not doc_files:
177
+ raise ValueError(f"No doc files found for {model_name}")
178
+
179
+ base_doc_string = (
180
+ f"## {fast_image_processor_name[:-4]}\n\n[[autodoc]] {fast_image_processor_name[:-4]}\n - preprocess"
181
+ )
182
+ fast_doc_string = f"## {fast_image_processor_name}\n\n[[autodoc]] {fast_image_processor_name}\n - preprocess"
183
+
184
+ for doc_file in doc_files:
185
+ with open(doc_file, "r", encoding="utf-8") as f:
186
+ content = f.read()
187
+
188
+ if fast_doc_string not in content:
189
+ # add the fast image processor to the doc
190
+ updated_content = content.replace(
191
+ base_doc_string,
192
+ base_doc_string + "\n\n" + fast_doc_string,
193
+ )
194
+
195
+ # write the updated content
196
+ with open(doc_file, "w", encoding="utf-8") as f:
197
+ f.write(updated_content)
198
+
199
+
200
+ def add_fast_image_processor_to_tests(fast_image_processor_name: str, model_name: str):
201
+ """
202
+ Add the fast image processor to the image processing tests.
203
+ """
204
+ tests_path = REPO_PATH / "tests" / "models" / model_name
205
+ test_file = tests_path / f"test_image_processing_{model_name}.py"
206
+ if not os.path.exists(test_file):
207
+ logger.warning(f"No test file found for {model_name}. Skipping.")
208
+ return
209
+
210
+ with open(test_file, "r", encoding="utf-8") as f:
211
+ content = f.read()
212
+
213
+ # add is_torchvision_available import to the imports
214
+ # Regex to match import statements from transformers.utils
215
+ pattern = r"""
216
+ from\s+transformers\.utils\s+import\s+
217
+ (?: # Non-capturing group for either:
218
+ ([\w, ]+) # 1. Single-line imports (e.g., 'a, b')
219
+ | # OR
220
+ \((.*?)\) # 2. Multi-line imports (e.g., '(a, ... b)')
221
+ )
222
+ """
223
+ regex = re.compile(pattern, re.VERBOSE | re.DOTALL)
224
+
225
+ def replacement_function(match):
226
+ # Extract existing imports
227
+ existing_imports = (match.group(1) or match.group(2)).split(",")
228
+ existing_imports = existing_imports[:-1] if existing_imports[-1] == "\n" else existing_imports
229
+ existing_imports = [imp.strip() for imp in existing_imports]
230
+
231
+ # Add the new import if not already present
232
+ if "is_torchvision_available" not in existing_imports:
233
+ existing_imports.append("is_torchvision_available")
234
+ existing_imports.sort()
235
+
236
+ # Rebuild the import statement
237
+ if match.group(1): # Single-line import
238
+ updated_imports = ", ".join(existing_imports)
239
+ else: # Multi-line import
240
+ updated_imports = "(\n " + ",\n ".join(existing_imports) + ",\n)"
241
+
242
+ return f"from transformers.utils import {updated_imports}"
243
+
244
+ # Replace all matches in the file content
245
+ updated_content = regex.sub(replacement_function, content)
246
+
247
+ # add the fast image processor to the imports
248
+ base_import_string = f" from transformers import {fast_image_processor_name[:-4]}"
249
+ fast_import_string = (
250
+ f" if is_torchvision_available():\n from transformers import {fast_image_processor_name}"
251
+ )
252
+ if fast_import_string not in updated_content:
253
+ updated_content = updated_content.replace(base_import_string, base_import_string + "\n\n" + fast_import_string)
254
+
255
+ # get line starting with " image_processing_class = " and add a line after it starting with " fast_image_processing_class = "
256
+ image_processing_class_line = re.search(r" image_processing_class = .*", updated_content)
257
+ if not image_processing_class_line:
258
+ logger.warning(f"Couldn't find the 'image_processing_class' line in {test_file}. Skipping.")
259
+ return
260
+
261
+ fast_image_processing_class_line = (
262
+ f" fast_image_processing_class = {fast_image_processor_name} if is_torchvision_available() else None"
263
+ )
264
+ if " fast_image_processing_class = " not in updated_content:
265
+ updated_content = updated_content.replace(
266
+ image_processing_class_line.group(0),
267
+ image_processing_class_line.group(0) + "\n" + fast_image_processing_class_line,
268
+ )
269
+
270
+ # write the updated content
271
+ with open(test_file, "w", encoding="utf-8") as f:
272
+ f.write(updated_content)
273
+
274
+
275
+ def get_fast_image_processing_content_header(content: str) -> str:
276
+ """
277
+ Get the header of the slow image processor file.
278
+ """
279
+ # get all the commented lines at the beginning of the file
280
+ content_header = re.search(r"^# coding=utf-8\n(#[^\n]*\n)*", content, re.MULTILINE)
281
+ if not content_header:
282
+ logger.warning("Couldn't find the content header in the slow image processor file. Using a default header.")
283
+ return (
284
+ f"# coding=utf-8\n"
285
+ f"# Copyright {CURRENT_YEAR} The HuggingFace Team. All rights reserved.\n"
286
+ f"#\n"
287
+ f'# Licensed under the Apache License, Version 2.0 (the "License");\n'
288
+ f"# you may not use this file except in compliance with the License.\n"
289
+ f"# You may obtain a copy of the License at\n"
290
+ f"#\n"
291
+ f"# http://www.apache.org/licenses/LICENSE-2.0\n"
292
+ f"#\n"
293
+ f"# Unless required by applicable law or agreed to in writing, software\n"
294
+ f'# distributed under the License is distributed on an "AS IS" BASIS,\n'
295
+ f"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
296
+ f"# See the License for the specific language governing permissions and\n"
297
+ f"# limitations under the License.\n"
298
+ f"\n"
299
+ )
300
+ content_header = content_header.group(0)
301
+ # replace the year in the copyright
302
+ content_header = re.sub(r"# Copyright (\d+)\s", f"# Copyright {CURRENT_YEAR} ", content_header)
303
+ # get the line starting with """Image processor in content if it exists
304
+ match = re.search(r'^"""Image processor.*$', content, re.MULTILINE)
305
+ if match:
306
+ content_header += match.group(0).replace("Image processor", "Fast Image processor")
307
+
308
+ return content_header
309
+
310
+
311
+ def write_default_fast_image_processor_file(
312
+ fast_image_processing_module_file: str, fast_image_processor_name: str, content_base_file: str
313
+ ):
314
+ """
315
+ Write a default fast image processor file. Used when encountering a problem while parsing the slow image processor file.
316
+ """
317
+ imports = "\n\nfrom ...image_processing_utils_fast import BaseImageProcessorFast\n\n\n"
318
+ content_header = get_fast_image_processing_content_header(content_base_file)
319
+ content_base_file = (
320
+ f"class {fast_image_processor_name}(BaseImageProcessorFast):\n"
321
+ " # To be implemented\n"
322
+ " resample = None\n"
323
+ " image_mean = None\n"
324
+ " image_std = None\n"
325
+ " size = None\n"
326
+ " default_to_square = None\n"
327
+ " crop_size = None\n"
328
+ " do_resize = None\n"
329
+ " do_center_crop = None\n"
330
+ " do_rescale = None\n"
331
+ " do_normalize = None\n"
332
+ " do_convert_rgb = None\n\n\n"
333
+ f'__all__ = ["{fast_image_processor_name}"]\n'
334
+ )
335
+
336
+ content = content_header + imports + content_base_file
337
+
338
+ with open(fast_image_processing_module_file, "w", encoding="utf-8") as f:
339
+ f.write(content)
340
+
341
+
342
+ def add_fast_image_processor_file(
343
+ fast_image_processing_module_file: str, fast_image_processor_name: str, content_base_file: str
344
+ ):
345
+ """
346
+ Add the fast image processor file to the model's folder.
347
+ """
348
+ # if the file already exists, do nothing
349
+ if os.path.exists(fast_image_processing_module_file):
350
+ print(f"{fast_image_processing_module_file} already exists. Skipping.")
351
+ return
352
+
353
+ regex = rf"class {fast_image_processor_name[:-4]}.*?(\n\S|$)"
354
+ match = re.search(regex, content_base_file, re.DOTALL)
355
+ if not match:
356
+ print(f"Couldn't find the {fast_image_processor_name[:-4]} class in {fast_image_processing_module_file}")
357
+ print("Creating a new file with the default content.")
358
+ return write_default_fast_image_processor_file(
359
+ fast_image_processing_module_file, fast_image_processor_name, content_base_file
360
+ )
361
+ # Exclude the last unindented line
362
+ slow_class_content = match.group(0).rstrip()
363
+ # get default args:
364
+ # find the __init__ block which start with def __init__ and ends with def
365
+ match = re.search(r"def __init__.*?def ", slow_class_content, re.DOTALL)
366
+ if not match:
367
+ print(
368
+ f"Couldn't find the __init__ block for {fast_image_processor_name[:-4]} in {fast_image_processing_module_file}"
369
+ )
370
+ print("Creating a new file with the default content.")
371
+ return write_default_fast_image_processor_file(
372
+ fast_image_processing_module_file, fast_image_processor_name, content_base_file
373
+ )
374
+ init = match.group(0)
375
+ init_signature_block = init.split(")")[0]
376
+ arg_names = init_signature_block.split(":")
377
+ arg_names = [arg_name.split("\n")[-1].strip() for arg_name in arg_names]
378
+ # get the default values
379
+ default_args = re.findall(r"= (.*?)(?:,|\))", init_signature_block)
380
+
381
+ # build default args dict
382
+ default_args_dict = dict(zip(arg_names, default_args))
383
+ pattern_default_size = r"size = size if size is not None else\s+(.*)"
384
+ match_default_size = re.findall(pattern_default_size, init)
385
+ default_args_dict["size"] = match_default_size[0] if match_default_size else None
386
+ pattern_default_crop_size = r"crop_size = crop_size if crop_size is not None else\s+(.*)"
387
+ match_default_crop_size = re.findall(pattern_default_crop_size, init)
388
+ default_args_dict["crop_size"] = match_default_crop_size[0] if match_default_crop_size else None
389
+ pattern_default_image_mean = r"self.image_mean = image_mean if image_mean is not None else\s+(.*)"
390
+ match_default_image_mean = re.findall(pattern_default_image_mean, init)
391
+ default_args_dict["image_mean"] = match_default_image_mean[0] if match_default_image_mean else None
392
+ pattern_default_image_std = r"self.image_std = image_std if image_std is not None else\s+(.*)"
393
+ match_default_image_std = re.findall(pattern_default_image_std, init)
394
+ default_args_dict["image_std"] = match_default_image_std[0] if match_default_image_std else None
395
+ default_args_dict["default_to_square"] = False if "(size, default_to_square=False" in init else None
396
+
397
+ content_header = get_fast_image_processing_content_header(content_base_file)
398
+ content_base_file = (
399
+ f"@auto_docstring\n"
400
+ f"class {fast_image_processor_name}(BaseImageProcessorFast):\n"
401
+ " # This generated class can be used as a starting point for the fast image processor.\n"
402
+ " # if the image processor is only used for simple augmentations, such as resizing, center cropping, rescaling, or normalizing,\n"
403
+ " # only the default values should be set in the class.\n"
404
+ " # If the image processor requires more complex augmentations, methods from BaseImageProcessorFast can be overridden.\n"
405
+ " # In most cases, only the `_preprocess` method should be overridden.\n\n"
406
+ " # For an example of a fast image processor requiring more complex augmentations, see `LlavaNextImageProcessorFast`.\n\n"
407
+ " # Default values should be checked against the slow image processor\n"
408
+ " # None values left after checking can be removed\n"
409
+ f" resample = {default_args_dict.get('resample')}\n"
410
+ f" image_mean = {default_args_dict.get('image_mean')}\n"
411
+ f" image_std = {default_args_dict.get('image_std')}\n"
412
+ f" size = {default_args_dict.get('size')}\n"
413
+ f" default_to_square = {default_args_dict.get('default_to_square')}\n"
414
+ f" crop_size = {default_args_dict.get('crop_size')}\n"
415
+ f" do_resize = {default_args_dict.get('do_resize')}\n"
416
+ f" do_center_crop = {default_args_dict.get('do_center_crop')}\n"
417
+ f" do_rescale = {default_args_dict.get('do_rescale')}\n"
418
+ f" do_normalize = {default_args_dict.get('do_normalize')}\n"
419
+ f" do_convert_rgb = {default_args_dict.get('do_convert_rgb')}\n\n\n"
420
+ f'__all__ = ["{fast_image_processor_name}"]\n'
421
+ )
422
+
423
+ imports = "\n\nfrom ...image_processing_utils_fast import BaseImageProcessorFast\n"
424
+ image_utils_imports = []
425
+ if default_args_dict.get("resample") is not None and "PILImageResampling" in default_args_dict.get("resample"):
426
+ image_utils_imports.append("PILImageResampling")
427
+ if default_args_dict.get("image_mean") is not None and not any(
428
+ char.isdigit() for char in default_args_dict.get("image_mean")
429
+ ):
430
+ image_utils_imports.append(default_args_dict.get("image_mean"))
431
+ if default_args_dict.get("image_std") is not None and not any(
432
+ char.isdigit() for char in default_args_dict.get("image_std")
433
+ ):
434
+ image_utils_imports.append(default_args_dict.get("image_std"))
435
+
436
+ if image_utils_imports:
437
+ # sort imports
438
+ image_utils_imports.sort()
439
+ imports += f"from ...image_utils import {', '.join(image_utils_imports)}\n"
440
+
441
+ imports += "from ...utils import auto_docstring\n"
442
+
443
+ content = content_header + imports + "\n\n" + content_base_file
444
+
445
+ with open(fast_image_processing_module_file, "w", encoding="utf-8") as f:
446
+ f.write(content)
447
+
448
+
449
+ def add_fast_image_processor(model_name: str):
450
+ """
451
+ Add the necessary references to the fast image processor in the transformers package,
452
+ and create the fast image processor file in the model's folder.
453
+ """
454
+ model_module = TRANSFORMERS_PATH / "models" / model_name
455
+ image_processing_module_file = list(model_module.glob("image_processing*.py"))
456
+ if not image_processing_module_file:
457
+ raise ValueError(f"No image processing module found in {model_module}")
458
+ elif len(image_processing_module_file) > 1:
459
+ for file_name in image_processing_module_file:
460
+ if not str(file_name).endswith("_fast.py"):
461
+ image_processing_module_file = str(file_name)
462
+ break
463
+ else:
464
+ image_processing_module_file = str(image_processing_module_file[0])
465
+
466
+ with open(image_processing_module_file, "r", encoding="utf-8") as f:
467
+ content_base_file = f.read()
468
+
469
+ # regex to find object starting with "class " and ending with "ImageProcessor", including "ImageProcessor" in the match
470
+ image_processor_name = re.findall(r"class (\w*ImageProcessor)", content_base_file)
471
+ if not image_processor_name:
472
+ raise ValueError(f"No ImageProcessor class found in {image_processing_module_file}")
473
+ elif len(image_processor_name) > 1:
474
+ raise ValueError(f"Multiple ImageProcessor classes found in {image_processing_module_file}")
475
+
476
+ image_processor_name = image_processor_name[0]
477
+ fast_image_processor_name = image_processor_name + "Fast"
478
+ fast_image_processing_module_file = image_processing_module_file.replace(".py", "_fast.py")
479
+
480
+ print(f"Adding {fast_image_processor_name} to {fast_image_processing_module_file}")
481
+
482
+ add_fast_image_processor_to_model_init(
483
+ fast_image_processing_module_file=fast_image_processing_module_file,
484
+ fast_image_processor_name=fast_image_processor_name,
485
+ model_name=model_name,
486
+ )
487
+
488
+ add_fast_image_processor_to_auto(
489
+ image_processor_name=image_processor_name,
490
+ fast_image_processor_name=fast_image_processor_name,
491
+ )
492
+
493
+ add_fast_image_processor_to_doc(
494
+ fast_image_processor_name=fast_image_processor_name,
495
+ model_name=model_name,
496
+ )
497
+
498
+ add_fast_image_processor_to_tests(
499
+ fast_image_processor_name=fast_image_processor_name,
500
+ model_name=model_name,
501
+ )
502
+
503
+ add_fast_image_processor_file(
504
+ fast_image_processing_module_file=fast_image_processing_module_file,
505
+ fast_image_processor_name=fast_image_processor_name,
506
+ content_base_file=content_base_file,
507
+ )
508
+
509
+
510
+ def add_new_model_like_command_factory(args: Namespace):
511
+ return AddFastImageProcessorCommand(model_name=args.model_name)
512
+
513
+
514
+ class AddFastImageProcessorCommand(BaseTransformersCLICommand):
515
+ @staticmethod
516
+ def register_subcommand(parser: ArgumentParser):
517
+ add_fast_image_processor_parser = parser.add_parser("add-fast-image-processor")
518
+ add_fast_image_processor_parser.add_argument(
519
+ "--model-name",
520
+ type=str,
521
+ required=True,
522
+ help="The name of the folder containing the model's implementation.",
523
+ )
524
+ add_fast_image_processor_parser.set_defaults(func=add_new_model_like_command_factory)
525
+
526
+ def __init__(self, model_name: str, *args):
527
+ self.model_name = model_name
528
+
529
+ def run(self):
530
+ add_fast_image_processor(model_name=self.model_name)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/add_new_model_like.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import difflib
15
+ import os
16
+ import re
17
+ import subprocess
18
+ import textwrap
19
+ from argparse import ArgumentParser, Namespace
20
+ from datetime import date
21
+ from pathlib import Path
22
+ from typing import Any, Callable, Optional, Union
23
+
24
+ from ..models.auto.configuration_auto import CONFIG_MAPPING_NAMES, MODEL_NAMES_MAPPING
25
+ from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES
26
+ from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES
27
+ from ..models.auto.processing_auto import PROCESSOR_MAPPING_NAMES
28
+ from ..models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES
29
+ from ..models.auto.video_processing_auto import VIDEO_PROCESSOR_MAPPING_NAMES
30
+ from ..utils import is_libcst_available
31
+ from . import BaseTransformersCLICommand
32
+ from .add_fast_image_processor import add_fast_image_processor
33
+
34
+
35
+ # We protect this import to avoid requiring it for all `transformers` CLI commands - however it is actually
36
+ # strictly required for this one (we need it both for modular and for the following Visitor)
37
+ if is_libcst_available():
38
+ import libcst as cst
39
+ from libcst import CSTVisitor
40
+ from libcst import matchers as m
41
+
42
+ class ClassFinder(CSTVisitor):
43
+ """
44
+ A visitor to find all classes in a python module.
45
+ """
46
+
47
+ def __init__(self):
48
+ self.classes: list = []
49
+ self.public_classes: list = []
50
+ self.is_in_class = False
51
+
52
+ def visit_ClassDef(self, node: cst.ClassDef) -> None:
53
+ """Record class names. We assume classes always only appear at top-level (i.e. no class definition in function or similar)"""
54
+ self.classes.append(node.name.value)
55
+ self.is_in_class = True
56
+
57
+ def leave_ClassDef(self, node: cst.ClassDef):
58
+ self.is_in_class = False
59
+
60
+ def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine):
61
+ """Record all public classes inside the `__all__` assignment."""
62
+ simple_top_level_assign_structure = m.SimpleStatementLine(
63
+ body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])]
64
+ )
65
+ if not self.is_in_class and m.matches(node, simple_top_level_assign_structure):
66
+ assigned_variable = node.body[0].targets[0].target.value
67
+ if assigned_variable == "__all__":
68
+ elements = node.body[0].value.elements
69
+ self.public_classes = [element.value.value for element in elements]
70
+
71
+
72
+ CURRENT_YEAR = date.today().year
73
+ TRANSFORMERS_PATH = Path(__file__).parent.parent
74
+ REPO_PATH = TRANSFORMERS_PATH.parent.parent
75
+
76
+ COPYRIGHT = f"""
77
+ # coding=utf-8
78
+ # Copyright {CURRENT_YEAR} the HuggingFace Team. All rights reserved.
79
+ #
80
+ # Licensed under the Apache License, Version 2.0 (the "License");
81
+ # you may not use this file except in compliance with the License.
82
+ # You may obtain a copy of the License at
83
+ #
84
+ # http://www.apache.org/licenses/LICENSE-2.0
85
+ #
86
+ # Unless required by applicable law or agreed to in writing, software
87
+ # distributed under the License is distributed on an "AS IS" BASIS,
88
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
89
+ # See the License for the specific language governing permissions and
90
+ # limitations under the License.
91
+ """.lstrip()
92
+
93
+
94
+ class ModelInfos:
95
+ """
96
+ Retrieve the basic informations about an existing model classes.
97
+ """
98
+
99
+ def __init__(self, lowercase_name: str):
100
+ # Just to make sure it's indeed lowercase
101
+ self.lowercase_name = lowercase_name.lower().replace(" ", "_").replace("-", "_")
102
+ if self.lowercase_name not in CONFIG_MAPPING_NAMES:
103
+ self.lowercase_name.replace("_", "-")
104
+ if self.lowercase_name not in CONFIG_MAPPING_NAMES:
105
+ raise ValueError(f"{lowercase_name} is not a valid model name")
106
+
107
+ self.paper_name = MODEL_NAMES_MAPPING[self.lowercase_name]
108
+ self.config_class = CONFIG_MAPPING_NAMES[self.lowercase_name]
109
+ self.camelcase_name = self.config_class.replace("Config", "")
110
+
111
+ # Get tokenizer class
112
+ if self.lowercase_name in TOKENIZER_MAPPING_NAMES:
113
+ self.tokenizer_class, self.fast_tokenizer_class = TOKENIZER_MAPPING_NAMES[self.lowercase_name]
114
+ self.fast_tokenizer_class = (
115
+ None if self.fast_tokenizer_class == "PreTrainedTokenizerFast" else self.fast_tokenizer_class
116
+ )
117
+ else:
118
+ self.tokenizer_class, self.fast_tokenizer_class = None, None
119
+
120
+ self.image_processor_class, self.fast_image_processor_class = IMAGE_PROCESSOR_MAPPING_NAMES.get(
121
+ self.lowercase_name, (None, None)
122
+ )
123
+ self.video_processor_class = VIDEO_PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None)
124
+ self.feature_extractor_class = FEATURE_EXTRACTOR_MAPPING_NAMES.get(self.lowercase_name, None)
125
+ self.processor_class = PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None)
126
+
127
+
128
+ def add_content_to_file(file_name: Union[str, os.PathLike], new_content: str, add_after: str):
129
+ """
130
+ A utility to add some content inside a given file.
131
+
132
+ Args:
133
+ file_name (`str` or `os.PathLike`):
134
+ The name of the file in which we want to insert some content.
135
+ new_content (`str`):
136
+ The content to add.
137
+ add_after (`str`):
138
+ The new content is added just after the first instance matching it.
139
+ """
140
+ with open(file_name, "r", encoding="utf-8") as f:
141
+ old_content = f.read()
142
+
143
+ before, after = old_content.split(add_after, 1)
144
+ new_content = before + add_after + new_content + after
145
+
146
+ with open(file_name, "w", encoding="utf-8") as f:
147
+ f.write(new_content)
148
+
149
+
150
+ def add_model_to_auto_mappings(
151
+ old_model_infos: ModelInfos,
152
+ new_lowercase_name: str,
153
+ new_model_paper_name: str,
154
+ filenames_to_add: list[tuple[str, bool]],
155
+ ):
156
+ """
157
+ Add a model to all the relevant mappings in the auto module.
158
+
159
+ Args:
160
+ old_model_infos (`ModelInfos`):
161
+ The structure containing the class informations of the old model.
162
+ new_lowercase_name (`str`):
163
+ The new lowercase model name.
164
+ new_model_paper_name (`str`):
165
+ The fully cased name (as in the official paper name) of the new model.
166
+ filenames_to_add (`list[tuple[str, bool]]`):
167
+ A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we
168
+ should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...]
169
+ """
170
+ new_cased_name = "".join(x.title() for x in new_lowercase_name.replace("-", "_").split("_"))
171
+ old_lowercase_name = old_model_infos.lowercase_name
172
+ old_cased_name = old_model_infos.camelcase_name
173
+ filenames_to_add = [
174
+ (filename.replace(old_lowercase_name, "auto"), to_add) for filename, to_add in filenames_to_add[1:]
175
+ ]
176
+ # fast tokenizer/image processor have the same auto mappings as normal ones
177
+ corrected_filenames_to_add = []
178
+ for file, to_add in filenames_to_add:
179
+ if re.search(r"(?:tokenization)|(?:image_processing)_auto_fast.py", file):
180
+ previous_file, previous_to_add = corrected_filenames_to_add[-1]
181
+ corrected_filenames_to_add[-1] = (previous_file, previous_to_add or to_add)
182
+ else:
183
+ corrected_filenames_to_add.append((file, to_add))
184
+
185
+ # Add the config mappings directly as the handling for config is a bit different
186
+ add_content_to_file(
187
+ TRANSFORMERS_PATH / "models" / "auto" / "configuration_auto.py",
188
+ new_content=f' ("{new_lowercase_name}", "{new_cased_name}Config"),\n',
189
+ add_after="CONFIG_MAPPING_NAMES = OrderedDict[str, str](\n [\n # Add configs here\n",
190
+ )
191
+ add_content_to_file(
192
+ TRANSFORMERS_PATH / "models" / "auto" / "configuration_auto.py",
193
+ new_content=f' ("{new_lowercase_name}", "{new_model_paper_name}"),\n',
194
+ add_after="MODEL_NAMES_MAPPING = OrderedDict[str, str](\n [\n # Add full (and cased) model names here\n",
195
+ )
196
+
197
+ for filename, to_add in corrected_filenames_to_add:
198
+ if to_add:
199
+ # The auto mapping
200
+ filename = filename.replace("_fast.py", ".py")
201
+ with open(TRANSFORMERS_PATH / "models" / "auto" / filename) as f:
202
+ file = f.read()
203
+ # The regex has to be a bit complex like this as the tokenizer mapping has new lines everywhere
204
+ matching_lines = re.findall(
205
+ rf'( {{8,12}}\(\s*"{old_lowercase_name}",.*?\),\n)(?: {{4,12}}\(|\])', file, re.DOTALL
206
+ )
207
+ for match in matching_lines:
208
+ add_content_to_file(
209
+ TRANSFORMERS_PATH / "models" / "auto" / filename,
210
+ new_content=match.replace(old_lowercase_name, new_lowercase_name).replace(
211
+ old_cased_name, new_cased_name
212
+ ),
213
+ add_after=match,
214
+ )
215
+
216
+
217
+ def create_doc_file(new_paper_name: str, public_classes: list[str]):
218
+ """
219
+ Create a new doc file to fill for the new model.
220
+
221
+ Args:
222
+ new_paper_name (`str`):
223
+ The fully cased name (as in the official paper name) of the new model.
224
+ public_classes (`list[str]`):
225
+ A list of all the public classes that the model will have in the library.
226
+ """
227
+ added_note = (
228
+ "\n\n⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that "
229
+ "may not be rendered properly in your Markdown viewer.\n\n-->\n\n"
230
+ )
231
+ copyright_for_markdown = re.sub(r"# ?", "", COPYRIGHT).replace("coding=utf-8\n", "<!--") + added_note
232
+
233
+ doc_template = textwrap.dedent(
234
+ f"""
235
+ # {new_paper_name}
236
+
237
+ ## Overview
238
+
239
+ The {new_paper_name} model was proposed in [<INSERT PAPER NAME HERE>](<INSERT PAPER LINK HERE>) by <INSERT AUTHORS HERE>.
240
+ <INSERT SHORT SUMMARY HERE>
241
+
242
+ The abstract from the paper is the following:
243
+
244
+ <INSERT PAPER ABSTRACT HERE>
245
+
246
+ Tips:
247
+
248
+ <INSERT TIPS ABOUT MODEL HERE>
249
+
250
+ This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/<INSERT YOUR HF USERNAME HERE>).
251
+ The original code can be found [here](<INSERT LINK TO GITHUB REPO HERE>).
252
+
253
+ ## Usage examples
254
+
255
+ <INSERT SOME NICE EXAMPLES HERE>
256
+
257
+ """
258
+ )
259
+
260
+ # Add public classes doc
261
+ doc_for_classes = []
262
+ for class_ in public_classes:
263
+ doc = f"## {class_}\n\n[[autodoc]] {class_}"
264
+ if "Model" in class_:
265
+ doc += "\n - forward"
266
+ doc_for_classes.append(doc)
267
+
268
+ class_doc = "\n\n".join(doc_for_classes)
269
+
270
+ return copyright_for_markdown + doc_template + class_doc
271
+
272
+
273
+ def insert_model_in_doc_toc(old_lowercase_name: str, new_lowercase_name: str, new_model_paper_name: str):
274
+ """
275
+ Insert the new model in the doc `_toctree.yaml`, in the same section as the old model.
276
+
277
+ Args:
278
+ old_lowercase_name (`str`):
279
+ The old lowercase model name.
280
+ new_lowercase_name (`str`):
281
+ The old lowercase model name.
282
+ new_model_paper_name (`str`):
283
+ The fully cased name (as in the official paper name) of the new model.
284
+ """
285
+ toc_file = REPO_PATH / "docs" / "source" / "en" / "_toctree.yml"
286
+ with open(toc_file, "r") as f:
287
+ content = f.read()
288
+
289
+ old_model_toc = re.search(rf"- local: model_doc/{old_lowercase_name}\n {{8}}title: .*?\n", content).group(0)
290
+ new_toc = f" - local: model_doc/{new_lowercase_name}\n title: {new_model_paper_name}\n"
291
+ add_content_to_file(
292
+ REPO_PATH / "docs" / "source" / "en" / "_toctree.yml", new_content=new_toc, add_after=old_model_toc
293
+ )
294
+
295
+
296
+ def create_init_file(old_lowercase_name: str, new_lowercase_name: str, filenames_to_add: list[tuple[str, bool]]):
297
+ """
298
+ Create the `__init__.py` file to add in the new model folder.
299
+
300
+ Args:
301
+ old_lowercase_name (`str`):
302
+ The old lowercase model name.
303
+ new_lowercase_name (`str`):
304
+ The new lowercase model name.
305
+ filenames_to_add (`list[tuple[str, bool]]`):
306
+ A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we
307
+ should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...]
308
+ """
309
+ filenames_to_add = [
310
+ (filename.replace(old_lowercase_name, new_lowercase_name).replace(".py", ""), to_add)
311
+ for filename, to_add in filenames_to_add
312
+ ]
313
+ imports = "\n ".join(f"from .{file} import *" for file, to_add in filenames_to_add if to_add)
314
+ init_file = COPYRIGHT + textwrap.dedent(
315
+ f"""
316
+ from typing import TYPE_CHECKING
317
+
318
+ from ...utils import _LazyModule
319
+ from ...utils.import_utils import define_import_structure
320
+
321
+
322
+ if TYPE_CHECKING:
323
+ {imports}
324
+ else:
325
+ import sys
326
+
327
+ _file = globals()["__file__"]
328
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
329
+ """
330
+ )
331
+ return init_file
332
+
333
+
334
+ def find_all_classes_from_file(module_name: str) -> set:
335
+ """
336
+ Find the name of all classes defined in `module_name`, including public ones (defined in `__all__`).
337
+
338
+ Args:
339
+ module_name (`str`):
340
+ The full path to the python module from which to extract classes.
341
+ """
342
+ with open(module_name, "r", encoding="utf-8") as file:
343
+ source_code = file.read()
344
+ module = cst.parse_module(source_code)
345
+ visitor = ClassFinder()
346
+ module.visit(visitor)
347
+ return visitor.classes, visitor.public_classes
348
+
349
+
350
+ def find_modular_structure(
351
+ module_name: str, old_model_infos: ModelInfos, new_cased_name: str
352
+ ) -> tuple[str, str, list]:
353
+ """
354
+ Extract the modular structure that will be needed to copy a file `module_name` using modular.
355
+
356
+ Args:
357
+ module_name (`str`):
358
+ The full path to the python module to copy with modular.
359
+ old_model_infos (`ModelInfos`):
360
+ The structure containing the class informations of the old model.
361
+ new_cased_name (`str`):
362
+ The new cased model name.
363
+ """
364
+ all_classes, public_classes = find_all_classes_from_file(module_name)
365
+ import_location = ".".join(module_name.parts[-2:]).replace(".py", "")
366
+ old_cased_name = old_model_infos.camelcase_name
367
+ imports = f"from ..{import_location} import {', '.join(class_ for class_ in all_classes)}"
368
+ modular_classes = "\n\n".join(
369
+ f"class {class_.replace(old_cased_name, new_cased_name)}({class_}):\n pass" for class_ in all_classes
370
+ )
371
+ public_classes = [class_.replace(old_cased_name, new_cased_name) for class_ in public_classes]
372
+ return imports, modular_classes, public_classes
373
+
374
+
375
+ def create_modular_file(
376
+ old_model_infos: ModelInfos,
377
+ new_lowercase_name: str,
378
+ filenames_to_add: list[tuple[str, bool]],
379
+ ) -> str:
380
+ """
381
+ Create a new modular file which will copy the old model, based on the new name and the different filenames
382
+ (modules) to add.
383
+
384
+ Args:
385
+ old_model_infos (`ModelInfos`):
386
+ The structure containing the class informations of the old model.
387
+ new_lowercase_name (`str`):
388
+ The new lowercase model name.
389
+ filenames_to_add (`list[tuple[str, bool]]`):
390
+ A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we
391
+ should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...]
392
+ """
393
+ new_cased_name = "".join(x.title() for x in new_lowercase_name.replace("-", "_").split("_"))
394
+ old_lowercase_name = old_model_infos.lowercase_name
395
+ old_folder_root = TRANSFORMERS_PATH / "models" / old_lowercase_name
396
+
397
+ # Construct the modular file from the original (old) model, by subclassing each class
398
+ all_imports = ""
399
+ all_bodies = ""
400
+ all_public_classes = []
401
+ for filename, to_add in filenames_to_add:
402
+ if to_add:
403
+ imports, body, public_classes = find_modular_structure(
404
+ old_folder_root / filename, old_model_infos, new_cased_name
405
+ )
406
+ all_imports += f"\n{imports}"
407
+ all_bodies += f"\n\n{body}"
408
+ all_public_classes.extend(public_classes)
409
+
410
+ # Create the __all__ assignment
411
+ public_classes_formatted = "\n ".join(f"{public_class}," for public_class in all_public_classes)
412
+ all_statement = textwrap.dedent(
413
+ f"""
414
+
415
+ __all__ = [
416
+ {public_classes_formatted}
417
+ ]
418
+ """
419
+ )
420
+ # Create the whole modular file
421
+ modular_file = COPYRIGHT + all_imports + all_bodies + all_statement
422
+ # Remove outer explicit quotes "" around the public class names before returning them
423
+ all_public_classes = [public_class.replace('"', "") for public_class in all_public_classes]
424
+ return modular_file, all_public_classes
425
+
426
+
427
+ def create_test_files(old_model_infos: ModelInfos, new_lowercase_name, filenames_to_add: list[tuple[str, bool]]):
428
+ """
429
+ Create the test files for the new model. It basically copies over the old test files and adjust the class names.
430
+
431
+ Args:
432
+ old_model_infos (`ModelInfos`):
433
+ The structure containing the class informations of the old model.
434
+ new_lowercase_name (`str`):
435
+ The new lowercase model name.
436
+ filenames_to_add (`list[tuple[str, bool]]`):
437
+ A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we
438
+ should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...]
439
+ """
440
+ new_cased_name = "".join(x.title() for x in new_lowercase_name.replace("-", "_").split("_"))
441
+ old_lowercase_name = old_model_infos.lowercase_name
442
+ old_cased_name = old_model_infos.camelcase_name
443
+ filenames_to_add = [
444
+ ("test_" + filename.replace(old_lowercase_name, new_lowercase_name), to_add)
445
+ for filename, to_add in filenames_to_add[1:]
446
+ ]
447
+ # fast tokenizer/image processor have the same test files as normal ones
448
+ corrected_filenames_to_add = []
449
+ for file, to_add in filenames_to_add:
450
+ if re.search(rf"test_(?:tokenization)|(?:image_processing)_{new_lowercase_name}_fast.py", file):
451
+ previous_file, previous_to_add = corrected_filenames_to_add[-1]
452
+ corrected_filenames_to_add[-1] = (previous_file, previous_to_add or to_add)
453
+ else:
454
+ corrected_filenames_to_add.append((file, to_add))
455
+
456
+ test_files = {}
457
+ for new_file, to_add in corrected_filenames_to_add:
458
+ if to_add:
459
+ original_test_file = new_file.replace(new_lowercase_name, old_lowercase_name)
460
+ original_test_path = REPO_PATH / "tests" / "models" / old_lowercase_name / original_test_file
461
+ # Sometimes, tests may not exist
462
+ if not original_test_path.is_file():
463
+ continue
464
+ with open(original_test_path, "r") as f:
465
+ test_code = f.read()
466
+ # Remove old copyright and add new one
467
+ test_lines = test_code.split("\n")
468
+ idx = 0
469
+ while test_lines[idx].startswith("#"):
470
+ idx += 1
471
+ test_code = COPYRIGHT + "\n".join(test_lines[idx:])
472
+ test_files[new_file] = test_code.replace(old_cased_name, new_cased_name)
473
+
474
+ return test_files
475
+
476
+
477
+ def create_new_model_like(
478
+ old_model_infos: ModelInfos,
479
+ new_lowercase_name: str,
480
+ new_model_paper_name: str,
481
+ filenames_to_add: list[tuple[str, bool]],
482
+ create_fast_image_processor: bool,
483
+ ):
484
+ """
485
+ Creates a new model module like a given model of the Transformers library.
486
+
487
+ Args:
488
+ old_model_infos (`ModelInfos`):
489
+ The structure containing the class informations of the old model.
490
+ new_lowercase_name (`str`):
491
+ The new lowercase model name.
492
+ new_model_paper_name (`str`):
493
+ The fully cased name (as in the official paper name) of the new model.
494
+ filenames_to_add (`list[tuple[str, bool]]`):
495
+ A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we
496
+ should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...]
497
+ create_fast_image_processor (`bool`):
498
+ If it makes sense, whether to add a fast processor as well, even if the old model does not have one.
499
+ """
500
+ # As the import was protected, raise if not present (as it's actually a hard dependency for this command)
501
+ if not is_libcst_available():
502
+ raise ValueError("You need to install `libcst` to run this command -> `pip install libcst`")
503
+
504
+ old_lowercase_name = old_model_infos.lowercase_name
505
+
506
+ # 1. We create the folder for our new model
507
+ new_module_folder = TRANSFORMERS_PATH / "models" / new_lowercase_name
508
+ os.makedirs(new_module_folder, exist_ok=True)
509
+
510
+ # 2. Create and add the modular file
511
+ modular_file, public_classes = create_modular_file(old_model_infos, new_lowercase_name, filenames_to_add)
512
+ with open(new_module_folder / f"modular_{new_lowercase_name}.py", "w") as f:
513
+ f.write(modular_file)
514
+
515
+ # 3. Create and add the __init__.py
516
+ init_file = create_init_file(old_lowercase_name, new_lowercase_name, filenames_to_add)
517
+ with open(new_module_folder / "__init__.py", "w") as f:
518
+ f.write(init_file)
519
+
520
+ # 4. Add new model to the models init
521
+ add_content_to_file(
522
+ TRANSFORMERS_PATH / "models" / "__init__.py",
523
+ new_content=f" from .{new_lowercase_name} import *\n",
524
+ add_after="if TYPE_CHECKING:\n",
525
+ )
526
+
527
+ # 5. Add model to auto mappings
528
+ add_model_to_auto_mappings(old_model_infos, new_lowercase_name, new_model_paper_name, filenames_to_add)
529
+
530
+ # 6. Add test files
531
+ tests_folder = REPO_PATH / "tests" / "models" / new_lowercase_name
532
+ os.makedirs(tests_folder, exist_ok=True)
533
+ # Add empty __init__.py
534
+ with open(tests_folder / "__init__.py", "w"):
535
+ pass
536
+ test_files = create_test_files(old_model_infos, new_lowercase_name, filenames_to_add)
537
+ for filename, content in test_files.items():
538
+ with open(tests_folder / filename, "w") as f:
539
+ f.write(content)
540
+
541
+ # 7. Add doc file
542
+ doc_file = create_doc_file(new_model_paper_name, public_classes)
543
+ with open(REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{new_lowercase_name}.md", "w") as f:
544
+ f.write(doc_file)
545
+ insert_model_in_doc_toc(old_lowercase_name, new_lowercase_name, new_model_paper_name)
546
+
547
+ # 8. Add additional fast image processor if necessary
548
+ if create_fast_image_processor:
549
+ add_fast_image_processor(model_name=new_lowercase_name)
550
+
551
+ # 9. Run linters
552
+ model_init_file = TRANSFORMERS_PATH / "models" / "__init__.py"
553
+ subprocess.run(
554
+ ["ruff", "check", new_module_folder, tests_folder, model_init_file, "--fix"],
555
+ cwd=REPO_PATH,
556
+ stdout=subprocess.DEVNULL,
557
+ )
558
+ subprocess.run(
559
+ ["ruff", "format", new_module_folder, tests_folder, model_init_file],
560
+ cwd=REPO_PATH,
561
+ stdout=subprocess.DEVNULL,
562
+ )
563
+ subprocess.run(
564
+ ["python", "utils/check_doc_toc.py", "--fix_and_overwrite"], cwd=REPO_PATH, stdout=subprocess.DEVNULL
565
+ )
566
+ subprocess.run(["python", "utils/sort_auto_mappings.py"], cwd=REPO_PATH, stdout=subprocess.DEVNULL)
567
+
568
+ # 10. Run the modular conversion
569
+ subprocess.run(
570
+ ["python", "utils/modular_model_converter.py", new_lowercase_name], cwd=REPO_PATH, stdout=subprocess.DEVNULL
571
+ )
572
+
573
+
574
+ def get_user_field(
575
+ question: str,
576
+ default_value: Optional[str] = None,
577
+ convert_to: Optional[Callable] = None,
578
+ fallback_message: Optional[str] = None,
579
+ ) -> Any:
580
+ """
581
+ A utility function that asks a question to the user to get an answer, potentially looping until it gets a valid
582
+ answer.
583
+
584
+ Args:
585
+ question (`str`):
586
+ The question to ask the user.
587
+ default_value (`str`, *optional*):
588
+ A potential default value that will be used when the answer is empty.
589
+ convert_to (`Callable`, *optional*):
590
+ If set, the answer will be passed to this function. If this function raises an error on the provided
591
+ answer, the question will be asked again.
592
+ fallback_message (`str`, *optional*):
593
+ A message that will be displayed each time the question is asked again to the user.
594
+
595
+ Returns:
596
+ `Any`: The answer provided by the user (or the default), passed through the potential conversion function.
597
+ """
598
+ if not question.endswith(" "):
599
+ question = question + " "
600
+ if default_value is not None:
601
+ question = f"{question} [{default_value}] "
602
+
603
+ valid_answer = False
604
+ while not valid_answer:
605
+ answer = input(question)
606
+ if default_value is not None and len(answer) == 0:
607
+ answer = default_value
608
+ if convert_to is not None:
609
+ try:
610
+ answer = convert_to(answer)
611
+ valid_answer = True
612
+ except Exception:
613
+ valid_answer = False
614
+ else:
615
+ valid_answer = True
616
+
617
+ if not valid_answer:
618
+ print(fallback_message)
619
+
620
+ return answer
621
+
622
+
623
+ def convert_to_bool(x: str) -> bool:
624
+ """
625
+ Converts a string to a bool.
626
+ """
627
+ if x.lower() in ["1", "y", "yes", "true"]:
628
+ return True
629
+ if x.lower() in ["0", "n", "no", "false"]:
630
+ return False
631
+ raise ValueError(f"{x} is not a value that can be converted to a bool.")
632
+
633
+
634
+ def get_user_input():
635
+ """
636
+ Ask the user for the necessary inputs to add the new model.
637
+ """
638
+ model_types = list(MODEL_NAMES_MAPPING.keys())
639
+
640
+ # Get old model type
641
+ valid_model_type = False
642
+ while not valid_model_type:
643
+ old_model_type = input(
644
+ "What model would you like to duplicate? Please provide it as lowercase, e.g. `llama`): "
645
+ )
646
+ if old_model_type in model_types:
647
+ valid_model_type = True
648
+ else:
649
+ print(f"{old_model_type} is not a valid model type.")
650
+ near_choices = difflib.get_close_matches(old_model_type, model_types)
651
+ if len(near_choices) >= 1:
652
+ if len(near_choices) > 1:
653
+ near_choices = " or ".join(near_choices)
654
+ print(f"Did you mean {near_choices}?")
655
+
656
+ old_model_infos = ModelInfos(old_model_type)
657
+
658
+ # Ask for the new model name
659
+ new_lowercase_name = get_user_field(
660
+ "What is the new model name? Please provide it as snake lowercase, e.g. `new_model`?"
661
+ )
662
+ new_model_paper_name = get_user_field(
663
+ "What is the fully cased name you would like to appear in the doc (e.g. `NeW ModEl`)? ",
664
+ default_value="".join(x.title() for x in new_lowercase_name.split("_")),
665
+ )
666
+
667
+ # Ask if we want to add individual processor classes as well
668
+ add_tokenizer = False
669
+ add_fast_tokenizer = False
670
+ add_image_processor = False
671
+ add_fast_image_processor = False
672
+ add_video_processor = False
673
+ add_feature_extractor = False
674
+ add_processor = False
675
+ if old_model_infos.tokenizer_class is not None:
676
+ add_tokenizer = get_user_field(
677
+ f"Do you want to create a new tokenizer? If `no`, it will use the same as {old_model_type} (y/n)?",
678
+ convert_to=convert_to_bool,
679
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
680
+ )
681
+ if old_model_infos.fast_tokenizer_class is not None:
682
+ add_fast_tokenizer = get_user_field(
683
+ f"Do you want to create a new fast tokenizer? If `no`, it will use the same as {old_model_type} (y/n)?",
684
+ convert_to=convert_to_bool,
685
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
686
+ )
687
+ if old_model_infos.image_processor_class is not None:
688
+ add_image_processor = get_user_field(
689
+ f"Do you want to create a new image processor? If `no`, it will use the same as {old_model_type} (y/n)?",
690
+ convert_to=convert_to_bool,
691
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
692
+ )
693
+ if old_model_infos.fast_image_processor_class is not None:
694
+ add_fast_image_processor = get_user_field(
695
+ f"Do you want to create a new fast image processor? If `no`, it will use the same as {old_model_type} (y/n)?",
696
+ convert_to=convert_to_bool,
697
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
698
+ )
699
+ if old_model_infos.video_processor_class is not None:
700
+ add_video_processor = get_user_field(
701
+ f"Do you want to create a new video processor? If `no`, it will use the same as {old_model_type} (y/n)?",
702
+ convert_to=convert_to_bool,
703
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
704
+ )
705
+ if old_model_infos.feature_extractor_class is not None:
706
+ add_feature_extractor = get_user_field(
707
+ f"Do you want to create a new feature extractor? If `no`, it will use the same as {old_model_type} (y/n)?",
708
+ convert_to=convert_to_bool,
709
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
710
+ )
711
+ if old_model_infos.processor_class is not None:
712
+ add_processor = get_user_field(
713
+ f"Do you want to create a new processor? If `no`, it will use the same as {old_model_type} (y/n)?",
714
+ convert_to=convert_to_bool,
715
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
716
+ )
717
+
718
+ old_lowercase_name = old_model_infos.lowercase_name
719
+ # A list of the old filenames, along whether we should copy them or not
720
+ filenames_to_add = (
721
+ (f"configuration_{old_lowercase_name}.py", True),
722
+ (f"modeling_{old_lowercase_name}.py", True),
723
+ (f"tokenization_{old_lowercase_name}.py", add_tokenizer),
724
+ (f"tokenization_{old_lowercase_name}_fast.py", add_fast_tokenizer),
725
+ (f"image_processing_{old_lowercase_name}.py", add_image_processor),
726
+ (f"image_processing_{old_lowercase_name}_fast.py", add_fast_image_processor),
727
+ (f"video_processing_{old_lowercase_name}.py", add_video_processor),
728
+ (f"feature_extraction_{old_lowercase_name}.py", add_feature_extractor),
729
+ (f"processing_{old_lowercase_name}.py", add_processor),
730
+ )
731
+
732
+ create_fast_image_processor = False
733
+ if add_image_processor and not add_fast_image_processor:
734
+ create_fast_image_processor = get_user_field(
735
+ "A fast image processor can be created from the slow one, but modifications might be needed. "
736
+ "Should we add a fast image processor class for this model (recommended) (y/n)? ",
737
+ convert_to=convert_to_bool,
738
+ default_value="y",
739
+ fallback_message="Please answer yes/no, y/n, true/false or 1/0.",
740
+ )
741
+
742
+ return old_model_infos, new_lowercase_name, new_model_paper_name, filenames_to_add, create_fast_image_processor
743
+
744
+
745
+ def add_new_model_like_command_factory(args: Namespace):
746
+ return AddNewModelLikeCommand(path_to_repo=args.path_to_repo)
747
+
748
+
749
+ class AddNewModelLikeCommand(BaseTransformersCLICommand):
750
+ @staticmethod
751
+ def register_subcommand(parser: ArgumentParser):
752
+ add_new_model_like_parser = parser.add_parser("add-new-model-like")
753
+ add_new_model_like_parser.add_argument(
754
+ "--path_to_repo", type=str, help="When not using an editable install, the path to the Transformers repo."
755
+ )
756
+ add_new_model_like_parser.set_defaults(func=add_new_model_like_command_factory)
757
+
758
+ def __init__(self, path_to_repo=None, *args):
759
+ (
760
+ self.old_model_infos,
761
+ self.new_lowercase_name,
762
+ self.new_model_paper_name,
763
+ self.filenames_to_add,
764
+ self.create_fast_image_processor,
765
+ ) = get_user_input()
766
+ self.path_to_repo = path_to_repo
767
+
768
+ def run(self):
769
+ if self.path_to_repo is not None:
770
+ # Adapt constants
771
+ global TRANSFORMERS_PATH
772
+ global REPO_PATH
773
+
774
+ REPO_PATH = Path(self.path_to_repo)
775
+ TRANSFORMERS_PATH = REPO_PATH / "src" / "transformers"
776
+
777
+ create_new_model_like(
778
+ old_model_infos=self.old_model_infos,
779
+ new_lowercase_name=self.new_lowercase_name,
780
+ new_model_paper_name=self.new_model_paper_name,
781
+ filenames_to_add=self.filenames_to_add,
782
+ create_fast_image_processor=self.create_fast_image_processor,
783
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/chat.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+
16
+ import asyncio
17
+ import copy
18
+ import json
19
+ import os
20
+ import platform
21
+ import re
22
+ import string
23
+ import time
24
+ from argparse import ArgumentParser, Namespace
25
+ from collections.abc import AsyncIterator
26
+ from dataclasses import dataclass, field
27
+ from threading import Thread
28
+ from typing import Optional
29
+
30
+ import yaml
31
+ from huggingface_hub import AsyncInferenceClient, ChatCompletionStreamOutput
32
+
33
+ from transformers import (
34
+ AutoTokenizer,
35
+ GenerationConfig,
36
+ PreTrainedTokenizer,
37
+ )
38
+ from transformers.commands import BaseTransformersCLICommand
39
+ from transformers.commands.serving import ServeArguments, ServeCommand
40
+ from transformers.utils import is_rich_available, is_torch_available
41
+
42
+
43
+ if platform.system() != "Windows":
44
+ import pwd
45
+
46
+ if is_rich_available():
47
+ from rich.console import Console
48
+ from rich.live import Live
49
+ from rich.markdown import Markdown
50
+
51
+ if is_torch_available():
52
+ import torch
53
+
54
+ from transformers import (
55
+ AutoModelForCausalLM,
56
+ AutoTokenizer,
57
+ BitsAndBytesConfig,
58
+ GenerationConfig,
59
+ )
60
+
61
+ ALLOWED_KEY_CHARS = set(string.ascii_letters + string.whitespace)
62
+ ALLOWED_VALUE_CHARS = set(
63
+ string.ascii_letters + string.digits + string.whitespace + r".!\"#$%&'()*+,\-/:<=>?@[]^_`{|}~"
64
+ )
65
+
66
+ DEFAULT_EXAMPLES = {
67
+ "llama": {"text": "There is a Llama in my lawn, how can I get rid of it?"},
68
+ "code": {
69
+ "text": (
70
+ "Write a Python function that integrates any Python function f(x) numerically over an arbitrary "
71
+ "interval [x_start, x_end]."
72
+ ),
73
+ },
74
+ "helicopter": {"text": "How many helicopters can a human eat in one sitting?"},
75
+ "numbers": {"text": "Count to 10 but skip every number ending with an 'e'"},
76
+ "birds": {"text": "Why aren't birds real?"},
77
+ "socks": {"text": "Why is it important to eat socks after meditating?"},
78
+ "numbers2": {"text": "Which number is larger, 9.9 or 9.11?"},
79
+ }
80
+
81
+ # Printed at the start of a chat session
82
+ HELP_STRING_MINIMAL = """
83
+
84
+ **TRANSFORMERS CHAT INTERFACE**
85
+
86
+ Chat interface to try out a model. Besides chatting with the model, here are some basic commands:
87
+ - **!help**: shows all available commands (set generation settings, save chat, etc.)
88
+ - **!status**: shows the current status of the model and generation settings
89
+ - **!clear**: clears the current conversation and starts a new one
90
+ - **!exit**: closes the interface
91
+ """
92
+
93
+
94
+ # Printed when the user types `help` in the chat session
95
+ HELP_STRING = f"""
96
+
97
+ **TRANSFORMERS CHAT INTERFACE HELP**
98
+
99
+ Full command list:
100
+ - **!help**: shows this help message
101
+ - **!clear**: clears the current conversation and starts a new one
102
+ - **!status**: shows the current status of the model and generation settings
103
+ - **!example {{NAME}}**: loads example named `{{NAME}}` from the config and uses it as the user input.
104
+ Available example names: `{"`, `".join(DEFAULT_EXAMPLES.keys())}`
105
+ - **!set {{ARG_1}}={{VALUE_1}} {{ARG_2}}={{VALUE_2}}** ...: changes the system prompt or generation settings (multiple
106
+ settings are separated by a space). Accepts the same flags and format as the `generate_flags` CLI argument.
107
+ If you're a new user, check this basic flag guide: https://huggingface.co/docs/transformers/llm_tutorial#common-options
108
+ - **!save {{SAVE_NAME}} (optional)**: saves the current chat and settings to file by default to
109
+ `./chat_history/{{MODEL_NAME}}/chat_{{DATETIME}}.yaml` or `{{SAVE_NAME}}` if provided
110
+ - **!exit**: closes the interface
111
+ """
112
+
113
+
114
+ class RichInterface:
115
+ def __init__(self, model_name: Optional[str] = None, user_name: Optional[str] = None):
116
+ self._console = Console()
117
+ if model_name is None:
118
+ self.model_name = "assistant"
119
+ else:
120
+ self.model_name = model_name
121
+ if user_name is None:
122
+ self.user_name = "user"
123
+ else:
124
+ self.user_name = user_name
125
+
126
+ async def stream_output(self, stream: AsyncIterator[ChatCompletionStreamOutput]) -> tuple[str, int]:
127
+ self._console.print(f"[bold blue]<{self.model_name}>:")
128
+ with Live(console=self._console, refresh_per_second=4) as live:
129
+ text = ""
130
+ async for token in await stream:
131
+ outputs = token.choices[0].delta.content
132
+
133
+ if not outputs:
134
+ continue
135
+
136
+ # Escapes single words encased in <>, e.g. <think> -> \<think\>, for proper rendering in Markdown.
137
+ # It only escapes single words that may have `_`, optionally following a `/` (e.g. </think>)
138
+ outputs = re.sub(r"<(/*)(\w*)>", r"\<\1\2\>", outputs)
139
+
140
+ text += outputs
141
+ # Render the accumulated text as Markdown
142
+ # NOTE: this is a workaround for the rendering "unstandard markdown"
143
+ # in rich. The chatbots output treat "\n" as a new line for
144
+ # better compatibility with real-world text. However, rendering
145
+ # in markdown would break the format. It is because standard markdown
146
+ # treat a single "\n" in normal text as a space.
147
+ # Our workaround is adding two spaces at the end of each line.
148
+ # This is not a perfect solution, as it would
149
+ # introduce trailing spaces (only) in code block, but it works well
150
+ # especially for console output, because in general the console does not
151
+ # care about trailing spaces.
152
+
153
+ lines = []
154
+ for line in text.splitlines():
155
+ lines.append(line)
156
+ if line.startswith("```"):
157
+ # Code block marker - do not add trailing spaces, as it would
158
+ # break the syntax highlighting
159
+ lines.append("\n")
160
+ else:
161
+ lines.append(" \n")
162
+
163
+ markdown = Markdown("".join(lines).strip(), code_theme="github-dark")
164
+
165
+ # Update the Live console output
166
+ live.update(markdown, refresh=True)
167
+
168
+ self._console.print()
169
+
170
+ return text
171
+
172
+ def input(self) -> str:
173
+ """Gets user input from the console."""
174
+ input = self._console.input(f"[bold red]<{self.user_name}>:\n")
175
+ self._console.print()
176
+ return input
177
+
178
+ def clear(self):
179
+ """Clears the console."""
180
+ self._console.clear()
181
+
182
+ def print_user_message(self, text: str):
183
+ """Prints a user message to the console."""
184
+ self._console.print(f"[bold red]<{self.user_name}>:[/ bold red]\n{text}")
185
+ self._console.print()
186
+
187
+ def print_color(self, text: str, color: str):
188
+ """Prints text in a given color to the console."""
189
+ self._console.print(f"[bold {color}]{text}")
190
+ self._console.print()
191
+
192
+ def print_help(self, minimal: bool = False):
193
+ """Prints the help message to the console."""
194
+ self._console.print(Markdown(HELP_STRING_MINIMAL if minimal else HELP_STRING))
195
+ self._console.print()
196
+
197
+ def print_status(self, model_name: str, generation_config: GenerationConfig, model_kwargs: dict):
198
+ """Prints the status of the model and generation settings to the console."""
199
+ self._console.print(f"[bold blue]Model: {model_name}\n")
200
+ if model_kwargs:
201
+ self._console.print(f"[bold blue]Model kwargs: {model_kwargs}")
202
+ self._console.print(f"[bold blue]{generation_config}")
203
+ self._console.print()
204
+
205
+
206
+ @dataclass
207
+ class ChatArguments:
208
+ r"""
209
+ Arguments for the chat CLI.
210
+
211
+ See the metadata arg for each argument's description -- the medatata will be printed with
212
+ `transformers chat --help`
213
+ """
214
+
215
+ # General settings
216
+ model_name_or_path: Optional[str] = field(
217
+ default=None,
218
+ metadata={
219
+ "help": "Name of the pre-trained model. The positional argument will take precedence if both are passed."
220
+ },
221
+ )
222
+ user: Optional[str] = field(
223
+ default=None,
224
+ metadata={"help": "Username to display in chat interface. Defaults to the current user's name."},
225
+ )
226
+ system_prompt: Optional[str] = field(default=None, metadata={"help": "System prompt."})
227
+ save_folder: str = field(default="./chat_history/", metadata={"help": "Folder to save chat history."})
228
+ examples_path: Optional[str] = field(default=None, metadata={"help": "Path to a yaml file with examples."})
229
+ verbose: bool = field(default=False, metadata={"help": "Whether to show runtime warnings in the chat interface."})
230
+
231
+ # Generation settings
232
+ generation_config: Optional[str] = field(
233
+ default=None,
234
+ metadata={
235
+ "help": (
236
+ "Path to a local generation config file or to a HuggingFace repo containing a "
237
+ "`generation_config.json` file. Other generation settings passed as CLI arguments will be applied on "
238
+ "top of this generation config."
239
+ ),
240
+ },
241
+ )
242
+
243
+ # Model loading
244
+ model_revision: str = field(
245
+ default="main",
246
+ metadata={"help": "Specific model version to use (can be a branch name, tag name or commit id)."},
247
+ )
248
+ device: str = field(default="auto", metadata={"help": "Device to use for inference."})
249
+ torch_dtype: Optional[str] = field(
250
+ default=None,
251
+ metadata={
252
+ "help": "`torch_dtype` is deprecated! Please use `dtype` argument instead.",
253
+ "choices": ["auto", "bfloat16", "float16", "float32"],
254
+ },
255
+ )
256
+ dtype: Optional[str] = field(
257
+ default="auto",
258
+ metadata={
259
+ "help": "Override the default `torch.dtype` and load the model under this dtype. If `'auto'` is passed, "
260
+ "the dtype will be automatically derived from the model's weights.",
261
+ "choices": ["auto", "bfloat16", "float16", "float32"],
262
+ },
263
+ )
264
+ trust_remote_code: bool = field(
265
+ default=False, metadata={"help": "Whether to trust remote code when loading a model."}
266
+ )
267
+ attn_implementation: Optional[str] = field(
268
+ default=None,
269
+ metadata={
270
+ "help": "Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in "
271
+ "which case you must install this manually by running `pip install flash-attn --no-build-isolation`."
272
+ },
273
+ )
274
+ load_in_8bit: bool = field(
275
+ default=False,
276
+ metadata={"help": "Whether to use 8 bit precision for the base model - works only with LoRA."},
277
+ )
278
+ load_in_4bit: bool = field(
279
+ default=False,
280
+ metadata={"help": "Whether to use 4 bit precision for the base model - works only with LoRA."},
281
+ )
282
+ bnb_4bit_quant_type: str = field(default="nf4", metadata={"help": "Quantization type.", "choices": ["fp4", "nf4"]})
283
+ use_bnb_nested_quant: bool = field(default=False, metadata={"help": "Whether to use nested quantization."})
284
+
285
+ # Serving settings
286
+ host: str = field(default="localhost", metadata={"help": "Interface the server will listen to.."})
287
+ port: int = field(default=8000, metadata={"help": "Port the server will listen to."})
288
+
289
+ def __post_init__(self):
290
+ """Only used for BC `torch_dtype` argument."""
291
+ # In this case only the BC torch_dtype was given
292
+ if self.torch_dtype is not None and self.dtype == "auto":
293
+ self.dtype = self.torch_dtype
294
+
295
+
296
+ def chat_command_factory(args: Namespace):
297
+ """
298
+ Factory function used to chat with a local model.
299
+ """
300
+ return ChatCommand(args)
301
+
302
+
303
+ class ChatCommand(BaseTransformersCLICommand):
304
+ @staticmethod
305
+ def register_subcommand(parser: ArgumentParser):
306
+ """
307
+ Register this command to argparse so it's available for the transformer-cli
308
+
309
+ Args:
310
+ parser: Root parser to register command-specific arguments
311
+ """
312
+ dataclass_types = (ChatArguments,)
313
+ chat_parser = parser.add_parser("chat", dataclass_types=dataclass_types)
314
+
315
+ group = chat_parser.add_argument_group("Positional arguments")
316
+ group.add_argument(
317
+ "model_name_or_path_or_address",
318
+ type=str,
319
+ default=None,
320
+ help="Name of the pre-trained model or address to connect to.",
321
+ )
322
+ group.add_argument(
323
+ "generate_flags",
324
+ type=str,
325
+ default=None,
326
+ help=(
327
+ "Flags to pass to `generate`, using a space as a separator between flags. Accepts booleans, numbers, "
328
+ "and lists of integers, more advanced parameterization should be set through --generation-config. "
329
+ "Example: `transformers chat <model_repo> max_new_tokens=100 do_sample=False eos_token_id=[1,2]`. "
330
+ "If you're a new user, check this basic flag guide: "
331
+ "https://huggingface.co/docs/transformers/llm_tutorial#common-options"
332
+ ),
333
+ nargs="*",
334
+ )
335
+ chat_parser.set_defaults(func=chat_command_factory)
336
+
337
+ def __init__(self, args):
338
+ if args.model_name_or_path_or_address is not None:
339
+ name = args.model_name_or_path_or_address
340
+ if name.startswith("http") or name.startswith("https") or name.startswith("localhost"):
341
+ self.spawn_backend = False
342
+
343
+ if args.host != "localhost" or args.port != 8000:
344
+ raise ValueError(
345
+ "Looks like you’ve set both a server address and a custom host/port. "
346
+ "Please pick just one way to specify the server."
347
+ )
348
+
349
+ args.host, args.port = args.model_name_or_path_or_address.rsplit(":", 1)
350
+
351
+ if args.model_name_or_path is None:
352
+ raise ValueError(
353
+ "When connecting to a server, please specify a model name with the --model_name_or_path flag."
354
+ )
355
+ else:
356
+ self.spawn_backend = True
357
+ args.model_name_or_path = args.model_name_or_path_or_address
358
+
359
+ if not is_rich_available() and (not is_torch_available() and self.spawn_backend):
360
+ raise ImportError(
361
+ "You need to install rich to use the chat interface. Additionally, you have not specified a remote "
362
+ "endpoint and are therefore spawning a backend. Torch is required for this: (`pip install rich torch`)"
363
+ )
364
+ elif not is_rich_available():
365
+ raise ImportError("You need to install rich to use the chat interface. (`pip install rich`)")
366
+ elif not is_torch_available() and self.spawn_backend:
367
+ raise ImportError(
368
+ "You have not specified a remote endpoint and are therefore spawning a backend. Torch is required "
369
+ "for this: (`pip install rich torch`)"
370
+ )
371
+
372
+ self.args = args
373
+
374
+ # -----------------------------------------------------------------------------------------------------------------
375
+ # Chat session methods
376
+ @staticmethod
377
+ def get_username() -> str:
378
+ """Returns the username of the current user."""
379
+ if platform.system() == "Windows":
380
+ return os.getlogin()
381
+ else:
382
+ return pwd.getpwuid(os.getuid()).pw_name
383
+
384
+ @staticmethod
385
+ def save_chat(chat, args: ChatArguments, filename: Optional[str] = None) -> str:
386
+ """Saves the chat history to a file."""
387
+ output_dict = {}
388
+ output_dict["settings"] = vars(args)
389
+ output_dict["chat_history"] = chat
390
+
391
+ folder = args.save_folder
392
+
393
+ if filename is None:
394
+ time_str = time.strftime("%Y-%m-%d_%H-%M-%S")
395
+ filename = f"{args.model_name_or_path_or_address}/chat_{time_str}.json"
396
+ filename = os.path.join(folder, filename)
397
+
398
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
399
+ with open(filename, "w") as f:
400
+ json.dump(output_dict, f, indent=4)
401
+ return os.path.abspath(filename)
402
+
403
+ @staticmethod
404
+ def clear_chat_history(system_prompt: Optional[str] = None) -> list[dict]:
405
+ """Clears the chat history."""
406
+ if system_prompt is None:
407
+ chat = []
408
+ else:
409
+ chat = [{"role": "system", "content": system_prompt}]
410
+ return chat
411
+
412
+ # -----------------------------------------------------------------------------------------------------------------
413
+ # Input parsing methods
414
+ def parse_generate_flags(self, generate_flags: list[str]) -> dict:
415
+ """Parses the generate flags from the user input into a dictionary of `generate` kwargs."""
416
+ if len(generate_flags) == 0:
417
+ return {}
418
+
419
+ # Assumption: `generate_flags` is a list of strings, each string being a `flag=value` pair, that can be parsed
420
+ # into a json string if we:
421
+ # 1. Add quotes around each flag name
422
+ generate_flags_as_dict = {'"' + flag.split("=")[0] + '"': flag.split("=")[1] for flag in generate_flags}
423
+
424
+ # 2. Handle types:
425
+ # 2. a. booleans should be lowercase, None should be null
426
+ generate_flags_as_dict = {
427
+ k: v.lower() if v.lower() in ["true", "false"] else v for k, v in generate_flags_as_dict.items()
428
+ }
429
+ generate_flags_as_dict = {k: "null" if v == "None" else v for k, v in generate_flags_as_dict.items()}
430
+
431
+ # 2. b. strings should be quoted
432
+ def is_number(s: str) -> bool:
433
+ # handle negative numbers
434
+ if s.startswith("-"):
435
+ s = s[1:]
436
+ return s.replace(".", "", 1).isdigit()
437
+
438
+ generate_flags_as_dict = {k: f'"{v}"' if not is_number(v) else v for k, v in generate_flags_as_dict.items()}
439
+ # 2. c. [no processing needed] lists are lists of ints because `generate` doesn't take lists of strings :)
440
+ # We also mention in the help message that we only accept lists of ints for now.
441
+
442
+ # 3. Join the result into a comma separated string
443
+ generate_flags_string = ", ".join([f"{k}: {v}" for k, v in generate_flags_as_dict.items()])
444
+
445
+ # 4. Add the opening/closing brackets
446
+ generate_flags_string = "{" + generate_flags_string + "}"
447
+
448
+ # 5. Remove quotes around boolean/null and around lists
449
+ generate_flags_string = generate_flags_string.replace('"null"', "null")
450
+ generate_flags_string = generate_flags_string.replace('"true"', "true")
451
+ generate_flags_string = generate_flags_string.replace('"false"', "false")
452
+ generate_flags_string = generate_flags_string.replace('"[', "[")
453
+ generate_flags_string = generate_flags_string.replace(']"', "]")
454
+
455
+ # 6. Replace the `=` with `:`
456
+ generate_flags_string = generate_flags_string.replace("=", ":")
457
+
458
+ try:
459
+ processed_generate_flags = json.loads(generate_flags_string)
460
+ except json.JSONDecodeError:
461
+ raise ValueError(
462
+ "Failed to convert `generate_flags` into a valid JSON object."
463
+ "\n`generate_flags` = {generate_flags}"
464
+ "\nConverted JSON string = {generate_flags_string}"
465
+ )
466
+ return processed_generate_flags
467
+
468
+ def get_generation_parameterization(
469
+ self, args: ChatArguments, model_generation_config: GenerationConfig
470
+ ) -> tuple[GenerationConfig, dict]:
471
+ """
472
+ Returns a GenerationConfig object holding the generation parameters for the CLI command.
473
+ """
474
+ # No generation config arg provided -> use model's default generation config, then apply CLI defaults
475
+ if args.generation_config is not None:
476
+ if ".json" in args.generation_config: # is a local file
477
+ dirname = os.path.dirname(args.generation_config)
478
+ filename = os.path.basename(args.generation_config)
479
+ generation_config = GenerationConfig.from_pretrained(dirname, filename)
480
+ else:
481
+ generation_config = GenerationConfig.from_pretrained(args.generation_config)
482
+ else:
483
+ # !!!!!!!!!
484
+ # This is a chat session, so we have a few non-standard defaults
485
+ # !!!!!!!!!
486
+ generation_config = copy.deepcopy(model_generation_config)
487
+ generation_config.update(**{"do_sample": True, "max_new_tokens": 256})
488
+
489
+ # Finally: parse and apply `generate_flags`
490
+ parsed_generate_flags = self.parse_generate_flags(args.generate_flags)
491
+ model_kwargs = generation_config.update(**parsed_generate_flags)
492
+ # `model_kwargs` contain non-generation flags in `parsed_generate_flags` that should be passed directly to
493
+ # `generate`
494
+ return generation_config, model_kwargs
495
+
496
+ @staticmethod
497
+ def parse_eos_tokens(
498
+ tokenizer: PreTrainedTokenizer,
499
+ generation_config: GenerationConfig,
500
+ eos_tokens: Optional[str],
501
+ eos_token_ids: Optional[str],
502
+ ) -> tuple[int, list[int]]:
503
+ """Retrieves the pad token ID and all possible EOS token IDs."""
504
+ if generation_config.pad_token_id is None:
505
+ pad_token_id = generation_config.eos_token_id
506
+ else:
507
+ pad_token_id = generation_config.pad_token_id
508
+
509
+ all_eos_token_ids = []
510
+
511
+ if eos_tokens is not None:
512
+ all_eos_token_ids.extend(tokenizer.convert_tokens_to_ids(eos_tokens.split(",")))
513
+
514
+ if eos_token_ids is not None:
515
+ all_eos_token_ids.extend([int(token_id) for token_id in eos_token_ids.split(",")])
516
+
517
+ if len(all_eos_token_ids) == 0:
518
+ all_eos_token_ids.append(generation_config.eos_token_id)
519
+
520
+ return pad_token_id, all_eos_token_ids
521
+
522
+ # -----------------------------------------------------------------------------------------------------------------
523
+ # Model loading and performance automation methods
524
+ @staticmethod
525
+ def get_quantization_config(model_args: ChatArguments) -> Optional["BitsAndBytesConfig"]:
526
+ if model_args.load_in_4bit:
527
+ quantization_config = BitsAndBytesConfig(
528
+ load_in_4bit=True,
529
+ # For consistency with model weights, we use the same value as `dtype`
530
+ bnb_4bit_compute_dtype=model_args.dtype,
531
+ bnb_4bit_quant_type=model_args.bnb_4bit_quant_type,
532
+ bnb_4bit_use_double_quant=model_args.use_bnb_nested_quant,
533
+ bnb_4bit_quant_storage=model_args.dtype,
534
+ )
535
+ elif model_args.load_in_8bit:
536
+ quantization_config = BitsAndBytesConfig(
537
+ load_in_8bit=True,
538
+ )
539
+ else:
540
+ quantization_config = None
541
+
542
+ return quantization_config
543
+
544
+ def load_model_and_tokenizer(self, args: ChatArguments) -> tuple["AutoModelForCausalLM", AutoTokenizer]:
545
+ tokenizer = AutoTokenizer.from_pretrained(
546
+ args.model_name_or_path_positional,
547
+ revision=args.model_revision,
548
+ trust_remote_code=args.trust_remote_code,
549
+ )
550
+
551
+ dtype = args.dtype if args.dtype in ["auto", None] else getattr(torch, args.dtype)
552
+ quantization_config = self.get_quantization_config(args)
553
+ model_kwargs = {
554
+ "revision": args.model_revision,
555
+ "attn_implementation": args.attn_implementation,
556
+ "dtype": dtype,
557
+ "device_map": "auto",
558
+ "quantization_config": quantization_config,
559
+ }
560
+ model = AutoModelForCausalLM.from_pretrained(
561
+ args.model_name_or_path_positional, trust_remote_code=args.trust_remote_code, **model_kwargs
562
+ )
563
+
564
+ if getattr(model, "hf_device_map", None) is None:
565
+ model = model.to(args.device)
566
+
567
+ return model, tokenizer
568
+
569
+ # -----------------------------------------------------------------------------------------------------------------
570
+ # User commands
571
+ def handle_non_exit_user_commands(
572
+ self,
573
+ user_input: str,
574
+ args: ChatArguments,
575
+ interface: RichInterface,
576
+ examples: dict[str, dict[str, str]],
577
+ generation_config: GenerationConfig,
578
+ model_kwargs: dict,
579
+ chat: list[dict],
580
+ ) -> tuple[list[dict], GenerationConfig, dict]:
581
+ """
582
+ Handles all user commands except for `!exit`. May update the chat history (e.g. reset it) or the
583
+ generation config (e.g. set a new flag).
584
+ """
585
+ valid_command = True
586
+
587
+ if user_input == "!clear":
588
+ chat = self.clear_chat_history(args.system_prompt)
589
+ interface.clear()
590
+
591
+ elif user_input == "!help":
592
+ interface.print_help()
593
+
594
+ elif user_input.startswith("!save") and len(user_input.split()) < 2:
595
+ split_input = user_input.split()
596
+
597
+ if len(split_input) == 2:
598
+ filename = split_input[1]
599
+ else:
600
+ filename = None
601
+ filename = self.save_chat(chat, args, filename)
602
+ interface.print_color(text=f"Chat saved in {filename}!", color="green")
603
+
604
+ elif user_input.startswith("!set"):
605
+ # splits the new args into a list of strings, each string being a `flag=value` pair (same format as
606
+ # `generate_flags`)
607
+ new_generate_flags = user_input[4:].strip()
608
+ new_generate_flags = new_generate_flags.split()
609
+ # sanity check: each member in the list must have an =
610
+ for flag in new_generate_flags:
611
+ if "=" not in flag:
612
+ interface.print_color(
613
+ text=(
614
+ f"Invalid flag format, missing `=` after `{flag}`. Please use the format "
615
+ "`arg_1=value_1 arg_2=value_2 ...`."
616
+ ),
617
+ color="red",
618
+ )
619
+ break
620
+ else:
621
+ # parses the new args into a dictionary of `generate` kwargs, and updates the corresponding variables
622
+ parsed_new_generate_flags = self.parse_generate_flags(new_generate_flags)
623
+ new_model_kwargs = generation_config.update(**parsed_new_generate_flags)
624
+ model_kwargs.update(**new_model_kwargs)
625
+
626
+ elif user_input.startswith("!example") and len(user_input.split()) == 2:
627
+ example_name = user_input.split()[1]
628
+ if example_name in examples:
629
+ interface.clear()
630
+ chat = []
631
+ interface.print_user_message(examples[example_name]["text"])
632
+ chat.append({"role": "user", "content": examples[example_name]["text"]})
633
+ else:
634
+ example_error = (
635
+ f"Example {example_name} not found in list of available examples: {list(examples.keys())}."
636
+ )
637
+ interface.print_color(text=example_error, color="red")
638
+
639
+ elif user_input == "!status":
640
+ interface.print_status(
641
+ model_name=args.model_name_or_path,
642
+ generation_config=generation_config,
643
+ model_kwargs=model_kwargs,
644
+ )
645
+
646
+ else:
647
+ valid_command = False
648
+ interface.print_color(text=f"'{user_input}' is not a valid command. Showing help message.", color="red")
649
+ interface.print_help()
650
+
651
+ return chat, valid_command, generation_config, model_kwargs
652
+
653
+ # -----------------------------------------------------------------------------------------------------------------
654
+ # Main logic
655
+ def run(self):
656
+ asyncio.run(self._inner_run())
657
+
658
+ async def _inner_run(self):
659
+ if self.spawn_backend:
660
+ serve_args = ServeArguments(
661
+ device=self.args.device,
662
+ dtype=self.args.dtype,
663
+ trust_remote_code=self.args.trust_remote_code,
664
+ attn_implementation=self.args.attn_implementation,
665
+ load_in_8bit=self.args.load_in_8bit,
666
+ load_in_4bit=self.args.load_in_4bit,
667
+ bnb_4bit_quant_type=self.args.bnb_4bit_quant_type,
668
+ use_bnb_nested_quant=self.args.use_bnb_nested_quant,
669
+ host=self.args.host,
670
+ port=self.args.port,
671
+ log_level="error",
672
+ )
673
+ serve_command = ServeCommand(serve_args)
674
+
675
+ thread = Thread(target=serve_command.run)
676
+ thread.daemon = True
677
+ thread.start()
678
+
679
+ model = self.args.model_name_or_path + "@" + self.args.model_revision
680
+ host = "http://localhost" if self.args.host == "localhost" else self.args.host
681
+ client = AsyncInferenceClient(f"{host}:{self.args.port}")
682
+
683
+ args = self.args
684
+ if args.examples_path is None:
685
+ examples = DEFAULT_EXAMPLES
686
+ else:
687
+ with open(args.examples_path) as f:
688
+ examples = yaml.safe_load(f)
689
+
690
+ if args.user is None:
691
+ user = self.get_username()
692
+ else:
693
+ user = args.user
694
+
695
+ model_generation_config = GenerationConfig.from_pretrained(args.model_name_or_path)
696
+ generation_config, model_kwargs = self.get_generation_parameterization(args, model_generation_config)
697
+
698
+ interface = RichInterface(model_name=args.model_name_or_path, user_name=user)
699
+ interface.clear()
700
+ chat = self.clear_chat_history(args.system_prompt)
701
+
702
+ # Starts the session with a minimal help message at the top, so that a user doesn't get stuck
703
+ interface.print_help(minimal=True)
704
+ while True:
705
+ try:
706
+ user_input = interface.input()
707
+
708
+ # User commands
709
+ if user_input.startswith("!"):
710
+ # `!exit` is special, it breaks the loop
711
+ if user_input == "!exit":
712
+ break
713
+ else:
714
+ chat, valid_command, generation_config, model_kwargs = self.handle_non_exit_user_commands(
715
+ user_input=user_input,
716
+ args=args,
717
+ interface=interface,
718
+ examples=examples,
719
+ generation_config=generation_config,
720
+ model_kwargs=model_kwargs,
721
+ chat=chat,
722
+ )
723
+ # `!example` sends a user message to the model
724
+ if not valid_command or not user_input.startswith("!example"):
725
+ continue
726
+ else:
727
+ chat.append({"role": "user", "content": user_input})
728
+
729
+ stream = client.chat_completion(
730
+ chat,
731
+ stream=True,
732
+ extra_body={
733
+ "generation_config": generation_config.to_json_string(),
734
+ "model": model,
735
+ },
736
+ )
737
+
738
+ model_output = await interface.stream_output(stream)
739
+
740
+ chat.append({"role": "assistant", "content": model_output})
741
+
742
+ except KeyboardInterrupt:
743
+ break
744
+ finally:
745
+ await client.close()
746
+
747
+
748
+ if __name__ == "__main__":
749
+ args = ChatArguments()
750
+ args.model_name_or_path_or_address = "meta-llama/Llama-3.2-3b-Instruct"
751
+ args.model_name_or_path_or_address = "http://localhost:8000"
752
+ chat = ChatCommand(args)
753
+ chat.run()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/convert.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ from argparse import ArgumentParser, Namespace
16
+
17
+ from ..utils import logging
18
+ from . import BaseTransformersCLICommand
19
+
20
+
21
+ def convert_command_factory(args: Namespace):
22
+ """
23
+ Factory function used to convert a model TF 1.0 checkpoint in a PyTorch checkpoint.
24
+
25
+ Returns: ServeCommand
26
+ """
27
+ return ConvertCommand(
28
+ args.model_type, args.tf_checkpoint, args.pytorch_dump_output, args.config, args.finetuning_task_name
29
+ )
30
+
31
+
32
+ IMPORT_ERROR_MESSAGE = """
33
+ transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires
34
+ TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.
35
+ """
36
+
37
+
38
+ class ConvertCommand(BaseTransformersCLICommand):
39
+ @staticmethod
40
+ def register_subcommand(parser: ArgumentParser):
41
+ """
42
+ Register this command to argparse so it's available for the transformer-cli
43
+
44
+ Args:
45
+ parser: Root parser to register command-specific arguments
46
+ """
47
+ train_parser = parser.add_parser(
48
+ "convert",
49
+ help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.",
50
+ )
51
+ train_parser.add_argument("--model_type", type=str, required=True, help="Model's type.")
52
+ train_parser.add_argument(
53
+ "--tf_checkpoint", type=str, required=True, help="TensorFlow checkpoint path or folder."
54
+ )
55
+ train_parser.add_argument(
56
+ "--pytorch_dump_output", type=str, required=True, help="Path to the PyTorch saved model output."
57
+ )
58
+ train_parser.add_argument("--config", type=str, default="", help="Configuration file path or folder.")
59
+ train_parser.add_argument(
60
+ "--finetuning_task_name",
61
+ type=str,
62
+ default=None,
63
+ help="Optional fine-tuning task name if the TF model was a finetuned model.",
64
+ )
65
+ train_parser.set_defaults(func=convert_command_factory)
66
+
67
+ def __init__(
68
+ self,
69
+ model_type: str,
70
+ tf_checkpoint: str,
71
+ pytorch_dump_output: str,
72
+ config: str,
73
+ finetuning_task_name: str,
74
+ *args,
75
+ ):
76
+ self._logger = logging.get_logger("transformers/converting")
77
+
78
+ self._logger.info(f"Loading model {model_type}")
79
+ self._model_type = model_type
80
+ self._tf_checkpoint = tf_checkpoint
81
+ self._pytorch_dump_output = pytorch_dump_output
82
+ self._config = config
83
+ self._finetuning_task_name = finetuning_task_name
84
+
85
+ def run(self):
86
+ if self._model_type == "albert":
87
+ try:
88
+ from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
89
+ convert_tf_checkpoint_to_pytorch,
90
+ )
91
+ except ImportError:
92
+ raise ImportError(IMPORT_ERROR_MESSAGE)
93
+
94
+ convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
95
+ elif self._model_type == "bert":
96
+ try:
97
+ from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
98
+ convert_tf_checkpoint_to_pytorch,
99
+ )
100
+ except ImportError:
101
+ raise ImportError(IMPORT_ERROR_MESSAGE)
102
+
103
+ convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
104
+ elif self._model_type == "funnel":
105
+ try:
106
+ from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
107
+ convert_tf_checkpoint_to_pytorch,
108
+ )
109
+ except ImportError:
110
+ raise ImportError(IMPORT_ERROR_MESSAGE)
111
+
112
+ convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
113
+ elif self._model_type == "t5":
114
+ try:
115
+ from ..models.t5.convert_t5_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
116
+ except ImportError:
117
+ raise ImportError(IMPORT_ERROR_MESSAGE)
118
+
119
+ convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
120
+ elif self._model_type == "gpt":
121
+ from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
122
+ convert_openai_checkpoint_to_pytorch,
123
+ )
124
+
125
+ convert_openai_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
126
+ elif self._model_type == "gpt2":
127
+ try:
128
+ from ..models.gpt2.convert_gpt2_original_tf_checkpoint_to_pytorch import (
129
+ convert_gpt2_checkpoint_to_pytorch,
130
+ )
131
+ except ImportError:
132
+ raise ImportError(IMPORT_ERROR_MESSAGE)
133
+
134
+ convert_gpt2_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
135
+ elif self._model_type == "xlnet":
136
+ try:
137
+ from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
138
+ convert_xlnet_checkpoint_to_pytorch,
139
+ )
140
+ except ImportError:
141
+ raise ImportError(IMPORT_ERROR_MESSAGE)
142
+
143
+ convert_xlnet_checkpoint_to_pytorch(
144
+ self._tf_checkpoint, self._config, self._pytorch_dump_output, self._finetuning_task_name
145
+ )
146
+ elif self._model_type == "xlm":
147
+ from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
148
+ convert_xlm_checkpoint_to_pytorch,
149
+ )
150
+
151
+ convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint, self._pytorch_dump_output)
152
+ elif self._model_type == "lxmert":
153
+ from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
154
+ convert_lxmert_checkpoint_to_pytorch,
155
+ )
156
+
157
+ convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint, self._pytorch_dump_output)
158
+ elif self._model_type == "rembert":
159
+ from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
160
+ convert_rembert_tf_checkpoint_to_pytorch,
161
+ )
162
+
163
+ convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
164
+ else:
165
+ raise ValueError("--model_type should be selected in the list [bert, gpt, gpt2, t5, xlnet, xlm, lxmert]")
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/commands/download.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ from argparse import ArgumentParser
16
+
17
+ from . import BaseTransformersCLICommand
18
+
19
+
20
+ def download_command_factory(args):
21
+ return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code)
22
+
23
+
24
+ class DownloadCommand(BaseTransformersCLICommand):
25
+ @staticmethod
26
+ def register_subcommand(parser: ArgumentParser):
27
+ download_parser = parser.add_parser("download")
28
+ download_parser.add_argument(
29
+ "--cache-dir", type=str, default=None, help="Path to location to store the models"
30
+ )
31
+ download_parser.add_argument(
32
+ "--force", action="store_true", help="Force the model to be download even if already in cache-dir"
33
+ )
34
+ download_parser.add_argument(
35
+ "--trust-remote-code",
36
+ action="store_true",
37
+ help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine",
38
+ )
39
+ download_parser.add_argument("model", type=str, help="Name of the model to download")
40
+ download_parser.set_defaults(func=download_command_factory)
41
+
42
+ def __init__(self, model: str, cache: str, force: bool, trust_remote_code: bool):
43
+ self._model = model
44
+ self._cache = cache
45
+ self._force = force
46
+ self._trust_remote_code = trust_remote_code
47
+
48
+ def run(self):
49
+ from ..models.auto import AutoModel, AutoTokenizer
50
+
51
+ AutoModel.from_pretrained(
52
+ self._model, cache_dir=self._cache, force_download=self._force, trust_remote_code=self._trust_remote_code
53
+ )
54
+ AutoTokenizer.from_pretrained(
55
+ self._model, cache_dir=self._cache, force_download=self._force, trust_remote_code=self._trust_remote_code
56
+ )