jasonfan commited on
Commit
633c43e
·
verified ·
1 Parent(s): 24260e8

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/lib64/python3.10/site-packages/torch-2.8.0.dist-info/INSTALLER +1 -0
  2. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/METADATA +644 -0
  3. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/RECORD +0 -0
  4. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/REQUESTED +0 -0
  5. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/WHEEL +5 -0
  6. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/entry_points.txt +6 -0
  7. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/licenses/LICENSE +0 -0
  8. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/licenses/NOTICE +456 -0
  9. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/top_level.txt +3 -0
  10. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/cpp_jit.py +172 -0
  11. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/fuzzer.py +462 -0
  12. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/sparse_fuzzer.py +121 -0
  13. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/timeit_template.cpp +43 -0
  14. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/timer.py +541 -0
  15. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__init__.py +0 -0
  16. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h +129 -0
  17. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/compat_bindings.cpp +35 -0
  18. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_callgrind_template.cpp +68 -0
  19. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py +910 -0
  20. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h +0 -0
  21. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/bottleneck/__init__.py +0 -0
  22. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/bottleneck/__main__.py +229 -0
  23. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/__init__.py +77 -0
  24. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/__init__.py +54 -0
  25. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/collate.py +398 -0
  26. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/fetch.py +55 -0
  27. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/pin_memory.py +110 -0
  28. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/signal_handling.py +79 -0
  29. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/worker.py +374 -0
  30. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/backward_compatibility.py +11 -0
  31. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/dataloader.py +1664 -0
  32. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/__init__.py +1 -0
  33. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/_decorator.py +213 -0
  34. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/_hook_iterator.py +279 -0
  35. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/_typing.py +482 -0
  36. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/__init__.py +11 -0
  37. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py +128 -0
  38. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py +457 -0
  39. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py +136 -0
  40. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/structures.py +22 -0
  41. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/datapipe.py +416 -0
  42. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/datapipe.pyi +726 -0
  43. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/gen_pyi.py +336 -0
  44. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/__init__.py +65 -0
  45. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/callable.py +242 -0
  46. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/combinatorics.py +190 -0
  47. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/combining.py +696 -0
  48. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/filelister.py +68 -0
  49. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/fileopener.py +77 -0
  50. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/grouping.py +322 -0
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/METADATA ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: torch
3
+ Version: 2.8.0
4
+ Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
5
+ Home-page: https://pytorch.org/
6
+ Download-URL: https://github.com/pytorch/pytorch/tags
7
+ Author: PyTorch Team
8
+ Author-email: packages@pytorch.org
9
+ License: BSD-3-Clause
10
+ Project-URL: Homepage, https://pytorch.org/
11
+ Project-URL: Documentation, https://pytorch.org/docs/
12
+ Project-URL: Source, https://github.com/pytorch/pytorch
13
+ Project-URL: Forum, https://discuss.pytorch.org/
14
+ Keywords: pytorch,machine learning
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Education
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: License :: OSI Approved :: BSD License
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Topic :: Software Development
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Programming Language :: C++
27
+ Classifier: Programming Language :: Python :: 3
28
+ Classifier: Programming Language :: Python :: 3.9
29
+ Classifier: Programming Language :: Python :: 3.10
30
+ Classifier: Programming Language :: Python :: 3.11
31
+ Classifier: Programming Language :: Python :: 3.12
32
+ Classifier: Programming Language :: Python :: 3.13
33
+ Requires-Python: >=3.9.0
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ License-File: NOTICE
37
+ Requires-Dist: filelock
38
+ Requires-Dist: typing-extensions>=4.10.0
39
+ Requires-Dist: setuptools; python_version >= "3.12"
40
+ Requires-Dist: sympy>=1.13.3
41
+ Requires-Dist: networkx
42
+ Requires-Dist: jinja2
43
+ Requires-Dist: fsspec
44
+ Requires-Dist: nvidia-cuda-nvrtc-cu12==12.8.93; platform_system == "Linux" and platform_machine == "x86_64"
45
+ Requires-Dist: nvidia-cuda-runtime-cu12==12.8.90; platform_system == "Linux" and platform_machine == "x86_64"
46
+ Requires-Dist: nvidia-cuda-cupti-cu12==12.8.90; platform_system == "Linux" and platform_machine == "x86_64"
47
+ Requires-Dist: nvidia-cudnn-cu12==9.10.2.21; platform_system == "Linux" and platform_machine == "x86_64"
48
+ Requires-Dist: nvidia-cublas-cu12==12.8.4.1; platform_system == "Linux" and platform_machine == "x86_64"
49
+ Requires-Dist: nvidia-cufft-cu12==11.3.3.83; platform_system == "Linux" and platform_machine == "x86_64"
50
+ Requires-Dist: nvidia-curand-cu12==10.3.9.90; platform_system == "Linux" and platform_machine == "x86_64"
51
+ Requires-Dist: nvidia-cusolver-cu12==11.7.3.90; platform_system == "Linux" and platform_machine == "x86_64"
52
+ Requires-Dist: nvidia-cusparse-cu12==12.5.8.93; platform_system == "Linux" and platform_machine == "x86_64"
53
+ Requires-Dist: nvidia-cusparselt-cu12==0.7.1; platform_system == "Linux" and platform_machine == "x86_64"
54
+ Requires-Dist: nvidia-nccl-cu12==2.27.3; platform_system == "Linux" and platform_machine == "x86_64"
55
+ Requires-Dist: nvidia-nvtx-cu12==12.8.90; platform_system == "Linux" and platform_machine == "x86_64"
56
+ Requires-Dist: nvidia-nvjitlink-cu12==12.8.93; platform_system == "Linux" and platform_machine == "x86_64"
57
+ Requires-Dist: nvidia-cufile-cu12==1.13.1.3; platform_system == "Linux" and platform_machine == "x86_64"
58
+ Requires-Dist: triton==3.4.0; platform_system == "Linux" and platform_machine == "x86_64"
59
+ Provides-Extra: optree
60
+ Requires-Dist: optree>=0.13.0; extra == "optree"
61
+ Provides-Extra: opt-einsum
62
+ Requires-Dist: opt-einsum>=3.3; extra == "opt-einsum"
63
+ Provides-Extra: pyyaml
64
+ Requires-Dist: pyyaml; extra == "pyyaml"
65
+ Dynamic: author
66
+ Dynamic: author-email
67
+ Dynamic: classifier
68
+ Dynamic: description
69
+ Dynamic: description-content-type
70
+ Dynamic: download-url
71
+ Dynamic: home-page
72
+ Dynamic: keywords
73
+ Dynamic: license-file
74
+ Dynamic: provides-extra
75
+ Dynamic: requires-dist
76
+ Dynamic: requires-python
77
+ Dynamic: summary
78
+
79
+ ![PyTorch Logo](https://github.com/pytorch/pytorch/raw/main/docs/source/_static/img/pytorch-logo-dark.png)
80
+
81
+ --------------------------------------------------------------------------------
82
+
83
+ PyTorch is a Python package that provides two high-level features:
84
+ - Tensor computation (like NumPy) with strong GPU acceleration
85
+ - Deep neural networks built on a tape-based autograd system
86
+
87
+ You can reuse your favorite Python packages such as NumPy, SciPy, and Cython to extend PyTorch when needed.
88
+
89
+ Our trunk health (Continuous Integration signals) can be found at [hud.pytorch.org](https://hud.pytorch.org/ci/pytorch/pytorch/main).
90
+
91
+ <!-- toc -->
92
+
93
+ - [More About PyTorch](#more-about-pytorch)
94
+ - [A GPU-Ready Tensor Library](#a-gpu-ready-tensor-library)
95
+ - [Dynamic Neural Networks: Tape-Based Autograd](#dynamic-neural-networks-tape-based-autograd)
96
+ - [Python First](#python-first)
97
+ - [Imperative Experiences](#imperative-experiences)
98
+ - [Fast and Lean](#fast-and-lean)
99
+ - [Extensions Without Pain](#extensions-without-pain)
100
+ - [Installation](#installation)
101
+ - [Binaries](#binaries)
102
+ - [NVIDIA Jetson Platforms](#nvidia-jetson-platforms)
103
+ - [From Source](#from-source)
104
+ - [Prerequisites](#prerequisites)
105
+ - [NVIDIA CUDA Support](#nvidia-cuda-support)
106
+ - [AMD ROCm Support](#amd-rocm-support)
107
+ - [Intel GPU Support](#intel-gpu-support)
108
+ - [Get the PyTorch Source](#get-the-pytorch-source)
109
+ - [Install Dependencies](#install-dependencies)
110
+ - [Install PyTorch](#install-pytorch)
111
+ - [Adjust Build Options (Optional)](#adjust-build-options-optional)
112
+ - [Docker Image](#docker-image)
113
+ - [Using pre-built images](#using-pre-built-images)
114
+ - [Building the image yourself](#building-the-image-yourself)
115
+ - [Building the Documentation](#building-the-documentation)
116
+ - [Building a PDF](#building-a-pdf)
117
+ - [Previous Versions](#previous-versions)
118
+ - [Getting Started](#getting-started)
119
+ - [Resources](#resources)
120
+ - [Communication](#communication)
121
+ - [Releases and Contributing](#releases-and-contributing)
122
+ - [The Team](#the-team)
123
+ - [License](#license)
124
+
125
+ <!-- tocstop -->
126
+
127
+ ## More About PyTorch
128
+
129
+ [Learn the basics of PyTorch](https://pytorch.org/tutorials/beginner/basics/intro.html)
130
+
131
+ At a granular level, PyTorch is a library that consists of the following components:
132
+
133
+ | Component | Description |
134
+ | ---- | --- |
135
+ | [**torch**](https://pytorch.org/docs/stable/torch.html) | A Tensor library like NumPy, with strong GPU support |
136
+ | [**torch.autograd**](https://pytorch.org/docs/stable/autograd.html) | A tape-based automatic differentiation library that supports all differentiable Tensor operations in torch |
137
+ | [**torch.jit**](https://pytorch.org/docs/stable/jit.html) | A compilation stack (TorchScript) to create serializable and optimizable models from PyTorch code |
138
+ | [**torch.nn**](https://pytorch.org/docs/stable/nn.html) | A neural networks library deeply integrated with autograd designed for maximum flexibility |
139
+ | [**torch.multiprocessing**](https://pytorch.org/docs/stable/multiprocessing.html) | Python multiprocessing, but with magical memory sharing of torch Tensors across processes. Useful for data loading and Hogwild training |
140
+ | [**torch.utils**](https://pytorch.org/docs/stable/data.html) | DataLoader and other utility functions for convenience |
141
+
142
+ Usually, PyTorch is used either as:
143
+
144
+ - A replacement for NumPy to use the power of GPUs.
145
+ - A deep learning research platform that provides maximum flexibility and speed.
146
+
147
+ Elaborating Further:
148
+
149
+ ### A GPU-Ready Tensor Library
150
+
151
+ If you use NumPy, then you have used Tensors (a.k.a. ndarray).
152
+
153
+ ![Tensor illustration](./docs/source/_static/img/tensor_illustration.png)
154
+
155
+ PyTorch provides Tensors that can live either on the CPU or the GPU and accelerates the
156
+ computation by a huge amount.
157
+
158
+ We provide a wide variety of tensor routines to accelerate and fit your scientific computation needs
159
+ such as slicing, indexing, mathematical operations, linear algebra, reductions.
160
+ And they are fast!
161
+
162
+ ### Dynamic Neural Networks: Tape-Based Autograd
163
+
164
+ PyTorch has a unique way of building neural networks: using and replaying a tape recorder.
165
+
166
+ Most frameworks such as TensorFlow, Theano, Caffe, and CNTK have a static view of the world.
167
+ One has to build a neural network and reuse the same structure again and again.
168
+ Changing the way the network behaves means that one has to start from scratch.
169
+
170
+ With PyTorch, we use a technique called reverse-mode auto-differentiation, which allows you to
171
+ change the way your network behaves arbitrarily with zero lag or overhead. Our inspiration comes
172
+ from several research papers on this topic, as well as current and past work such as
173
+ [torch-autograd](https://github.com/twitter/torch-autograd),
174
+ [autograd](https://github.com/HIPS/autograd),
175
+ [Chainer](https://chainer.org), etc.
176
+
177
+ While this technique is not unique to PyTorch, it's one of the fastest implementations of it to date.
178
+ You get the best of speed and flexibility for your crazy research.
179
+
180
+ ![Dynamic graph](https://github.com/pytorch/pytorch/raw/main/docs/source/_static/img/dynamic_graph.gif)
181
+
182
+ ### Python First
183
+
184
+ PyTorch is not a Python binding into a monolithic C++ framework.
185
+ It is built to be deeply integrated into Python.
186
+ You can use it naturally like you would use [NumPy](https://www.numpy.org/) / [SciPy](https://www.scipy.org/) / [scikit-learn](https://scikit-learn.org) etc.
187
+ You can write your new neural network layers in Python itself, using your favorite libraries
188
+ and use packages such as [Cython](https://cython.org/) and [Numba](http://numba.pydata.org/).
189
+ Our goal is to not reinvent the wheel where appropriate.
190
+
191
+ ### Imperative Experiences
192
+
193
+ PyTorch is designed to be intuitive, linear in thought, and easy to use.
194
+ When you execute a line of code, it gets executed. There isn't an asynchronous view of the world.
195
+ When you drop into a debugger or receive error messages and stack traces, understanding them is straightforward.
196
+ The stack trace points to exactly where your code was defined.
197
+ We hope you never spend hours debugging your code because of bad stack traces or asynchronous and opaque execution engines.
198
+
199
+ ### Fast and Lean
200
+
201
+ PyTorch has minimal framework overhead. We integrate acceleration libraries
202
+ such as [Intel MKL](https://software.intel.com/mkl) and NVIDIA ([cuDNN](https://developer.nvidia.com/cudnn), [NCCL](https://developer.nvidia.com/nccl)) to maximize speed.
203
+ At the core, its CPU and GPU Tensor and neural network backends
204
+ are mature and have been tested for years.
205
+
206
+ Hence, PyTorch is quite fast — whether you run small or large neural networks.
207
+
208
+ The memory usage in PyTorch is extremely efficient compared to Torch or some of the alternatives.
209
+ We've written custom memory allocators for the GPU to make sure that
210
+ your deep learning models are maximally memory efficient.
211
+ This enables you to train bigger deep learning models than before.
212
+
213
+ ### Extensions Without Pain
214
+
215
+ Writing new neural network modules, or interfacing with PyTorch's Tensor API was designed to be straightforward
216
+ and with minimal abstractions.
217
+
218
+ You can write new neural network layers in Python using the torch API
219
+ [or your favorite NumPy-based libraries such as SciPy](https://pytorch.org/tutorials/advanced/numpy_extensions_tutorial.html).
220
+
221
+ If you want to write your layers in C/C++, we provide a convenient extension API that is efficient and with minimal boilerplate.
222
+ No wrapper code needs to be written. You can see [a tutorial here](https://pytorch.org/tutorials/advanced/cpp_extension.html) and [an example here](https://github.com/pytorch/extension-cpp).
223
+
224
+
225
+ ## Installation
226
+
227
+ ### Binaries
228
+ Commands to install binaries via Conda or pip wheels are on our website: [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)
229
+
230
+
231
+ #### NVIDIA Jetson Platforms
232
+
233
+ Python wheels for NVIDIA's Jetson Nano, Jetson TX1/TX2, Jetson Xavier NX/AGX, and Jetson AGX Orin are provided [here](https://forums.developer.nvidia.com/t/pytorch-for-jetson-version-1-10-now-available/72048) and the L4T container is published [here](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/l4t-pytorch)
234
+
235
+ They require JetPack 4.2 and above, and [@dusty-nv](https://github.com/dusty-nv) and [@ptrblck](https://github.com/ptrblck) are maintaining them.
236
+
237
+
238
+ ### From Source
239
+
240
+ #### Prerequisites
241
+ If you are installing from source, you will need:
242
+ - Python 3.9 or later
243
+ - A compiler that fully supports C++17, such as clang or gcc (gcc 9.4.0 or newer is required, on Linux)
244
+ - Visual Studio or Visual Studio Build Tool (Windows only)
245
+
246
+ \* PyTorch CI uses Visual C++ BuildTools, which come with Visual Studio Enterprise,
247
+ Professional, or Community Editions. You can also install the build tools from
248
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/. The build tools *do not*
249
+ come with Visual Studio Code by default.
250
+
251
+ An example of environment setup is shown below:
252
+
253
+ * Linux:
254
+
255
+ ```bash
256
+ $ source <CONDA_INSTALL_DIR>/bin/activate
257
+ $ conda create -y -n <CONDA_NAME>
258
+ $ conda activate <CONDA_NAME>
259
+ ```
260
+
261
+ * Windows:
262
+
263
+ ```bash
264
+ $ source <CONDA_INSTALL_DIR>\Scripts\activate.bat
265
+ $ conda create -y -n <CONDA_NAME>
266
+ $ conda activate <CONDA_NAME>
267
+ $ call "C:\Program Files\Microsoft Visual Studio\<VERSION>\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
268
+ ```
269
+
270
+ A conda environment is not required. You can also do a PyTorch build in a
271
+ standard virtual environment, e.g., created with tools like `uv`, provided
272
+ your system has installed all the necessary dependencies unavailable as pip
273
+ packages (e.g., CUDA, MKL.)
274
+
275
+ ##### NVIDIA CUDA Support
276
+ If you want to compile with CUDA support, [select a supported version of CUDA from our support matrix](https://pytorch.org/get-started/locally/), then install the following:
277
+ - [NVIDIA CUDA](https://developer.nvidia.com/cuda-downloads)
278
+ - [NVIDIA cuDNN](https://developer.nvidia.com/cudnn) v8.5 or above
279
+ - [Compiler](https://gist.github.com/ax3l/9489132) compatible with CUDA
280
+
281
+ Note: You could refer to the [cuDNN Support Matrix](https://docs.nvidia.com/deeplearning/cudnn/backend/latest/reference/support-matrix.html) for cuDNN versions with the various supported CUDA, CUDA driver and NVIDIA hardware
282
+
283
+ If you want to disable CUDA support, export the environment variable `USE_CUDA=0`.
284
+ Other potentially useful environment variables may be found in `setup.py`. If
285
+ CUDA is installed in a non-standard location, set PATH so that the nvcc you
286
+ want to use can be found (e.g., `export PATH=/usr/local/cuda-12.8/bin:$PATH`).
287
+
288
+ If you are building for NVIDIA's Jetson platforms (Jetson Nano, TX1, TX2, AGX Xavier), Instructions to install PyTorch for Jetson Nano are [available here](https://devtalk.nvidia.com/default/topic/1049071/jetson-nano/pytorch-for-jetson-nano/)
289
+
290
+ ##### AMD ROCm Support
291
+ If you want to compile with ROCm support, install
292
+ - [AMD ROCm](https://rocm.docs.amd.com/en/latest/deploy/linux/quick_start.html) 4.0 and above installation
293
+ - ROCm is currently supported only for Linux systems.
294
+
295
+ By default the build system expects ROCm to be installed in `/opt/rocm`. If ROCm is installed in a different directory, the `ROCM_PATH` environment variable must be set to the ROCm installation directory. The build system automatically detects the AMD GPU architecture. Optionally, the AMD GPU architecture can be explicitly set with the `PYTORCH_ROCM_ARCH` environment variable [AMD GPU architecture](https://rocm.docs.amd.com/projects/install-on-linux/en/latest/reference/system-requirements.html#supported-gpus)
296
+
297
+ If you want to disable ROCm support, export the environment variable `USE_ROCM=0`.
298
+ Other potentially useful environment variables may be found in `setup.py`.
299
+
300
+ ##### Intel GPU Support
301
+ If you want to compile with Intel GPU support, follow these
302
+ - [PyTorch Prerequisites for Intel GPUs](https://www.intel.com/content/www/us/en/developer/articles/tool/pytorch-prerequisites-for-intel-gpus.html) instructions.
303
+ - Intel GPU is supported for Linux and Windows.
304
+
305
+ If you want to disable Intel GPU support, export the environment variable `USE_XPU=0`.
306
+ Other potentially useful environment variables may be found in `setup.py`.
307
+
308
+ #### Get the PyTorch Source
309
+ ```bash
310
+ git clone https://github.com/pytorch/pytorch
311
+ cd pytorch
312
+ # if you are updating an existing checkout
313
+ git submodule sync
314
+ git submodule update --init --recursive
315
+ ```
316
+
317
+ #### Install Dependencies
318
+
319
+ **Common**
320
+
321
+ ```bash
322
+ conda install cmake ninja
323
+ # Run this command from the PyTorch directory after cloning the source code using the “Get the PyTorch Source“ section below
324
+ pip install -r requirements.txt
325
+ ```
326
+
327
+ **On Linux**
328
+
329
+ ```bash
330
+ pip install mkl-static mkl-include
331
+ # CUDA only: Add LAPACK support for the GPU if needed
332
+ # magma installation: run with active conda environment. specify CUDA version to install
333
+ .ci/docker/common/install_magma_conda.sh 12.4
334
+
335
+ # (optional) If using torch.compile with inductor/triton, install the matching version of triton
336
+ # Run from the pytorch directory after cloning
337
+ # For Intel GPU support, please explicitly `export USE_XPU=1` before running command.
338
+ make triton
339
+ ```
340
+
341
+ **On MacOS**
342
+
343
+ ```bash
344
+ # Add this package on intel x86 processor machines only
345
+ pip install mkl-static mkl-include
346
+ # Add these packages if torch.distributed is needed
347
+ conda install pkg-config libuv
348
+ ```
349
+
350
+ **On Windows**
351
+
352
+ ```bash
353
+ pip install mkl-static mkl-include
354
+ # Add these packages if torch.distributed is needed.
355
+ # Distributed package support on Windows is a prototype feature and is subject to changes.
356
+ conda install -c conda-forge libuv=1.39
357
+ ```
358
+
359
+ #### Install PyTorch
360
+ **On Linux**
361
+
362
+ If you're compiling for AMD ROCm then first run this command:
363
+ ```bash
364
+ # Only run this if you're compiling for ROCm
365
+ python tools/amd_build/build_amd.py
366
+ ```
367
+
368
+ Install PyTorch
369
+ ```bash
370
+ export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
371
+ python setup.py develop
372
+ ```
373
+
374
+ **On macOS**
375
+
376
+ ```bash
377
+ python3 setup.py develop
378
+ ```
379
+
380
+ **On Windows**
381
+
382
+ If you want to build legacy python code, please refer to [Building on legacy code and CUDA](https://github.com/pytorch/pytorch/blob/main/CONTRIBUTING.md#building-on-legacy-code-and-cuda)
383
+
384
+ **CPU-only builds**
385
+
386
+ In this mode PyTorch computations will run on your CPU, not your GPU.
387
+
388
+ ```cmd
389
+ python setup.py develop
390
+ ```
391
+
392
+ Note on OpenMP: The desired OpenMP implementation is Intel OpenMP (iomp). In order to link against iomp, you'll need to manually download the library and set up the building environment by tweaking `CMAKE_INCLUDE_PATH` and `LIB`. The instruction [here](https://github.com/pytorch/pytorch/blob/main/docs/source/notes/windows.rst#building-from-source) is an example for setting up both MKL and Intel OpenMP. Without these configurations for CMake, Microsoft Visual C OpenMP runtime (vcomp) will be used.
393
+
394
+ **CUDA based build**
395
+
396
+ In this mode PyTorch computations will leverage your GPU via CUDA for faster number crunching
397
+
398
+ [NVTX](https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) is needed to build Pytorch with CUDA.
399
+ NVTX is a part of CUDA distributive, where it is called "Nsight Compute". To install it onto an already installed CUDA run CUDA installation once again and check the corresponding checkbox.
400
+ Make sure that CUDA with Nsight Compute is installed after Visual Studio.
401
+
402
+ Currently, VS 2017 / 2019, and Ninja are supported as the generator of CMake. If `ninja.exe` is detected in `PATH`, then Ninja will be used as the default generator, otherwise, it will use VS 2017 / 2019.
403
+ <br/> If Ninja is selected as the generator, the latest MSVC will get selected as the underlying toolchain.
404
+
405
+ Additional libraries such as
406
+ [Magma](https://developer.nvidia.com/magma), [oneDNN, a.k.a. MKLDNN or DNNL](https://github.com/oneapi-src/oneDNN), and [Sccache](https://github.com/mozilla/sccache) are often needed. Please refer to the [installation-helper](https://github.com/pytorch/pytorch/tree/main/.ci/pytorch/win-test-helpers/installation-helpers) to install them.
407
+
408
+ You can refer to the [build_pytorch.bat](https://github.com/pytorch/pytorch/blob/main/.ci/pytorch/win-test-helpers/build_pytorch.bat) script for some other environment variables configurations
409
+
410
+
411
+ ```cmd
412
+ cmd
413
+
414
+ :: Set the environment variables after you have downloaded and unzipped the mkl package,
415
+ :: else CMake would throw an error as `Could NOT find OpenMP`.
416
+ set CMAKE_INCLUDE_PATH={Your directory}\mkl\include
417
+ set LIB={Your directory}\mkl\lib;%LIB%
418
+
419
+ :: Read the content in the previous section carefully before you proceed.
420
+ :: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block.
421
+ :: "Visual Studio 2019 Developer Command Prompt" will be run automatically.
422
+ :: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator.
423
+ set CMAKE_GENERATOR_TOOLSET_VERSION=14.27
424
+ set DISTUTILS_USE_SDK=1
425
+ for /f "usebackq tokens=*" %i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version [15^,17^) -products * -latest -property installationPath`) do call "%i\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION%
426
+
427
+ :: [Optional] If you want to override the CUDA host compiler
428
+ set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe
429
+
430
+ python setup.py develop
431
+
432
+ ```
433
+
434
+ **Intel GPU builds**
435
+
436
+ In this mode PyTorch with Intel GPU support will be built.
437
+
438
+ Please make sure [the common prerequisites](#prerequisites) as well as [the prerequisites for Intel GPU](#intel-gpu-support) are properly installed and the environment variables are configured prior to starting the build. For build tool support, `Visual Studio 2022` is required.
439
+
440
+ Then PyTorch can be built with the command:
441
+
442
+ ```cmd
443
+ :: CMD Commands:
444
+ :: Set the CMAKE_PREFIX_PATH to help find corresponding packages
445
+ :: %CONDA_PREFIX% only works after `conda activate custom_env`
446
+
447
+ if defined CMAKE_PREFIX_PATH (
448
+ set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library;%CMAKE_PREFIX_PATH%"
449
+ ) else (
450
+ set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library"
451
+ )
452
+
453
+ python setup.py develop
454
+ ```
455
+
456
+ ##### Adjust Build Options (Optional)
457
+
458
+ You can adjust the configuration of cmake variables optionally (without building first), by doing
459
+ the following. For example, adjusting the pre-detected directories for CuDNN or BLAS can be done
460
+ with such a step.
461
+
462
+ On Linux
463
+ ```bash
464
+ export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
465
+ CMAKE_ONLY=1 python setup.py build
466
+ ccmake build # or cmake-gui build
467
+ ```
468
+
469
+ On macOS
470
+ ```bash
471
+ export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
472
+ MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ CMAKE_ONLY=1 python setup.py build
473
+ ccmake build # or cmake-gui build
474
+ ```
475
+
476
+ ### Docker Image
477
+
478
+ #### Using pre-built images
479
+
480
+ You can also pull a pre-built docker image from Docker Hub and run with docker v19.03+
481
+
482
+ ```bash
483
+ docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest
484
+ ```
485
+
486
+ Please note that PyTorch uses shared memory to share data between processes, so if torch multiprocessing is used (e.g.
487
+ for multithreaded data loaders) the default shared memory segment size that container runs with is not enough, and you
488
+ should increase shared memory size either with `--ipc=host` or `--shm-size` command line options to `nvidia-docker run`.
489
+
490
+ #### Building the image yourself
491
+
492
+ **NOTE:** Must be built with a docker version > 18.06
493
+
494
+ The `Dockerfile` is supplied to build images with CUDA 11.1 support and cuDNN v8.
495
+ You can pass `PYTHON_VERSION=x.y` make variable to specify which Python version is to be used by Miniconda, or leave it
496
+ unset to use the default.
497
+
498
+ ```bash
499
+ make -f docker.Makefile
500
+ # images are tagged as docker.io/${your_docker_username}/pytorch
501
+ ```
502
+
503
+ You can also pass the `CMAKE_VARS="..."` environment variable to specify additional CMake variables to be passed to CMake during the build.
504
+ See [setup.py](./setup.py) for the list of available variables.
505
+
506
+ ```bash
507
+ make -f docker.Makefile
508
+ ```
509
+
510
+ ### Building the Documentation
511
+
512
+ To build documentation in various formats, you will need [Sphinx](http://www.sphinx-doc.org)
513
+ and the pytorch_sphinx_theme2.
514
+
515
+ Before you build the documentation locally, ensure `torch` is
516
+ installed in your environment. For small fixes, you can install the
517
+ nightly version as described in [Getting Started](https://pytorch.org/get-started/locally/).
518
+
519
+ For more complex fixes, such as adding a new module and docstrings for
520
+ the new module, you might need to install torch [from source](#from-source).
521
+ See [Docstring Guidelines](https://github.com/pytorch/pytorch/wiki/Docstring-Guidelines)
522
+ for docstring conventions.
523
+
524
+ ```bash
525
+ cd docs/
526
+ pip install -r requirements.txt
527
+ make html
528
+ make serve
529
+ ```
530
+
531
+ Run `make` to get a list of all available output formats.
532
+
533
+ If you get a katex error run `npm install katex`. If it persists, try
534
+ `npm install -g katex`
535
+
536
+ > [!NOTE]
537
+ > If you installed `nodejs` with a different package manager (e.g.,
538
+ > `conda`) then `npm` will probably install a version of `katex` that is not
539
+ > compatible with your version of `nodejs` and doc builds will fail.
540
+ > A combination of versions that is known to work is `node@6.13.1` and
541
+ > `katex@0.13.18`. To install the latter with `npm` you can run
542
+ > ```npm install -g katex@0.13.18```
543
+
544
+ > [!NOTE]
545
+ > If you see a numpy incompatibility error, run:
546
+ > ```
547
+ > pip install 'numpy<2'
548
+ > ```
549
+
550
+ When you make changes to the dependencies run by CI, edit the
551
+ `.ci/docker/requirements-docs.txt` file.
552
+
553
+ #### Building a PDF
554
+
555
+ To compile a PDF of all PyTorch documentation, ensure you have
556
+ `texlive` and LaTeX installed. On macOS, you can install them using:
557
+
558
+ ```
559
+ brew install --cask mactex
560
+ ```
561
+
562
+ To create the PDF:
563
+
564
+ 1. Run:
565
+
566
+ ```
567
+ make latexpdf
568
+ ```
569
+
570
+ This will generate the necessary files in the `build/latex` directory.
571
+
572
+ 2. Navigate to this directory and execute:
573
+
574
+ ```
575
+ make LATEXOPTS="-interaction=nonstopmode"
576
+ ```
577
+
578
+ This will produce a `pytorch.pdf` with the desired content. Run this
579
+ command one more time so that it generates the correct table
580
+ of contents and index.
581
+
582
+ > [!NOTE]
583
+ > To view the Table of Contents, switch to the **Table of Contents**
584
+ > view in your PDF viewer.
585
+
586
+
587
+ ### Previous Versions
588
+
589
+ Installation instructions and binaries for previous PyTorch versions may be found
590
+ on [our website](https://pytorch.org/get-started/previous-versions).
591
+
592
+
593
+ ## Getting Started
594
+
595
+ Three-pointers to get you started:
596
+ - [Tutorials: get you started with understanding and using PyTorch](https://pytorch.org/tutorials/)
597
+ - [Examples: easy to understand PyTorch code across all domains](https://github.com/pytorch/examples)
598
+ - [The API Reference](https://pytorch.org/docs/)
599
+ - [Glossary](https://github.com/pytorch/pytorch/blob/main/GLOSSARY.md)
600
+
601
+ ## Resources
602
+
603
+ * [PyTorch.org](https://pytorch.org/)
604
+ * [PyTorch Tutorials](https://pytorch.org/tutorials/)
605
+ * [PyTorch Examples](https://github.com/pytorch/examples)
606
+ * [PyTorch Models](https://pytorch.org/hub/)
607
+ * [Intro to Deep Learning with PyTorch from Udacity](https://www.udacity.com/course/deep-learning-pytorch--ud188)
608
+ * [Intro to Machine Learning with PyTorch from Udacity](https://www.udacity.com/course/intro-to-machine-learning-nanodegree--nd229)
609
+ * [Deep Neural Networks with PyTorch from Coursera](https://www.coursera.org/learn/deep-neural-networks-with-pytorch)
610
+ * [PyTorch Twitter](https://twitter.com/PyTorch)
611
+ * [PyTorch Blog](https://pytorch.org/blog/)
612
+ * [PyTorch YouTube](https://www.youtube.com/channel/UCWXI5YeOsh03QvJ59PMaXFw)
613
+
614
+ ## Communication
615
+ * Forums: Discuss implementations, research, etc. https://discuss.pytorch.org
616
+ * GitHub Issues: Bug reports, feature requests, install issues, RFCs, thoughts, etc.
617
+ * Slack: The [PyTorch Slack](https://pytorch.slack.com/) hosts a primary audience of moderate to experienced PyTorch users and developers for general chat, online discussions, collaboration, etc. If you are a beginner looking for help, the primary medium is [PyTorch Forums](https://discuss.pytorch.org). If you need a slack invite, please fill this form: https://goo.gl/forms/PP1AGvNHpSaJP8to1
618
+ * Newsletter: No-noise, a one-way email newsletter with important announcements about PyTorch. You can sign-up here: https://eepurl.com/cbG0rv
619
+ * Facebook Page: Important announcements about PyTorch. https://www.facebook.com/pytorch
620
+ * For brand guidelines, please visit our website at [pytorch.org](https://pytorch.org/)
621
+
622
+ ## Releases and Contributing
623
+
624
+ Typically, PyTorch has three minor releases a year. Please let us know if you encounter a bug by [filing an issue](https://github.com/pytorch/pytorch/issues).
625
+
626
+ We appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion.
627
+
628
+ If you plan to contribute new features, utility functions, or extensions to the core, please first open an issue and discuss the feature with us.
629
+ Sending a PR without discussion might end up resulting in a rejected PR because we might be taking the core in a different direction than you might be aware of.
630
+
631
+ To learn more about making a contribution to Pytorch, please see our [Contribution page](CONTRIBUTING.md). For more information about PyTorch releases, see [Release page](RELEASE.md).
632
+
633
+ ## The Team
634
+
635
+ PyTorch is a community-driven project with several skillful engineers and researchers contributing to it.
636
+
637
+ PyTorch is currently maintained by [Soumith Chintala](http://soumith.ch), [Gregory Chanan](https://github.com/gchanan), [Dmytro Dzhulgakov](https://github.com/dzhulgakov), [Edward Yang](https://github.com/ezyang), and [Nikita Shulga](https://github.com/malfet) with major contributions coming from hundreds of talented individuals in various forms and means.
638
+ A non-exhaustive but growing list needs to mention: [Trevor Killeen](https://github.com/killeent), [Sasank Chilamkurthy](https://github.com/chsasank), [Sergey Zagoruyko](https://github.com/szagoruyko), [Adam Lerer](https://github.com/adamlerer), [Francisco Massa](https://github.com/fmassa), [Alykhan Tejani](https://github.com/alykhantejani), [Luca Antiga](https://github.com/lantiga), [Alban Desmaison](https://github.com/albanD), [Andreas Koepf](https://github.com/andreaskoepf), [James Bradbury](https://github.com/jekbradbury), [Zeming Lin](https://github.com/ebetica), [Yuandong Tian](https://github.com/yuandong-tian), [Guillaume Lample](https://github.com/glample), [Marat Dukhan](https://github.com/Maratyszcza), [Natalia Gimelshein](https://github.com/ngimel), [Christian Sarofeen](https://github.com/csarofeen), [Martin Raison](https://github.com/martinraison), [Edward Yang](https://github.com/ezyang), [Zachary Devito](https://github.com/zdevito). <!-- codespell:ignore -->
639
+
640
+ Note: This project is unrelated to [hughperkins/pytorch](https://github.com/hughperkins/pytorch) with the same name. Hugh is a valuable contributor to the Torch community and has helped with many things Torch and PyTorch.
641
+
642
+ ## License
643
+
644
+ PyTorch has a BSD-style license, as found in the [LICENSE](LICENSE) file.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/REQUESTED ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (79.0.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_28_x86_64
5
+
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [console_scripts]
2
+ torchfrtrace = tools.flight_recorder.fr_trace:main
3
+ torchrun = torch.distributed.run:main
4
+
5
+ [torchrun.logs_specs]
6
+ default = torch.distributed.elastic.multiprocessing:DefaultLogsSpecs
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/licenses/LICENSE ADDED
The diff for this file is too large to render. See raw diff
 
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/licenses/NOTICE ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ =======================================================================
2
+ Software under third_party
3
+ =======================================================================
4
+ Software libraries under third_party are provided as github submodule
5
+ links, and their content is not part of the Caffe2 codebase. Their
6
+ licences can be found under the respective software repositories.
7
+
8
+ =======================================================================
9
+ Earlier BSD License
10
+ =======================================================================
11
+ Early development of Caffe2 in 2015 and early 2016 is licensed under the
12
+ BSD license. The license is attached below:
13
+
14
+ All contributions by Facebook:
15
+ Copyright (c) 2016 Facebook Inc.
16
+
17
+ All contributions by Google:
18
+ Copyright (c) 2015 Google Inc.
19
+ All rights reserved.
20
+
21
+ All contributions by Yangqing Jia:
22
+ Copyright (c) 2015 Yangqing Jia
23
+ All rights reserved.
24
+
25
+ All contributions by Kakao Brain:
26
+ Copyright 2019-2020 Kakao Brain
27
+
28
+ All other contributions:
29
+ Copyright(c) 2015, 2016 the respective contributors
30
+ All rights reserved.
31
+
32
+ Redistribution and use in source and binary forms, with or without
33
+ modification, are permitted provided that the following conditions are met:
34
+
35
+ 1. Redistributions of source code must retain the above copyright notice, this
36
+ list of conditions and the following disclaimer.
37
+ 2. Redistributions in binary form must reproduce the above copyright notice,
38
+ this list of conditions and the following disclaimer in the documentation
39
+ and/or other materials provided with the distribution.
40
+
41
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
42
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
43
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
44
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
45
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
46
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
49
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
50
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51
+
52
+
53
+ =======================================================================
54
+ Caffe's BSD License
55
+ =======================================================================
56
+ Some parts of the caffe2 code is derived from the original Caffe code, which is
57
+ created by Yangqing Jia and is now a BSD-licensed open-source project. The Caffe
58
+ license is as follows:
59
+
60
+ COPYRIGHT
61
+
62
+ All contributions by the University of California:
63
+ Copyright (c) 2014, The Regents of the University of California (Regents)
64
+ All rights reserved.
65
+
66
+ All other contributions:
67
+ Copyright (c) 2014, the respective contributors
68
+ All rights reserved.
69
+
70
+ Caffe uses a shared copyright model: each contributor holds copyright over
71
+ their contributions to Caffe. The project versioning records all such
72
+ contribution and copyright details. If a contributor wants to further mark
73
+ their specific copyright on a particular contribution, they should indicate
74
+ their copyright solely in the commit message of the change when it is
75
+ committed.
76
+
77
+ LICENSE
78
+
79
+ Redistribution and use in source and binary forms, with or without
80
+ modification, are permitted provided that the following conditions are met:
81
+
82
+ 1. Redistributions of source code must retain the above copyright notice, this
83
+ list of conditions and the following disclaimer.
84
+ 2. Redistributions in binary form must reproduce the above copyright notice,
85
+ this list of conditions and the following disclaimer in the documentation
86
+ and/or other materials provided with the distribution.
87
+
88
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
89
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
90
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
91
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
92
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
93
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
94
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
95
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
96
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
97
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
98
+
99
+ CONTRIBUTION AGREEMENT
100
+
101
+ By contributing to the BVLC/caffe repository through pull-request, comment,
102
+ or otherwise, the contributor releases their content to the
103
+ license and copyright terms herein.
104
+
105
+ =======================================================================
106
+ Caffe2's Apache License
107
+ =======================================================================
108
+
109
+ This repo contains Caffe2 code, which was previously licensed under
110
+ Apache License Version 2.0:
111
+
112
+ Apache License
113
+ Version 2.0, January 2004
114
+ http://www.apache.org/licenses/
115
+
116
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
117
+
118
+ 1. Definitions.
119
+
120
+ "License" shall mean the terms and conditions for use, reproduction,
121
+ and distribution as defined by Sections 1 through 9 of this document.
122
+
123
+ "Licensor" shall mean the copyright owner or entity authorized by
124
+ the copyright owner that is granting the License.
125
+
126
+ "Legal Entity" shall mean the union of the acting entity and all
127
+ other entities that control, are controlled by, or are under common
128
+ control with that entity. For the purposes of this definition,
129
+ "control" means (i) the power, direct or indirect, to cause the
130
+ direction or management of such entity, whether by contract or
131
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
132
+ outstanding shares, or (iii) beneficial ownership of such entity.
133
+
134
+ "You" (or "Your") shall mean an individual or Legal Entity
135
+ exercising permissions granted by this License.
136
+
137
+ "Source" form shall mean the preferred form for making modifications,
138
+ including but not limited to software source code, documentation
139
+ source, and configuration files.
140
+
141
+ "Object" form shall mean any form resulting from mechanical
142
+ transformation or translation of a Source form, including but
143
+ not limited to compiled object code, generated documentation,
144
+ and conversions to other media types.
145
+
146
+ "Work" shall mean the work of authorship, whether in Source or
147
+ Object form, made available under the License, as indicated by a
148
+ copyright notice that is included in or attached to the work
149
+ (an example is provided in the Appendix below).
150
+
151
+ "Derivative Works" shall mean any work, whether in Source or Object
152
+ form, that is based on (or derived from) the Work and for which the
153
+ editorial revisions, annotations, elaborations, or other modifications
154
+ represent, as a whole, an original work of authorship. For the purposes
155
+ of this License, Derivative Works shall not include works that remain
156
+ separable from, or merely link (or bind by name) to the interfaces of,
157
+ the Work and Derivative Works thereof.
158
+
159
+ "Contribution" shall mean any work of authorship, including
160
+ the original version of the Work and any modifications or additions
161
+ to that Work or Derivative Works thereof, that is intentionally
162
+ submitted to Licensor for inclusion in the Work by the copyright owner
163
+ or by an individual or Legal Entity authorized to submit on behalf of
164
+ the copyright owner. For the purposes of this definition, "submitted"
165
+ means any form of electronic, verbal, or written communication sent
166
+ to the Licensor or its representatives, including but not limited to
167
+ communication on electronic mailing lists, source code control systems,
168
+ and issue tracking systems that are managed by, or on behalf of, the
169
+ Licensor for the purpose of discussing and improving the Work, but
170
+ excluding communication that is conspicuously marked or otherwise
171
+ designated in writing by the copyright owner as "Not a Contribution."
172
+
173
+ "Contributor" shall mean Licensor and any individual or Legal Entity
174
+ on behalf of whom a Contribution has been received by Licensor and
175
+ subsequently incorporated within the Work.
176
+
177
+ 2. Grant of Copyright License. Subject to the terms and conditions of
178
+ this License, each Contributor hereby grants to You a perpetual,
179
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
180
+ copyright license to reproduce, prepare Derivative Works of,
181
+ publicly display, publicly perform, sublicense, and distribute the
182
+ Work and such Derivative Works in Source or Object form.
183
+
184
+ 3. Grant of Patent License. Subject to the terms and conditions of
185
+ this License, each Contributor hereby grants to You a perpetual,
186
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
187
+ (except as stated in this section) patent license to make, have made,
188
+ use, offer to sell, sell, import, and otherwise transfer the Work,
189
+ where such license applies only to those patent claims licensable
190
+ by such Contributor that are necessarily infringed by their
191
+ Contribution(s) alone or by combination of their Contribution(s)
192
+ with the Work to which such Contribution(s) was submitted. If You
193
+ institute patent litigation against any entity (including a
194
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
195
+ or a Contribution incorporated within the Work constitutes direct
196
+ or contributory patent infringement, then any patent licenses
197
+ granted to You under this License for that Work shall terminate
198
+ as of the date such litigation is filed.
199
+
200
+ 4. Redistribution. You may reproduce and distribute copies of the
201
+ Work or Derivative Works thereof in any medium, with or without
202
+ modifications, and in Source or Object form, provided that You
203
+ meet the following conditions:
204
+
205
+ (a) You must give any other recipients of the Work or
206
+ Derivative Works a copy of this License; and
207
+
208
+ (b) You must cause any modified files to carry prominent notices
209
+ stating that You changed the files; and
210
+
211
+ (c) You must retain, in the Source form of any Derivative Works
212
+ that You distribute, all copyright, patent, trademark, and
213
+ attribution notices from the Source form of the Work,
214
+ excluding those notices that do not pertain to any part of
215
+ the Derivative Works; and
216
+
217
+ (d) If the Work includes a "NOTICE" text file as part of its
218
+ distribution, then any Derivative Works that You distribute must
219
+ include a readable copy of the attribution notices contained
220
+ within such NOTICE file, excluding those notices that do not
221
+ pertain to any part of the Derivative Works, in at least one
222
+ of the following places: within a NOTICE text file distributed
223
+ as part of the Derivative Works; within the Source form or
224
+ documentation, if provided along with the Derivative Works; or,
225
+ within a display generated by the Derivative Works, if and
226
+ wherever such third-party notices normally appear. The contents
227
+ of the NOTICE file are for informational purposes only and
228
+ do not modify the License. You may add Your own attribution
229
+ notices within Derivative Works that You distribute, alongside
230
+ or as an addendum to the NOTICE text from the Work, provided
231
+ that such additional attribution notices cannot be construed
232
+ as modifying the License.
233
+
234
+ You may add Your own copyright statement to Your modifications and
235
+ may provide additional or different license terms and conditions
236
+ for use, reproduction, or distribution of Your modifications, or
237
+ for any such Derivative Works as a whole, provided Your use,
238
+ reproduction, and distribution of the Work otherwise complies with
239
+ the conditions stated in this License.
240
+
241
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
242
+ any Contribution intentionally submitted for inclusion in the Work
243
+ by You to the Licensor shall be under the terms and conditions of
244
+ this License, without any additional terms or conditions.
245
+ Notwithstanding the above, nothing herein shall supersede or modify
246
+ the terms of any separate license agreement you may have executed
247
+ with Licensor regarding such Contributions.
248
+
249
+ 6. Trademarks. This License does not grant permission to use the trade
250
+ names, trademarks, service marks, or product names of the Licensor,
251
+ except as required for reasonable and customary use in describing the
252
+ origin of the Work and reproducing the content of the NOTICE file.
253
+
254
+ 7. Disclaimer of Warranty. Unless required by applicable law or
255
+ agreed to in writing, Licensor provides the Work (and each
256
+ Contributor provides its Contributions) on an "AS IS" BASIS,
257
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
258
+ implied, including, without limitation, any warranties or conditions
259
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
260
+ PARTICULAR PURPOSE. You are solely responsible for determining the
261
+ appropriateness of using or redistributing the Work and assume any
262
+ risks associated with Your exercise of permissions under this License.
263
+
264
+ 8. Limitation of Liability. In no event and under no legal theory,
265
+ whether in tort (including negligence), contract, or otherwise,
266
+ unless required by applicable law (such as deliberate and grossly
267
+ negligent acts) or agreed to in writing, shall any Contributor be
268
+ liable to You for damages, including any direct, indirect, special,
269
+ incidental, or consequential damages of any character arising as a
270
+ result of this License or out of the use or inability to use the
271
+ Work (including but not limited to damages for loss of goodwill,
272
+ work stoppage, computer failure or malfunction, or any and all
273
+ other commercial damages or losses), even if such Contributor
274
+ has been advised of the possibility of such damages.
275
+
276
+ 9. Accepting Warranty or Additional Liability. While redistributing
277
+ the Work or Derivative Works thereof, You may choose to offer,
278
+ and charge a fee for, acceptance of support, warranty, indemnity,
279
+ or other liability obligations and/or rights consistent with this
280
+ License. However, in accepting such obligations, You may act only
281
+ on Your own behalf and on Your sole responsibility, not on behalf
282
+ of any other Contributor, and only if You agree to indemnify,
283
+ defend, and hold each Contributor harmless for any liability
284
+ incurred by, or claims asserted against, such Contributor by reason
285
+ of your accepting any such warranty or additional liability.
286
+
287
+ =======================================================================
288
+ Cephes's 3-Clause BSD License
289
+ =======================================================================
290
+
291
+ Code derived from implementations in the Cephes Math Library should mention
292
+ its derivation and reference the following license:
293
+
294
+ 3-Clause BSD License for the Cephes Math Library
295
+ Copyright (c) 2018, Steven Moshier
296
+ All rights reserved.
297
+
298
+ Redistribution and use in source and binary forms, with or without
299
+ modification, are permitted provided that the following conditions are met:
300
+
301
+ * Redistributions of source code must retain the above copyright
302
+ notice, this list of conditions and the following disclaimer.
303
+
304
+ * Redistributions in binary form must reproduce the above copyright
305
+ notice, this list of conditions and the following disclaimer in the
306
+ documentation and/or other materials provided with the distribution.
307
+
308
+ * Neither the name of the nor the
309
+ names of its contributors may be used to endorse or promote products
310
+ derived from this software without specific prior written permission.
311
+
312
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
313
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
314
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
315
+ DISCLAIMED. IN NO EVENT SHALL Steven Moshier BE LIABLE FOR ANY
316
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
317
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
318
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
319
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
320
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
321
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
322
+
323
+
324
+ =======================================================================
325
+ SciPy's 3-Clause BSD License
326
+ =======================================================================
327
+
328
+ Code derived from implementations in SciPy should mention its derivation
329
+ and reference the following license:
330
+
331
+ Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.
332
+ All rights reserved.
333
+
334
+ Redistribution and use in source and binary forms, with or without
335
+ modification, are permitted provided that the following conditions
336
+ are met:
337
+
338
+ 1. Redistributions of source code must retain the above copyright
339
+ notice, this list of conditions and the following disclaimer.
340
+
341
+ 2. Redistributions in binary form must reproduce the above
342
+ copyright notice, this list of conditions and the following
343
+ disclaimer in the documentation and/or other materials provided
344
+ with the distribution.
345
+
346
+ 3. Neither the name of the copyright holder nor the names of its
347
+ contributors may be used to endorse or promote products derived
348
+ from this software without specific prior written permission.
349
+
350
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
351
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
352
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
353
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
354
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
355
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
356
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
357
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
358
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
359
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
360
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
361
+
362
+ =======================================================================
363
+ Boost's 1.0 Software License
364
+ =======================================================================
365
+
366
+ Code derived from implementations in Boost 1.0 should mention its
367
+ derivation and reference the following license:
368
+
369
+ Boost Software License - Version 1.0 - August 17th, 2003
370
+
371
+ Permission is hereby granted, free of charge, to any person or organization
372
+ obtaining a copy of the software and accompanying documentation covered by
373
+ this license (the "Software") to use, reproduce, display, distribute,
374
+ execute, and transmit the Software, and to prepare derivative works of the
375
+ Software, and to permit third-parties to whom the Software is furnished to
376
+ do so, all subject to the following:
377
+
378
+ The copyright notices in the Software and this entire statement, including
379
+ the above license grant, this restriction and the following disclaimer,
380
+ must be included in all copies of the Software, in whole or in part, and
381
+ all derivative works of the Software, unless such copies or derivative
382
+ works are solely in the form of machine-executable object code generated by
383
+ a source language processor.
384
+
385
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
386
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
387
+ FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
388
+ SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
389
+ FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
390
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
391
+ DEALINGS IN THE SOFTWARE.
392
+
393
+ END OF TERMS AND CONDITIONS
394
+
395
+ APPENDIX: How to apply the Apache License to your work.
396
+
397
+ To apply the Apache License to your work, attach the following
398
+ boilerplate notice, with the fields enclosed by brackets "[]"
399
+ replaced with your own identifying information. (Don't include
400
+ the brackets!) The text should be enclosed in the appropriate
401
+ comment syntax for the file format. We also recommend that a
402
+ file or class name and description of purpose be included on the
403
+ same "printed page" as the copyright notice for easier
404
+ identification within third-party archives.
405
+
406
+ Copyright [yyyy] [name of copyright owner]
407
+
408
+ Licensed under the Apache License, Version 2.0 (the "License");
409
+ you may not use this file except in compliance with the License.
410
+ You may obtain a copy of the License at
411
+
412
+ http://www.apache.org/licenses/LICENSE-2.0
413
+
414
+ Unless required by applicable law or agreed to in writing, software
415
+ distributed under the License is distributed on an "AS IS" BASIS,
416
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
417
+ See the License for the specific language governing permissions and
418
+ limitations under the License.
419
+
420
+ =======================================================================
421
+ PILLOW-SIMD Software License
422
+ =======================================================================
423
+
424
+ Code derived from implementations in PILLOW-SIMD should mention its derivation
425
+ and reference the following license:
426
+
427
+ The Python Imaging Library (PIL) is
428
+
429
+ Copyright © 1997-2011 by Secret Labs AB
430
+ Copyright © 1995-2011 by Fredrik Lundh
431
+
432
+ Pillow is the friendly PIL fork. It is
433
+
434
+ Copyright © 2010-2022 by Alex Clark and contributors
435
+
436
+ Like PIL, Pillow is licensed under the open source HPND License:
437
+
438
+ By obtaining, using, and/or copying this software and/or its associated
439
+ documentation, you agree that you have read, understood, and will comply
440
+ with the following terms and conditions:
441
+
442
+ Permission to use, copy, modify, and distribute this software and its
443
+ associated documentation for any purpose and without fee is hereby granted,
444
+ provided that the above copyright notice appears in all copies, and that
445
+ both that copyright notice and this permission notice appear in supporting
446
+ documentation, and that the name of Secret Labs AB or the author not be
447
+ used in advertising or publicity pertaining to distribution of the software
448
+ without specific, written prior permission.
449
+
450
+ SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
451
+ SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
452
+ IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
453
+ INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
454
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
455
+ OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
456
+ PERFORMANCE OF THIS SOFTWARE.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch-2.8.0.dist-info/top_level.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ functorch
2
+ torch
3
+ torchgen
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/cpp_jit.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JIT C++ strings into executables."""
2
+ import atexit
3
+ import os
4
+ import re
5
+ import shutil
6
+ import textwrap
7
+ import threading
8
+ from typing import Any, Optional
9
+
10
+ import torch
11
+ from torch.utils.benchmark.utils._stubs import CallgrindModuleType, TimeitModuleType
12
+ from torch.utils.benchmark.utils.common import _make_temp_dir
13
+ from torch.utils import cpp_extension
14
+
15
+
16
+ LOCK = threading.Lock()
17
+ SOURCE_ROOT = os.path.split(os.path.abspath(__file__))[0]
18
+
19
+ # We calculate uuid once at import time so that separate processes will have
20
+ # separate build roots, but threads will share the same build root.
21
+ # `cpp_extension` uses build root as part of the cache key, so per-invocation
22
+ # uuid's (e.g. different build root per _compile_template call) would lead to
23
+ # a 0% cache hit rate and spurious recompilation. Consider the following:
24
+ # ```
25
+ # setup = "auto x = torch::ones({1024, 1024});"
26
+ # stmt = "torch::mm(x, x);"
27
+ # for num_threads in [1, 2, 4, 8]:
28
+ # print(Timer(stmt, setup, num_threads=num_threads, language="c++").blocked_autorange())
29
+ # ````
30
+ # `setup` and `stmt` do not change, so we can reuse the executable from the
31
+ # first pass through the loop.
32
+ _BUILD_ROOT: Optional[str] = None
33
+
34
+ def _get_build_root() -> str:
35
+ global _BUILD_ROOT
36
+ if _BUILD_ROOT is None:
37
+ _BUILD_ROOT = _make_temp_dir(prefix="benchmark_utils_jit_build")
38
+ atexit.register(shutil.rmtree, _BUILD_ROOT)
39
+ return _BUILD_ROOT
40
+
41
+
42
+ # BACK_TESTING_NOTE:
43
+ # There are two workflows where this code could be used. One is the obvious
44
+ # case where someone simply builds or installs PyTorch and uses Timer.
45
+ # The other is that the entire `torch/utils/benchmark` folder from a CURRENT
46
+ # PyTorch checkout is copy-pasted into a much OLDER version of the PyTorch
47
+ # source code. This is what we refer to here as "back testing". The rationale
48
+ # is that we might want to use current tooling to study some aspect of an
49
+ # earlier version of PyTorch. (e.g. a regression.)
50
+ #
51
+ # The problem is that Timer relies on several aspects of core PyTorch, namely
52
+ # some binding functions for Valgrind symbols in `torch._C` and the
53
+ # `torch.__config__._cxx_flags()` method. If we were to naively copy code
54
+ # around this wouldn't work as the symbols of interest aren't present in
55
+ # earlier versions of PyTorch. In order to work around this, we must add back
56
+ # testing shims. These shims will never activate during normal use, but will
57
+ # allow Timer to function outside of the "correct" version of PyTorch by
58
+ # emulating functionality that was added later.
59
+ #
60
+ # These shims are temporary, and as Timer becomes more integrated with
61
+ # PyTorch the cost and complexity of such shims will increase. Once back
62
+ # testing is no longer required (which is to say we have done enough historic
63
+ # analysis and the shims no longer justify their maintenance and code
64
+ # complexity costs) back testing paths will be removed.
65
+
66
+ CXX_FLAGS: Optional[list[str]]
67
+ if hasattr(torch.__config__, "_cxx_flags"):
68
+ try:
69
+ CXX_FLAGS = torch.__config__._cxx_flags().strip().split()
70
+ if CXX_FLAGS is not None and "-g" not in CXX_FLAGS:
71
+ CXX_FLAGS.append("-g")
72
+ # remove "-W" flags to allow build benchmarks
73
+ # with a relaxed constraint of compiler versions
74
+ if CXX_FLAGS is not None:
75
+ CXX_FLAGS = list(filter(lambda x: not x.startswith("-W"), CXX_FLAGS))
76
+
77
+ except RuntimeError:
78
+ # We are in FBCode.
79
+ CXX_FLAGS = None
80
+ else:
81
+ # FIXME: Remove when back testing is no longer required.
82
+ CXX_FLAGS = ["-O2", "-fPIC", "-g"]
83
+
84
+ EXTRA_INCLUDE_PATHS: list[str] = [os.path.join(SOURCE_ROOT, "valgrind_wrapper")]
85
+ CONDA_PREFIX = os.getenv("CONDA_PREFIX")
86
+ if CONDA_PREFIX is not None:
87
+ # Load will automatically search /usr/include, but not conda include.
88
+ EXTRA_INCLUDE_PATHS.append(os.path.join(CONDA_PREFIX, "include"))
89
+
90
+
91
+ COMPAT_CALLGRIND_BINDINGS: Optional[CallgrindModuleType] = None
92
+ def get_compat_bindings() -> CallgrindModuleType:
93
+ with LOCK:
94
+ global COMPAT_CALLGRIND_BINDINGS
95
+ if COMPAT_CALLGRIND_BINDINGS is None:
96
+ COMPAT_CALLGRIND_BINDINGS = cpp_extension.load(
97
+ name="callgrind_bindings",
98
+ sources=[os.path.join(
99
+ SOURCE_ROOT,
100
+ "valgrind_wrapper",
101
+ "compat_bindings.cpp"
102
+ )],
103
+ extra_cflags=CXX_FLAGS,
104
+ extra_include_paths=EXTRA_INCLUDE_PATHS,
105
+ )
106
+ return COMPAT_CALLGRIND_BINDINGS
107
+
108
+
109
+ def _compile_template(
110
+ *,
111
+ stmt: str,
112
+ setup: str,
113
+ global_setup: str,
114
+ src: str,
115
+ is_standalone: bool
116
+ ) -> Any:
117
+ for before, after, indentation in (
118
+ ("// GLOBAL_SETUP_TEMPLATE_LOCATION", global_setup, 0),
119
+ ("// SETUP_TEMPLATE_LOCATION", setup, 4),
120
+ ("// STMT_TEMPLATE_LOCATION", stmt, 8)
121
+ ):
122
+ # C++ doesn't care about indentation so this code isn't load
123
+ # bearing the way it is with Python, but this makes the source
124
+ # look nicer if a human has to look at it.
125
+ src = re.sub(
126
+ before,
127
+ textwrap.indent(after, " " * indentation)[indentation:],
128
+ src
129
+ )
130
+
131
+ # We want to isolate different Timers. However `cpp_extension` will
132
+ # cache builds which will significantly reduce the cost of repeated
133
+ # invocations.
134
+ with LOCK:
135
+ name = f"timer_cpp_{abs(hash(src))}"
136
+ build_dir = os.path.join(_get_build_root(), name)
137
+ os.makedirs(build_dir, exist_ok=True)
138
+
139
+ src_path = os.path.join(build_dir, "timer_src.cpp")
140
+ with open(src_path, "w") as f:
141
+ f.write(src)
142
+
143
+ # `cpp_extension` has its own locking scheme, so we don't need our lock.
144
+ return cpp_extension.load(
145
+ name=name,
146
+ sources=[src_path],
147
+ build_directory=build_dir,
148
+ extra_cflags=CXX_FLAGS,
149
+ extra_include_paths=EXTRA_INCLUDE_PATHS,
150
+ is_python_module=not is_standalone,
151
+ is_standalone=is_standalone,
152
+ )
153
+
154
+
155
+ def compile_timeit_template(*, stmt: str, setup: str, global_setup: str) -> TimeitModuleType:
156
+ template_path: str = os.path.join(SOURCE_ROOT, "timeit_template.cpp")
157
+ with open(template_path) as f:
158
+ src: str = f.read()
159
+
160
+ module = _compile_template(stmt=stmt, setup=setup, global_setup=global_setup, src=src, is_standalone=False)
161
+ assert isinstance(module, TimeitModuleType)
162
+ return module
163
+
164
+
165
+ def compile_callgrind_template(*, stmt: str, setup: str, global_setup: str) -> str:
166
+ template_path: str = os.path.join(SOURCE_ROOT, "valgrind_wrapper", "timer_callgrind_template.cpp")
167
+ with open(template_path) as f:
168
+ src: str = f.read()
169
+
170
+ target = _compile_template(stmt=stmt, setup=setup, global_setup=global_setup, src=src, is_standalone=True)
171
+ assert isinstance(target, str)
172
+ return target
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/fuzzer.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import itertools as it
4
+ from typing import Any, Callable, Optional, Union
5
+
6
+ import torch
7
+
8
+
9
+ __all__ = [
10
+ "Fuzzer",
11
+ "FuzzedParameter", "ParameterAlias",
12
+ "FuzzedTensor",
13
+ ]
14
+
15
+
16
+ _DISTRIBUTIONS = (
17
+ "loguniform",
18
+ "uniform",
19
+ )
20
+
21
+
22
+ class FuzzedParameter:
23
+ """Specification for a parameter to be generated during fuzzing."""
24
+ def __init__(
25
+ self,
26
+ name: str,
27
+ minval: Optional[Union[int, float]] = None,
28
+ maxval: Optional[Union[int, float]] = None,
29
+ distribution: Optional[Union[str, dict[Any, float]]] = None,
30
+ strict: bool = False,
31
+ ):
32
+ """
33
+ Args:
34
+ name:
35
+ A string name with which to identify the parameter.
36
+ FuzzedTensors can reference this string in their
37
+ specifications.
38
+ minval:
39
+ The lower bound for the generated value. See the description
40
+ of `distribution` for type behavior.
41
+ maxval:
42
+ The upper bound for the generated value. Type behavior is
43
+ identical to `minval`.
44
+ distribution:
45
+ Specifies the distribution from which this parameter should
46
+ be drawn. There are three possibilities:
47
+ - "loguniform"
48
+ Samples between `minval` and `maxval` (inclusive) such
49
+ that the probabilities are uniform in log space. As a
50
+ concrete example, if minval=1 and maxval=100, a sample
51
+ is as likely to fall in [1, 10) as it is [10, 100].
52
+ - "uniform"
53
+ Samples are chosen with uniform probability between
54
+ `minval` and `maxval` (inclusive). If either `minval`
55
+ or `maxval` is a float then the distribution is the
56
+ continuous uniform distribution; otherwise samples
57
+ are constrained to the integers.
58
+ - dict:
59
+ If a dict is passed, the keys are taken to be choices
60
+ for the variables and the values are interpreted as
61
+ probabilities. (And must sum to one.)
62
+ If a dict is passed, `minval` and `maxval` must not be set.
63
+ Otherwise, they must be set.
64
+ strict:
65
+ If a parameter is strict, it will not be included in the
66
+ iterative resampling process which Fuzzer uses to find a
67
+ valid parameter configuration. This allows an author to
68
+ prevent skew from resampling for a given parameter (for
69
+ instance, a low size limit could inadvertently bias towards
70
+ Tensors with fewer dimensions) at the cost of more iterations
71
+ when generating parameters.
72
+ """
73
+ self._name = name
74
+ self._minval = minval
75
+ self._maxval = maxval
76
+ self._distribution = self._check_distribution(distribution)
77
+ self.strict = strict
78
+
79
+ @property
80
+ def name(self):
81
+ return self._name
82
+
83
+ def sample(self, state):
84
+ if self._distribution == "loguniform":
85
+ return self._loguniform(state)
86
+
87
+ if self._distribution == "uniform":
88
+ return self._uniform(state)
89
+
90
+ if isinstance(self._distribution, dict):
91
+ return self._custom_distribution(state)
92
+
93
+ def _check_distribution(self, distribution):
94
+ if not isinstance(distribution, dict):
95
+ assert distribution in _DISTRIBUTIONS
96
+ else:
97
+ assert not any(i < 0 for i in distribution.values()), "Probabilities cannot be negative"
98
+ assert abs(sum(distribution.values()) - 1) <= 1e-5, "Distribution is not normalized"
99
+ assert self._minval is None
100
+ assert self._maxval is None
101
+
102
+ return distribution
103
+
104
+ def _loguniform(self, state):
105
+ import numpy as np
106
+ output = int(2 ** state.uniform(
107
+ low=np.log2(self._minval) if self._minval is not None else None,
108
+ high=np.log2(self._maxval) if self._maxval is not None else None,
109
+ ))
110
+ if self._minval is not None and output < self._minval:
111
+ return self._minval
112
+ if self._maxval is not None and output > self._maxval:
113
+ return self._maxval
114
+ return output
115
+
116
+ def _uniform(self, state):
117
+ if isinstance(self._minval, int) and isinstance(self._maxval, int):
118
+ return int(state.randint(low=self._minval, high=self._maxval + 1))
119
+ return state.uniform(low=self._minval, high=self._maxval)
120
+
121
+ def _custom_distribution(self, state):
122
+ import numpy as np
123
+ # If we directly pass the keys to `choice`, numpy will convert
124
+ # them to numpy dtypes.
125
+ index = state.choice(
126
+ np.arange(len(self._distribution)),
127
+ p=tuple(self._distribution.values()))
128
+ return list(self._distribution.keys())[index]
129
+
130
+
131
+ class ParameterAlias:
132
+ """Indicates that a parameter should alias the value of another parameter.
133
+
134
+ When used in conjunction with a custom distribution, this allows fuzzed
135
+ tensors to represent a broader range of behaviors. For example, the
136
+ following sometimes produces Tensors which broadcast:
137
+
138
+ Fuzzer(
139
+ parameters=[
140
+ FuzzedParameter("x_len", 4, 1024, distribution="uniform"),
141
+
142
+ # `y` will either be size one, or match the size of `x`.
143
+ FuzzedParameter("y_len", distribution={
144
+ 0.5: 1,
145
+ 0.5: ParameterAlias("x_len")
146
+ }),
147
+ ],
148
+ tensors=[
149
+ FuzzedTensor("x", size=("x_len",)),
150
+ FuzzedTensor("y", size=("y_len",)),
151
+ ],
152
+ )
153
+
154
+ Chains of alias' are allowed, but may not contain cycles.
155
+ """
156
+ def __init__(self, alias_to):
157
+ self.alias_to = alias_to
158
+
159
+ def __repr__(self):
160
+ return f"ParameterAlias[alias_to: {self.alias_to}]"
161
+
162
+
163
+ def dtype_size(dtype):
164
+ if dtype == torch.bool:
165
+ return 1
166
+ if dtype.is_floating_point or dtype.is_complex:
167
+ return int(torch.finfo(dtype).bits / 8)
168
+ return int(torch.iinfo(dtype).bits / 8)
169
+
170
+
171
+ def prod(values, base=1):
172
+ """np.prod can overflow, so for sizes the product should be done in Python.
173
+
174
+ Even though np.prod type promotes to int64, it can still overflow in which
175
+ case the negative value will pass the size check and OOM when attempting to
176
+ actually allocate the Tensor.
177
+ """
178
+ return functools.reduce(lambda x, y: int(x) * int(y), values, base)
179
+
180
+
181
+ class FuzzedTensor:
182
+ def __init__(
183
+ self,
184
+ name: str,
185
+ size: tuple[Union[str, int], ...],
186
+ steps: Optional[tuple[Union[str, int], ...]] = None,
187
+ probability_contiguous: float = 0.5,
188
+ min_elements: Optional[int] = None,
189
+ max_elements: Optional[int] = None,
190
+ max_allocation_bytes: Optional[int] = None,
191
+ dim_parameter: Optional[str] = None,
192
+ roll_parameter: Optional[str] = None,
193
+ dtype=torch.float32,
194
+ cuda=False,
195
+ tensor_constructor: Optional[Callable] = None
196
+ ):
197
+ """
198
+ Args:
199
+ name:
200
+ A string identifier for the generated Tensor.
201
+ size:
202
+ A tuple of integers or strings specifying the size of the generated
203
+ Tensor. String values will replaced with a concrete int during the
204
+ generation process, while ints are simply passed as literals.
205
+ steps:
206
+ An optional tuple with the same length as `size`. This indicates
207
+ that a larger Tensor should be allocated, and then sliced to
208
+ produce the generated Tensor. For instance, if size is (4, 8)
209
+ and steps is (1, 4), then a tensor `t` of size (4, 32) will be
210
+ created and then `t[:, ::4]` will be used. (Allowing one to test
211
+ Tensors with strided memory.)
212
+ probability_contiguous:
213
+ A number between zero and one representing the chance that the
214
+ generated Tensor has a contiguous memory layout. This is achieved by
215
+ randomly permuting the shape of a Tensor, calling `.contiguous()`,
216
+ and then permuting back. This is applied before `steps`, which can
217
+ also cause a Tensor to be non-contiguous.
218
+ min_elements:
219
+ The minimum number of parameters that this Tensor must have for a
220
+ set of parameters to be valid. (Otherwise they are resampled.)
221
+ max_elements:
222
+ Like `min_elements`, but setting an upper bound.
223
+ max_allocation_bytes:
224
+ Like `max_elements`, but for the size of Tensor that must be
225
+ allocated prior to slicing for `steps` (if applicable). For
226
+ example, a FloatTensor with size (1024, 1024) and steps (4, 4)
227
+ would have 1M elements, but would require a 64 MB allocation.
228
+ dim_parameter:
229
+ The length of `size` and `steps` will be truncated to this value.
230
+ This allows Tensors of varying dimensions to be generated by the
231
+ Fuzzer.
232
+ dtype:
233
+ The PyTorch dtype of the generated Tensor.
234
+ cuda:
235
+ Whether to place the Tensor on a GPU.
236
+ tensor_constructor:
237
+ Callable which will be used instead of the default Tensor
238
+ construction method. This allows the author to enforce properties
239
+ of the Tensor (e.g. it can only have certain values). The dtype and
240
+ concrete shape of the Tensor to be created will be passed, and
241
+ concrete values of all parameters will be passed as kwargs. Note
242
+ that transformations to the result (permuting, slicing) will be
243
+ performed by the Fuzzer; the tensor_constructor is only responsible
244
+ for creating an appropriately sized Tensor.
245
+ """
246
+ self._name = name
247
+ self._size = size
248
+ self._steps = steps
249
+ self._probability_contiguous = probability_contiguous
250
+ self._min_elements = min_elements
251
+ self._max_elements = max_elements
252
+ self._max_allocation_bytes = max_allocation_bytes
253
+ self._dim_parameter = dim_parameter
254
+ self._dtype = dtype
255
+ self._cuda = cuda
256
+ self._tensor_constructor = tensor_constructor
257
+
258
+ @property
259
+ def name(self):
260
+ return self._name
261
+
262
+ @staticmethod
263
+ def default_tensor_constructor(size, dtype, **kwargs):
264
+ if dtype.is_floating_point or dtype.is_complex:
265
+ return torch.rand(size=size, dtype=dtype, device="cpu")
266
+ else:
267
+ return torch.randint(1, 127, size=size, dtype=dtype, device="cpu")
268
+
269
+ def _make_tensor(self, params, state):
270
+ import numpy as np
271
+ size, steps, allocation_size = self._get_size_and_steps(params)
272
+ constructor = (
273
+ self._tensor_constructor or
274
+ self.default_tensor_constructor
275
+ )
276
+
277
+ raw_tensor = constructor(size=allocation_size, dtype=self._dtype, **params)
278
+ if self._cuda:
279
+ raw_tensor = raw_tensor.cuda()
280
+
281
+ # Randomly permute the Tensor and call `.contiguous()` to force re-ordering
282
+ # of the memory, and then permute it back to the original shape.
283
+ dim = len(size)
284
+ order = np.arange(dim)
285
+ if state.rand() > self._probability_contiguous:
286
+ while dim > 1 and np.all(order == np.arange(dim)):
287
+ order = state.permutation(raw_tensor.dim())
288
+
289
+ raw_tensor = raw_tensor.permute(tuple(order)).contiguous()
290
+ raw_tensor = raw_tensor.permute(tuple(np.argsort(order)))
291
+
292
+ slices = [slice(0, size * step, step) for size, step in zip(size, steps)]
293
+ tensor = raw_tensor[tuple(slices)]
294
+
295
+ properties = {
296
+ "numel": int(tensor.numel()),
297
+ "order": order,
298
+ "steps": steps,
299
+ "is_contiguous": tensor.is_contiguous(),
300
+ "dtype": str(self._dtype),
301
+ }
302
+
303
+ return tensor, properties
304
+
305
+ def _get_size_and_steps(self, params):
306
+ dim = (
307
+ params[self._dim_parameter]
308
+ if self._dim_parameter is not None
309
+ else len(self._size)
310
+ )
311
+
312
+ def resolve(values, dim):
313
+ """Resolve values into concrete integers."""
314
+ values = tuple(params.get(i, i) for i in values)
315
+ if len(values) > dim:
316
+ values = values[:dim]
317
+ if len(values) < dim:
318
+ values = values + tuple(1 for _ in range(dim - len(values)))
319
+ return values
320
+
321
+ size = resolve(self._size, dim)
322
+ steps = resolve(self._steps or (), dim)
323
+ allocation_size = tuple(size_i * step_i for size_i, step_i in zip(size, steps))
324
+ return size, steps, allocation_size
325
+
326
+ def satisfies_constraints(self, params):
327
+ size, _, allocation_size = self._get_size_and_steps(params)
328
+ # Product is computed in Python to avoid integer overflow.
329
+ num_elements = prod(size)
330
+ assert num_elements >= 0
331
+
332
+ allocation_bytes = prod(allocation_size, base=dtype_size(self._dtype))
333
+
334
+ def nullable_greater(left, right):
335
+ if left is None or right is None:
336
+ return False
337
+ return left > right
338
+
339
+ return not any((
340
+ nullable_greater(num_elements, self._max_elements),
341
+ nullable_greater(self._min_elements, num_elements),
342
+ nullable_greater(allocation_bytes, self._max_allocation_bytes),
343
+ ))
344
+
345
+
346
+ class Fuzzer:
347
+ def __init__(
348
+ self,
349
+ parameters: list[Union[FuzzedParameter, list[FuzzedParameter]]],
350
+ tensors: list[Union[FuzzedTensor, list[FuzzedTensor]]],
351
+ constraints: Optional[list[Callable]] = None,
352
+ seed: Optional[int] = None
353
+ ):
354
+ """
355
+ Args:
356
+ parameters:
357
+ List of FuzzedParameters which provide specifications
358
+ for generated parameters. Iterable elements will be
359
+ unpacked, though arbitrary nested structures will not.
360
+ tensors:
361
+ List of FuzzedTensors which define the Tensors which
362
+ will be created each step based on the parameters for
363
+ that step. Iterable elements will be unpacked, though
364
+ arbitrary nested structures will not.
365
+ constraints:
366
+ List of callables. They will be called with params
367
+ as kwargs, and if any of them return False the current
368
+ set of parameters will be rejected.
369
+ seed:
370
+ Seed for the RandomState used by the Fuzzer. This will
371
+ also be used to set the PyTorch random seed so that random
372
+ ops will create reproducible Tensors.
373
+ """
374
+ import numpy as np
375
+ if seed is None:
376
+ seed = int(np.random.RandomState().randint(0, 2 ** 32 - 1, dtype=np.int64))
377
+ self._seed = seed
378
+ self._parameters = Fuzzer._unpack(parameters, FuzzedParameter)
379
+ self._tensors = Fuzzer._unpack(tensors, FuzzedTensor)
380
+ self._constraints = constraints or ()
381
+
382
+ p_names = {p.name for p in self._parameters}
383
+ t_names = {t.name for t in self._tensors}
384
+ name_overlap = p_names.intersection(t_names)
385
+ if name_overlap:
386
+ raise ValueError(f"Duplicate names in parameters and tensors: {name_overlap}")
387
+
388
+ self._rejections = 0
389
+ self._total_generated = 0
390
+
391
+ @staticmethod
392
+ def _unpack(values, cls):
393
+ return tuple(it.chain.from_iterable(
394
+ [[i] if isinstance(i, cls) else i for i in values]
395
+ ))
396
+
397
+ def take(self, n):
398
+ import numpy as np
399
+ state = np.random.RandomState(self._seed)
400
+ torch.manual_seed(state.randint(low=0, high=2 ** 63, dtype=np.int64))
401
+ for _ in range(n):
402
+ params = self._generate(state)
403
+ tensors = {}
404
+ tensor_properties = {}
405
+ for t in self._tensors:
406
+ tensor, properties = t._make_tensor(params, state)
407
+ tensors[t.name] = tensor
408
+ tensor_properties[t.name] = properties
409
+ yield tensors, tensor_properties, params
410
+
411
+ @property
412
+ def rejection_rate(self):
413
+ if not self._total_generated:
414
+ return 0.
415
+ return self._rejections / self._total_generated
416
+
417
+ def _generate(self, state):
418
+ strict_params: dict[str, Union[float, int, ParameterAlias]] = {}
419
+ for _ in range(1000):
420
+ candidate_params: dict[str, Union[float, int, ParameterAlias]] = {}
421
+ for p in self._parameters:
422
+ if p.strict:
423
+ if p.name in strict_params:
424
+ candidate_params[p.name] = strict_params[p.name]
425
+ else:
426
+ candidate_params[p.name] = p.sample(state)
427
+ strict_params[p.name] = candidate_params[p.name]
428
+ else:
429
+ candidate_params[p.name] = p.sample(state)
430
+
431
+ candidate_params = self._resolve_aliases(candidate_params)
432
+
433
+ self._total_generated += 1
434
+ if not all(f(candidate_params) for f in self._constraints):
435
+ self._rejections += 1
436
+ continue
437
+
438
+ if not all(t.satisfies_constraints(candidate_params) for t in self._tensors):
439
+ self._rejections += 1
440
+ continue
441
+
442
+ return candidate_params
443
+ raise ValueError("Failed to generate a set of valid parameters.")
444
+
445
+ @staticmethod
446
+ def _resolve_aliases(params):
447
+ params = dict(params)
448
+ alias_count = sum(isinstance(v, ParameterAlias) for v in params.values())
449
+
450
+ keys = list(params.keys())
451
+ while alias_count:
452
+ for k in keys:
453
+ v = params[k]
454
+ if isinstance(v, ParameterAlias):
455
+ params[k] = params[v.alias_to]
456
+ alias_count_new = sum(isinstance(v, ParameterAlias) for v in params.values())
457
+ if alias_count == alias_count_new:
458
+ raise ValueError(f"ParameterAlias cycle detected\n{params}")
459
+
460
+ alias_count = alias_count_new
461
+
462
+ return params
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/sparse_fuzzer.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional, Union
3
+ from numbers import Number
4
+ import torch
5
+ from torch.utils.benchmark import FuzzedTensor
6
+ import math
7
+
8
+ class FuzzedSparseTensor(FuzzedTensor):
9
+ def __init__(
10
+ self,
11
+ name: str,
12
+ size: tuple[Union[str, int], ...],
13
+ min_elements: Optional[int] = None,
14
+ max_elements: Optional[int] = None,
15
+ dim_parameter: Optional[str] = None,
16
+ sparse_dim: Optional[str] = None,
17
+ nnz: Optional[str] = None,
18
+ density: Optional[str] = None,
19
+ coalesced: Optional[str] = None,
20
+ dtype=torch.float32,
21
+ cuda=False
22
+ ):
23
+ """
24
+ Args:
25
+ name:
26
+ A string identifier for the generated Tensor.
27
+ size:
28
+ A tuple of integers or strings specifying the size of the generated
29
+ Tensor. String values will replaced with a concrete int during the
30
+ generation process, while ints are simply passed as literals.
31
+ min_elements:
32
+ The minimum number of parameters that this Tensor must have for a
33
+ set of parameters to be valid. (Otherwise they are resampled.)
34
+ max_elements:
35
+ Like `min_elements`, but setting an upper bound.
36
+ dim_parameter:
37
+ The length of `size` will be truncated to this value.
38
+ This allows Tensors of varying dimensions to be generated by the
39
+ Fuzzer.
40
+ sparse_dim:
41
+ The number of sparse dimensions in a sparse tensor.
42
+ density:
43
+ This value allows tensors of varying sparsities to be generated by the Fuzzer.
44
+ coalesced:
45
+ The sparse tensor format permits uncoalesced sparse tensors,
46
+ where there may be duplicate coordinates in the indices.
47
+ dtype:
48
+ The PyTorch dtype of the generated Tensor.
49
+ cuda:
50
+ Whether to place the Tensor on a GPU.
51
+ """
52
+ super().__init__(name=name, size=size, min_elements=min_elements,
53
+ max_elements=max_elements, dim_parameter=dim_parameter, dtype=dtype, cuda=cuda)
54
+ self._density = density
55
+ self._coalesced = coalesced
56
+ self._sparse_dim = sparse_dim
57
+
58
+ @staticmethod
59
+ def sparse_tensor_constructor(size, dtype, sparse_dim, nnz, is_coalesced):
60
+ """sparse_tensor_constructor creates a sparse tensor with coo format.
61
+
62
+ Note that when `is_coalesced` is False, the number of elements is doubled but the number of indices
63
+ represents the same amount of number of non zeros `nnz`, i.e, this is virtually the same tensor
64
+ with the same sparsity pattern. Moreover, most of the sparse operation will use coalesce() method
65
+ and what we want here is to get a sparse tensor with the same `nnz` even if this is coalesced or not.
66
+
67
+ In the other hand when `is_coalesced` is True the number of elements is reduced in the coalescing process
68
+ by an unclear amount however the probability to generate duplicates indices are low for most of the cases.
69
+ This decision was taken on purpose to maintain the construction cost as low as possible.
70
+ """
71
+ if isinstance(size, Number):
72
+ size = [size] * sparse_dim
73
+ assert all(size[d] > 0 for d in range(sparse_dim)) or nnz == 0, 'invalid arguments'
74
+ v_size = [nnz] + list(size[sparse_dim:])
75
+ if dtype.is_floating_point:
76
+ v = torch.rand(size=v_size, dtype=dtype, device="cpu")
77
+ else:
78
+ v = torch.randint(1, 127, size=v_size, dtype=dtype, device="cpu")
79
+
80
+ i = torch.rand(sparse_dim, nnz, device="cpu")
81
+ i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i))
82
+ i = i.to(torch.long)
83
+
84
+ if not is_coalesced:
85
+ v = torch.cat([v, torch.randn_like(v)], 0)
86
+ i = torch.cat([i, i], 1)
87
+
88
+ x = torch.sparse_coo_tensor(i, v, torch.Size(size))
89
+ if is_coalesced:
90
+ x = x.coalesce()
91
+ return x
92
+
93
+ def _make_tensor(self, params, state):
94
+ size, _, _ = self._get_size_and_steps(params)
95
+ density = params['density']
96
+ nnz = math.ceil(sum(size) * density)
97
+ assert nnz <= sum(size)
98
+
99
+ is_coalesced = params['coalesced']
100
+ sparse_dim = params['sparse_dim'] if self._sparse_dim else len(size)
101
+ sparse_dim = min(sparse_dim, len(size))
102
+ tensor = self.sparse_tensor_constructor(size, self._dtype, sparse_dim, nnz, is_coalesced)
103
+
104
+ if self._cuda:
105
+ tensor = tensor.cuda()
106
+ sparse_dim = tensor.sparse_dim()
107
+ dense_dim = tensor.dense_dim()
108
+ is_hybrid = len(size[sparse_dim:]) > 0
109
+
110
+ properties = {
111
+ "numel": int(tensor.numel()),
112
+ "shape": tensor.size(),
113
+ "is_coalesced": tensor.is_coalesced(),
114
+ "density": density,
115
+ "sparsity": 1.0 - density,
116
+ "sparse_dim": sparse_dim,
117
+ "dense_dim": dense_dim,
118
+ "is_hybrid": is_hybrid,
119
+ "dtype": str(self._dtype),
120
+ }
121
+ return tensor, properties
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/timeit_template.cpp ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* C++ template for Timer.timeit
2
+
3
+ This template will be consumed by `cpp_jit.py`, and will replace:
4
+ `GLOBAL_SETUP_TEMPLATE_LOCATION`,
5
+ `SETUP_TEMPLATE_LOCATION`
6
+ and
7
+ `STMT_TEMPLATE_LOCATION`
8
+ sections with user provided statements.
9
+ */
10
+ #include <chrono>
11
+
12
+ #include <c10/util/irange.h>
13
+ #include <torch/csrc/utils/pybind.h>
14
+ #include <pybind11/pybind11.h>
15
+ #include <torch/extension.h>
16
+
17
+ // Global setup. (e.g. #includes)
18
+ // GLOBAL_SETUP_TEMPLATE_LOCATION
19
+
20
+ double timeit(int n) {
21
+ pybind11::gil_scoped_release no_gil;
22
+
23
+ // Setup
24
+ // SETUP_TEMPLATE_LOCATION
25
+
26
+ {
27
+ // Warmup
28
+ // STMT_TEMPLATE_LOCATION
29
+ }
30
+
31
+ // Main loop
32
+ auto start_time = std::chrono::high_resolution_clock::now();
33
+ for (const auto loop_idx : c10::irange(n)) {
34
+ (void)loop_idx;
35
+ // STMT_TEMPLATE_LOCATION
36
+ }
37
+ auto end_time = std::chrono::high_resolution_clock::now();
38
+ return std::chrono::duration<double>(end_time - start_time).count();
39
+ }
40
+
41
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
42
+ m.def("timeit", &timeit);
43
+ }
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/timer.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Timer class based on the timeit.Timer class, but torch aware."""
2
+ import enum
3
+ import timeit
4
+ import textwrap
5
+ from typing import overload, Any, Callable, NoReturn, Optional, Union
6
+
7
+ import torch
8
+ from torch.utils.benchmark.utils import common, cpp_jit
9
+ from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType
10
+ from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface
11
+
12
+
13
+ __all__ = ["Timer", "timer", "Language"]
14
+
15
+
16
+ if torch.backends.cuda.is_built() and torch.cuda.is_available(): # type: ignore[no-untyped-call]
17
+ def timer() -> float:
18
+ torch.cuda.synchronize()
19
+ return timeit.default_timer()
20
+ elif torch.xpu.is_available():
21
+ def timer() -> float:
22
+ torch.xpu.synchronize()
23
+ return timeit.default_timer()
24
+ elif torch._C._get_privateuse1_backend_name() != "privateuseone":
25
+ privateuse1_device_handler = getattr(torch, torch._C._get_privateuse1_backend_name(), None) \
26
+ if torch._C._get_privateuse1_backend_name() != "cpu" else None
27
+
28
+ def timer() -> float:
29
+ if privateuse1_device_handler:
30
+ privateuse1_device_handler.synchronize()
31
+ return timeit.default_timer()
32
+ else:
33
+ timer = timeit.default_timer
34
+
35
+
36
+ class Language(enum.Enum):
37
+ PYTHON = 0
38
+ CPP = 1
39
+
40
+
41
+ class CPPTimer:
42
+ def __init__(
43
+ self,
44
+ stmt: str,
45
+ setup: str,
46
+ global_setup: str,
47
+ timer: Callable[[], float],
48
+ globals: dict[str, Any],
49
+ ) -> None:
50
+ if timer is not timeit.default_timer:
51
+ raise NotImplementedError(
52
+ "PyTorch was built with CUDA and a GPU is present; however "
53
+ "Timer does not yet support GPU measurements. If your "
54
+ "code is CPU only, pass `timer=timeit.default_timer` to the "
55
+ "Timer's constructor to indicate this. (Note that this will "
56
+ "produce incorrect results if the GPU is in fact used, as "
57
+ "Timer will not synchronize CUDA.)"
58
+ )
59
+
60
+ if globals:
61
+ raise ValueError("C++ timing does not support globals.")
62
+
63
+ self._stmt: str = textwrap.dedent(stmt)
64
+ self._setup: str = textwrap.dedent(setup)
65
+ self._global_setup: str = textwrap.dedent(global_setup)
66
+ self._timeit_module: Optional[TimeitModuleType] = None
67
+
68
+ def timeit(self, number: int) -> float:
69
+ if self._timeit_module is None:
70
+ self._timeit_module = cpp_jit.compile_timeit_template(
71
+ stmt=self._stmt,
72
+ setup=self._setup,
73
+ global_setup=self._global_setup,
74
+ )
75
+
76
+ return self._timeit_module.timeit(number)
77
+
78
+
79
+ class Timer:
80
+ """Helper class for measuring execution time of PyTorch statements.
81
+
82
+ For a full tutorial on how to use this class, see:
83
+ https://pytorch.org/tutorials/recipes/recipes/benchmark.html
84
+
85
+ The PyTorch Timer is based on `timeit.Timer` (and in fact uses
86
+ `timeit.Timer` internally), but with several key differences:
87
+
88
+ 1) Runtime aware:
89
+ Timer will perform warmups (important as some elements of PyTorch are
90
+ lazily initialized), set threadpool size so that comparisons are
91
+ apples-to-apples, and synchronize asynchronous CUDA functions when
92
+ necessary.
93
+
94
+ 2) Focus on replicates:
95
+ When measuring code, and particularly complex kernels / models,
96
+ run-to-run variation is a significant confounding factor. It is
97
+ expected that all measurements should include replicates to quantify
98
+ noise and allow median computation, which is more robust than mean.
99
+ To that effect, this class deviates from the `timeit` API by
100
+ conceptually merging `timeit.Timer.repeat` and `timeit.Timer.autorange`.
101
+ (Exact algorithms are discussed in method docstrings.) The `timeit`
102
+ method is replicated for cases where an adaptive strategy is not
103
+ desired.
104
+
105
+ 3) Optional metadata:
106
+ When defining a Timer, one can optionally specify `label`, `sub_label`,
107
+ `description`, and `env`. (Defined later) These fields are included in
108
+ the representation of result object and by the `Compare` class to group
109
+ and display results for comparison.
110
+
111
+ 4) Instruction counts
112
+ In addition to wall times, Timer can run a statement under Callgrind
113
+ and report instructions executed.
114
+
115
+ Directly analogous to `timeit.Timer` constructor arguments:
116
+
117
+ `stmt`, `setup`, `timer`, `globals`
118
+
119
+ PyTorch Timer specific constructor arguments:
120
+
121
+ `label`, `sub_label`, `description`, `env`, `num_threads`
122
+
123
+ Args:
124
+ stmt: Code snippet to be run in a loop and timed.
125
+
126
+ setup: Optional setup code. Used to define variables used in `stmt`
127
+
128
+ global_setup: (C++ only)
129
+ Code which is placed at the top level of the file for things like
130
+ `#include` statements.
131
+
132
+ timer:
133
+ Callable which returns the current time. If PyTorch was built
134
+ without CUDA or there is no GPU present, this defaults to
135
+ `timeit.default_timer`; otherwise it will synchronize CUDA before
136
+ measuring the time.
137
+
138
+ globals:
139
+ A dict which defines the global variables when `stmt` is being
140
+ executed. This is the other method for providing variables which
141
+ `stmt` needs.
142
+
143
+ label:
144
+ String which summarizes `stmt`. For instance, if `stmt` is
145
+ "torch.nn.functional.relu(torch.add(x, 1, out=out))"
146
+ one might set label to "ReLU(x + 1)" to improve readability.
147
+
148
+ sub_label:
149
+ Provide supplemental information to disambiguate measurements
150
+ with identical stmt or label. For instance, in our example
151
+ above sub_label might be "float" or "int", so that it is easy
152
+ to differentiate:
153
+ "ReLU(x + 1): (float)"
154
+
155
+ "ReLU(x + 1): (int)"
156
+ when printing Measurements or summarizing using `Compare`.
157
+
158
+ description:
159
+ String to distinguish measurements with identical label and
160
+ sub_label. The principal use of `description` is to signal to
161
+ `Compare` the columns of data. For instance one might set it
162
+ based on the input size to create a table of the form: ::
163
+
164
+ | n=1 | n=4 | ...
165
+ ------------- ...
166
+ ReLU(x + 1): (float) | ... | ... | ...
167
+ ReLU(x + 1): (int) | ... | ... | ...
168
+
169
+
170
+ using `Compare`. It is also included when printing a Measurement.
171
+
172
+ env:
173
+ This tag indicates that otherwise identical tasks were run in
174
+ different environments, and are therefore not equivalent, for
175
+ instance when A/B testing a change to a kernel. `Compare` will
176
+ treat Measurements with different `env` specification as distinct
177
+ when merging replicate runs.
178
+
179
+ num_threads:
180
+ The size of the PyTorch threadpool when executing `stmt`. Single
181
+ threaded performance is important as both a key inference workload
182
+ and a good indicator of intrinsic algorithmic efficiency, so the
183
+ default is set to one. This is in contrast to the default PyTorch
184
+ threadpool size which tries to utilize all cores.
185
+ """
186
+
187
+ _timer_cls: type[TimerClass] = timeit.Timer
188
+
189
+ def __init__(
190
+ self,
191
+ stmt: str = "pass",
192
+ setup: str = "pass",
193
+ global_setup: str = "",
194
+ timer: Callable[[], float] = timer,
195
+ globals: Optional[dict[str, Any]] = None,
196
+ label: Optional[str] = None,
197
+ sub_label: Optional[str] = None,
198
+ description: Optional[str] = None,
199
+ env: Optional[str] = None,
200
+ num_threads: int = 1,
201
+ language: Union[Language, str] = Language.PYTHON,
202
+ ):
203
+ if not isinstance(stmt, str):
204
+ raise ValueError("Currently only a `str` stmt is supported.")
205
+
206
+ # We copy `globals` to prevent mutations from leaking.
207
+ # (For instance, `eval` adds the `__builtins__` key)
208
+ self._globals = dict(globals or {})
209
+
210
+ timer_kwargs = {}
211
+ if language in (Language.PYTHON, "py", "python"):
212
+ # Include `torch` if not specified as a convenience feature.
213
+ self._globals.setdefault("torch", torch)
214
+ self._language: Language = Language.PYTHON
215
+ if global_setup:
216
+ raise ValueError(
217
+ f"global_setup is C++ only, got `{global_setup}`. Most "
218
+ "likely this code can simply be moved to `setup`."
219
+ )
220
+
221
+ elif language in (Language.CPP, "cpp", "c++"):
222
+ assert self._timer_cls is timeit.Timer, "_timer_cls has already been swapped."
223
+ self._timer_cls = CPPTimer
224
+ setup = ("" if setup == "pass" else setup)
225
+ self._language = Language.CPP
226
+ timer_kwargs["global_setup"] = global_setup
227
+
228
+ else:
229
+ raise ValueError(f"Invalid language `{language}`.")
230
+
231
+ # Convenience adjustment so that multi-line code snippets defined in
232
+ # functions do not IndentationError (Python) or look odd (C++). The
233
+ # leading newline removal is for the initial newline that appears when
234
+ # defining block strings. For instance:
235
+ # textwrap.dedent("""
236
+ # print("This is a stmt")
237
+ # """)
238
+ # produces '\nprint("This is a stmt")\n'.
239
+ #
240
+ # Stripping this down to 'print("This is a stmt")' doesn't change
241
+ # what gets executed, but it makes __repr__'s nicer.
242
+ stmt = textwrap.dedent(stmt)
243
+ stmt = (stmt[1:] if stmt and stmt[0] == "\n" else stmt).rstrip()
244
+ setup = textwrap.dedent(setup)
245
+ setup = (setup[1:] if setup and setup[0] == "\n" else setup).rstrip()
246
+
247
+ self._timer = self._timer_cls(
248
+ stmt=stmt,
249
+ setup=setup,
250
+ timer=timer,
251
+ globals=valgrind_timer_interface.CopyIfCallgrind.unwrap_all(self._globals),
252
+ **timer_kwargs,
253
+ )
254
+ self._task_spec = common.TaskSpec(
255
+ stmt=stmt,
256
+ setup=setup,
257
+ global_setup=global_setup,
258
+ label=label,
259
+ sub_label=sub_label,
260
+ description=description,
261
+ env=env,
262
+ num_threads=num_threads,
263
+ )
264
+
265
+ def _timeit(self, number: int) -> float:
266
+ # Even calling a timer in C++ takes ~50 ns, so no real operation should
267
+ # take less than 1 ns. (And this prevents divide by zero errors.)
268
+ return max(self._timer.timeit(number), 1e-9)
269
+
270
+ def timeit(self, number: int = 1000000) -> common.Measurement:
271
+ """Mirrors the semantics of timeit.Timer.timeit().
272
+
273
+ Execute the main statement (`stmt`) `number` times.
274
+ https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit
275
+ """
276
+ with common.set_torch_threads(self._task_spec.num_threads):
277
+ # Warmup
278
+ self._timeit(number=max(int(number // 100), 2))
279
+
280
+ return common.Measurement(
281
+ number_per_run=number,
282
+ raw_times=[self._timeit(number=number)],
283
+ task_spec=self._task_spec
284
+ )
285
+
286
+ def repeat(self, repeat: int = -1, number: int = -1) -> None:
287
+ raise NotImplementedError("See `Timer.blocked_autorange.`")
288
+
289
+ def autorange(self, callback: Optional[Callable[[int, float], NoReturn]] = None) -> None:
290
+ raise NotImplementedError("See `Timer.blocked_autorange.`")
291
+
292
+ def _threaded_measurement_loop(
293
+ self,
294
+ number: int,
295
+ time_hook: Callable[[], float],
296
+ stop_hook: Callable[[list[float]], bool],
297
+ min_run_time: float,
298
+ max_run_time: Optional[float] = None,
299
+ callback: Optional[Callable[[int, float], NoReturn]] = None
300
+ ) -> list[float]:
301
+ total_time = 0.0
302
+ can_stop = False
303
+ times: list[float] = []
304
+ with common.set_torch_threads(self._task_spec.num_threads):
305
+ while (total_time < min_run_time) or (not can_stop):
306
+ time_spent = time_hook()
307
+ times.append(time_spent)
308
+ total_time += time_spent
309
+ if callback:
310
+ callback(number, time_spent)
311
+ can_stop = stop_hook(times)
312
+ if max_run_time and total_time > max_run_time:
313
+ break
314
+ return times
315
+
316
+ def _estimate_block_size(self, min_run_time: float) -> int:
317
+ with common.set_torch_threads(self._task_spec.num_threads):
318
+ # Estimate the block size needed for measurement to be negligible
319
+ # compared to the inner loop. This also serves as a warmup.
320
+ overhead = torch.tensor([self._timeit(0) for _ in range(5)]).median().item()
321
+ number = 1
322
+ while True:
323
+ time_taken = self._timeit(number)
324
+ relative_overhead = overhead / time_taken
325
+ if relative_overhead <= 1e-4 and time_taken >= min_run_time / 1000:
326
+ break
327
+ if time_taken > min_run_time:
328
+ break
329
+ # Avoid overflow in C++ pybind11 interface
330
+ if number * 10 > 2147483647:
331
+ break
332
+ number *= 10
333
+ return number
334
+
335
+ def blocked_autorange(
336
+ self,
337
+ callback: Optional[Callable[[int, float], NoReturn]] = None,
338
+ min_run_time: float = 0.2,
339
+ ) -> common.Measurement:
340
+ """Measure many replicates while keeping timer overhead to a minimum.
341
+
342
+ At a high level, blocked_autorange executes the following pseudo-code::
343
+
344
+ `setup`
345
+
346
+ total_time = 0
347
+ while total_time < min_run_time
348
+ start = timer()
349
+ for _ in range(block_size):
350
+ `stmt`
351
+ total_time += (timer() - start)
352
+
353
+ Note the variable `block_size` in the inner loop. The choice of block
354
+ size is important to measurement quality, and must balance two
355
+ competing objectives:
356
+
357
+ 1) A small block size results in more replicates and generally
358
+ better statistics.
359
+
360
+ 2) A large block size better amortizes the cost of `timer`
361
+ invocation, and results in a less biased measurement. This is
362
+ important because CUDA synchronization time is non-trivial
363
+ (order single to low double digit microseconds) and would
364
+ otherwise bias the measurement.
365
+
366
+ blocked_autorange sets block_size by running a warmup period,
367
+ increasing block size until timer overhead is less than 0.1% of
368
+ the overall computation. This value is then used for the main
369
+ measurement loop.
370
+
371
+ Returns:
372
+ A `Measurement` object that contains measured runtimes and
373
+ repetition counts, and can be used to compute statistics.
374
+ (mean, median, etc.)
375
+ """
376
+ number = self._estimate_block_size(min_run_time)
377
+
378
+ def time_hook() -> float:
379
+ return self._timeit(number)
380
+
381
+ def stop_hook(times: list[float]) -> bool:
382
+ return True
383
+
384
+ times = self._threaded_measurement_loop(
385
+ number, time_hook, stop_hook,
386
+ min_run_time=min_run_time,
387
+ callback=callback)
388
+
389
+ return common.Measurement(
390
+ number_per_run=number,
391
+ raw_times=times,
392
+ task_spec=self._task_spec
393
+ )
394
+
395
+ def adaptive_autorange(
396
+ self,
397
+ threshold: float = 0.1,
398
+ *,
399
+ min_run_time: float = 0.01,
400
+ max_run_time: float = 10.0,
401
+ callback: Optional[Callable[[int, float], NoReturn]] = None,
402
+ ) -> common.Measurement:
403
+ """Similar to `blocked_autorange` but also checks for variablility in measurements
404
+ and repeats until iqr/median is smaller than `threshold` or `max_run_time` is reached.
405
+
406
+
407
+ At a high level, adaptive_autorange executes the following pseudo-code::
408
+
409
+ `setup`
410
+
411
+ times = []
412
+ while times.sum < max_run_time
413
+ start = timer()
414
+ for _ in range(block_size):
415
+ `stmt`
416
+ times.append(timer() - start)
417
+
418
+ enough_data = len(times)>3 and times.sum > min_run_time
419
+ small_iqr=times.iqr/times.mean<threshold
420
+
421
+ if enough_data and small_iqr:
422
+ break
423
+
424
+ Args:
425
+ threshold: value of iqr/median threshold for stopping
426
+
427
+ min_run_time: total runtime needed before checking `threshold`
428
+
429
+ max_run_time: total runtime for all measurements regardless of `threshold`
430
+
431
+ Returns:
432
+ A `Measurement` object that contains measured runtimes and
433
+ repetition counts, and can be used to compute statistics.
434
+ (mean, median, etc.)
435
+ """
436
+ number = self._estimate_block_size(min_run_time=0.05)
437
+
438
+ def time_hook() -> float:
439
+ return self._timeit(number)
440
+
441
+ def stop_hook(times: list[float]) -> bool:
442
+ if len(times) > 3:
443
+ return common.Measurement(
444
+ number_per_run=number,
445
+ raw_times=times,
446
+ task_spec=self._task_spec
447
+ ).meets_confidence(threshold=threshold)
448
+ return False
449
+ times = self._threaded_measurement_loop(
450
+ number, time_hook, stop_hook, min_run_time, max_run_time, callback=callback)
451
+
452
+ return common.Measurement(
453
+ number_per_run=number,
454
+ raw_times=times,
455
+ task_spec=self._task_spec
456
+ )
457
+
458
+ @overload
459
+ def collect_callgrind(
460
+ self,
461
+ number: int,
462
+ *,
463
+ repeats: None,
464
+ collect_baseline: bool,
465
+ retain_out_file: bool,
466
+ ) -> valgrind_timer_interface.CallgrindStats:
467
+ ...
468
+
469
+ @overload
470
+ def collect_callgrind(
471
+ self,
472
+ number: int,
473
+ *,
474
+ repeats: int,
475
+ collect_baseline: bool,
476
+ retain_out_file: bool,
477
+ ) -> tuple[valgrind_timer_interface.CallgrindStats, ...]:
478
+ ...
479
+
480
+ def collect_callgrind(
481
+ self,
482
+ number: int = 100,
483
+ *,
484
+ repeats: Optional[int] = None,
485
+ collect_baseline: bool = True,
486
+ retain_out_file: bool = False,
487
+ ) -> Any:
488
+ """Collect instruction counts using Callgrind.
489
+
490
+ Unlike wall times, instruction counts are deterministic
491
+ (modulo non-determinism in the program itself and small amounts of
492
+ jitter from the Python interpreter.) This makes them ideal for detailed
493
+ performance analysis. This method runs `stmt` in a separate process
494
+ so that Valgrind can instrument the program. Performance is severely
495
+ degraded due to the instrumentation, however this is ameliorated by
496
+ the fact that a small number of iterations is generally sufficient to
497
+ obtain good measurements.
498
+
499
+ In order to to use this method `valgrind`, `callgrind_control`, and
500
+ `callgrind_annotate` must be installed.
501
+
502
+ Because there is a process boundary between the caller (this process)
503
+ and the `stmt` execution, `globals` cannot contain arbitrary in-memory
504
+ data structures. (Unlike timing methods) Instead, globals are
505
+ restricted to builtins, `nn.Modules`'s, and TorchScripted functions/modules
506
+ to reduce the surprise factor from serialization and subsequent
507
+ deserialization. The `GlobalsBridge` class provides more detail on this
508
+ subject. Take particular care with nn.Modules: they rely on pickle and
509
+ you may need to add an import to `setup` for them to transfer properly.
510
+
511
+ By default, a profile for an empty statement will be collected and
512
+ cached to indicate how many instructions are from the Python loop which
513
+ drives `stmt`.
514
+
515
+ Returns:
516
+ A `CallgrindStats` object which provides instruction counts and
517
+ some basic facilities for analyzing and manipulating results.
518
+ """
519
+ if not isinstance(self._task_spec.stmt, str):
520
+ raise ValueError("`collect_callgrind` currently only supports string `stmt`")
521
+
522
+ if repeats is not None and repeats < 1:
523
+ raise ValueError("If specified, `repeats` must be >= 1")
524
+
525
+ # Check that the statement is valid. It doesn't guarantee success, but it's much
526
+ # simpler and quicker to raise an exception for a faulty `stmt` or `setup` in
527
+ # the parent process rather than the valgrind subprocess.
528
+ self._timeit(1)
529
+ is_python = (self._language == Language.PYTHON)
530
+ assert is_python or not self._globals
531
+ result = valgrind_timer_interface.wrapper_singleton().collect_callgrind(
532
+ task_spec=self._task_spec,
533
+ globals=self._globals,
534
+ number=number,
535
+ repeats=repeats or 1,
536
+ collect_baseline=collect_baseline and is_python,
537
+ is_python=is_python,
538
+ retain_out_file=retain_out_file,
539
+ )
540
+
541
+ return (result[0] if repeats is None else result)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ /*
3
+ ----------------------------------------------------------------
4
+
5
+ Notice that the following BSD-style license applies to this one
6
+ file (callgrind.h) only. The rest of Valgrind is licensed under the
7
+ terms of the GNU General Public License, version 2, unless
8
+ otherwise indicated. See the COPYING file in the source
9
+ distribution for details.
10
+
11
+ ----------------------------------------------------------------
12
+
13
+ This file is part of callgrind, a valgrind tool for cache simulation
14
+ and call tree tracing.
15
+
16
+ Copyright (C) 2003-2017 Josef Weidendorfer. All rights reserved.
17
+
18
+ Redistribution and use in source and binary forms, with or without
19
+ modification, are permitted provided that the following conditions
20
+ are met:
21
+
22
+ 1. Redistributions of source code must retain the above copyright
23
+ notice, this list of conditions and the following disclaimer.
24
+
25
+ 2. The origin of this software must not be misrepresented; you must
26
+ not claim that you wrote the original software. If you use this
27
+ software in a product, an acknowledgment in the product
28
+ documentation would be appreciated but is not required.
29
+
30
+ 3. Altered source versions must be plainly marked as such, and must
31
+ not be misrepresented as being the original software.
32
+
33
+ 4. The name of the author may not be used to endorse or promote
34
+ products derived from this software without specific prior written
35
+ permission.
36
+
37
+ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
38
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
39
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40
+ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
41
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
43
+ GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
45
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
46
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48
+
49
+ ----------------------------------------------------------------
50
+
51
+ Notice that the above BSD-style license applies to this one file
52
+ (callgrind.h) only. The entire rest of Valgrind is licensed under
53
+ the terms of the GNU General Public License, version 2. See the
54
+ COPYING file in the source distribution for details.
55
+
56
+ ----------------------------------------------------------------
57
+ */
58
+
59
+ #ifndef __CALLGRIND_H
60
+ #define __CALLGRIND_H
61
+
62
+ #include "valgrind.h"
63
+
64
+ /* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !!
65
+ This enum comprises an ABI exported by Valgrind to programs
66
+ which use client requests. DO NOT CHANGE THE ORDER OF THESE
67
+ ENTRIES, NOR DELETE ANY -- add new ones at the end.
68
+
69
+ The identification ('C','T') for Callgrind has historical
70
+ reasons: it was called "Calltree" before. Besides, ('C','G') would
71
+ clash with cachegrind.
72
+ */
73
+
74
+ typedef
75
+ enum {
76
+ VG_USERREQ__DUMP_STATS = VG_USERREQ_TOOL_BASE('C','T'),
77
+ VG_USERREQ__ZERO_STATS,
78
+ VG_USERREQ__TOGGLE_COLLECT,
79
+ VG_USERREQ__DUMP_STATS_AT,
80
+ VG_USERREQ__START_INSTRUMENTATION,
81
+ VG_USERREQ__STOP_INSTRUMENTATION
82
+ } Vg_CallgrindClientRequest;
83
+
84
+ /* Dump current state of cost centers, and zero them afterwards */
85
+ #define CALLGRIND_DUMP_STATS \
86
+ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DUMP_STATS, \
87
+ 0, 0, 0, 0, 0)
88
+
89
+ /* Dump current state of cost centers, and zero them afterwards.
90
+ The argument is appended to a string stating the reason which triggered
91
+ the dump. This string is written as a description field into the
92
+ profile data dump. */
93
+ #define CALLGRIND_DUMP_STATS_AT(pos_str) \
94
+ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DUMP_STATS_AT, \
95
+ pos_str, 0, 0, 0, 0)
96
+
97
+ /* Zero cost centers */
98
+ #define CALLGRIND_ZERO_STATS \
99
+ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ZERO_STATS, \
100
+ 0, 0, 0, 0, 0)
101
+
102
+ /* Toggles collection state.
103
+ The collection state specifies whether the happening of events
104
+ should be noted or if they are to be ignored. Events are noted
105
+ by increment of counters in a cost center */
106
+ #define CALLGRIND_TOGGLE_COLLECT \
107
+ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__TOGGLE_COLLECT, \
108
+ 0, 0, 0, 0, 0)
109
+
110
+ /* Start full callgrind instrumentation if not already switched on.
111
+ When cache simulation is done, it will flush the simulated cache;
112
+ this will lead to an artificial cache warmup phase afterwards with
113
+ cache misses which would not have happened in reality. */
114
+ #define CALLGRIND_START_INSTRUMENTATION \
115
+ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__START_INSTRUMENTATION, \
116
+ 0, 0, 0, 0, 0)
117
+
118
+ /* Stop full callgrind instrumentation if not already switched off.
119
+ This flushes Valgrinds translation cache, and does no additional
120
+ instrumentation afterwards, which effectivly will run at the same
121
+ speed as the "none" tool (ie. at minimal slowdown).
122
+ Use this to bypass Callgrind aggregation for uninteresting code parts.
123
+ To start Callgrind in this mode to ignore the setup phase, use
124
+ the option "--instr-atstart=no". */
125
+ #define CALLGRIND_STOP_INSTRUMENTATION \
126
+ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__STOP_INSTRUMENTATION, \
127
+ 0, 0, 0, 0, 0)
128
+
129
+ #endif /* __CALLGRIND_H */
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/compat_bindings.cpp ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Used to collect profiles of old versions of PyTorch. */
2
+ #include <callgrind.h>
3
+ #include <pybind11/pybind11.h>
4
+
5
+ bool _valgrind_supported_platform() {
6
+ #if defined(NVALGRIND)
7
+ return false;
8
+ #else
9
+ return true;
10
+ #endif
11
+ }
12
+
13
+ void _valgrind_toggle() {
14
+ #if defined(NVALGRIND)
15
+ TORCH_CHECK(false, "Valgrind is not supported.");
16
+ #else
17
+ CALLGRIND_TOGGLE_COLLECT;
18
+ #endif
19
+ }
20
+
21
+ void _valgrind_toggle_and_dump_stats() {
22
+ #if defined(NVALGRIND)
23
+ TORCH_CHECK(false, "Valgrind is not supported.");
24
+ #else
25
+ // NB: See note in Module.cpp
26
+ CALLGRIND_TOGGLE_COLLECT;
27
+ CALLGRIND_DUMP_STATS;
28
+ #endif
29
+ }
30
+
31
+ PYBIND11_MODULE(callgrind_bindings, m) {
32
+ m.def("_valgrind_supported_platform", &_valgrind_supported_platform);
33
+ m.def("_valgrind_toggle", &_valgrind_toggle);
34
+ m.def("_valgrind_toggle_and_dump_stats", &_valgrind_dump_stats);
35
+ }
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_callgrind_template.cpp ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* C++ template for Timer.collect_callgrind
2
+
3
+ This template will be consumed by `cpp_jit.py`, and will replace:
4
+ `GLOBAL_SETUP_TEMPLATE_LOCATION`,
5
+ `SETUP_TEMPLATE_LOCATION`
6
+ and
7
+ `STMT_TEMPLATE_LOCATION`
8
+ sections with user provided statements.
9
+ */
10
+
11
+ #include <c10/util/irange.h>
12
+ #include <callgrind.h>
13
+ #include <torch/torch.h>
14
+
15
+ #include <string>
16
+
17
+ // Global setup. (e.g. #includes)
18
+ // GLOBAL_SETUP_TEMPLATE_LOCATION
19
+
20
+ #if defined(NVALGRIND)
21
+ static_assert(false);
22
+ #endif
23
+
24
+ int main(int argc, char* argv[]) {
25
+ // This file should only be called inside of `Timer`, so we can adopt a
26
+ // very simple and rigid argument parsing scheme.
27
+ TORCH_CHECK(argc == 9);
28
+ TORCH_CHECK(std::string(argv[1]) == "--number");
29
+ auto number = std::stoi(argv[2]);
30
+
31
+ TORCH_CHECK(
32
+ std::string(argv[3]) == "--number-warmup" ||
33
+ std::string(argv[3]) == "--number_warmup");
34
+ auto number_warmup = std::stoi(argv[4]);
35
+
36
+ TORCH_CHECK(std::string(argv[5]) == "--repeats");
37
+ auto repeats = std::stoi(argv[6]);
38
+
39
+ TORCH_CHECK(
40
+ std::string(argv[7]) == "--number-threads" ||
41
+ std::string(argv[7]) == "--number_threads");
42
+ auto number_threads = std::stoi(argv[8]);
43
+ torch::set_num_threads(number_threads);
44
+
45
+ // Setup
46
+ // SETUP_TEMPLATE_LOCATION
47
+
48
+ // Warmup
49
+ for (const auto i : c10::irange(number_warmup)) {
50
+ (void)i;
51
+ // STMT_TEMPLATE_LOCATION
52
+ }
53
+
54
+ // Main loop
55
+ for (const auto repeat : c10::irange(repeats)) {
56
+ (void)repeat;
57
+ CALLGRIND_TOGGLE_COLLECT;
58
+
59
+ for (const auto i : c10::irange(number)) {
60
+ (void)i;
61
+ // STMT_TEMPLATE_LOCATION
62
+ }
63
+
64
+ // NB: See note in Module.cpp
65
+ CALLGRIND_TOGGLE_COLLECT;
66
+ CALLGRIND_DUMP_STATS;
67
+ }
68
+ }
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Intermediate layer between `Timer` and `valgrind`."""
2
+ import collections
3
+ import enum
4
+ import dataclasses
5
+ import itertools as it
6
+ import os
7
+ import pickle
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import textwrap
13
+ from typing import (
14
+ cast, Any, Callable, NamedTuple,
15
+ Optional, Union, TYPE_CHECKING)
16
+ from collections.abc import Iterator
17
+
18
+ import torch
19
+ from torch.utils.benchmark.utils import common, cpp_jit
20
+ from torch.utils.benchmark.utils._stubs import CallgrindModuleType
21
+ import operator
22
+
23
+
24
+ __all__ = ["FunctionCount", "FunctionCounts", "CallgrindStats", "CopyIfCallgrind"]
25
+
26
+
27
+ if TYPE_CHECKING:
28
+ CompletedProcessType = subprocess.CompletedProcess[str]
29
+ else:
30
+ CompletedProcessType = subprocess.CompletedProcess
31
+
32
+
33
+ class FunctionCount(NamedTuple):
34
+ # TODO(#105471): Rename the count field
35
+ count: int # type: ignore[assignment]
36
+ function: str
37
+
38
+
39
+ @dataclasses.dataclass(repr=False, eq=False, frozen=True)
40
+ class FunctionCounts:
41
+ """Container for manipulating Callgrind results.
42
+
43
+ It supports:
44
+ 1) Addition and subtraction to combine or diff results.
45
+ 2) Tuple-like indexing.
46
+ 3) A `denoise` function which strips CPython calls which are known to
47
+ be non-deterministic and quite noisy.
48
+ 4) Two higher order methods (`filter` and `transform`) for custom
49
+ manipulation.
50
+ """
51
+ _data: tuple[FunctionCount, ...]
52
+ inclusive: bool
53
+ truncate_rows: bool = True
54
+
55
+ # For normal use, torch._tensor_str.PRINT_OPTS.linewidth determines
56
+ # the print settings. This is simply to allow hermetic unit tests.
57
+ _linewidth: Optional[int] = None
58
+
59
+ def __iter__(self) -> Iterator[FunctionCount]:
60
+ yield from self._data
61
+
62
+ def __len__(self) -> int:
63
+ return len(self._data)
64
+
65
+ def __getitem__(self, item: Any) -> Union[FunctionCount, "FunctionCounts"]:
66
+ data: Union[FunctionCount, tuple[FunctionCount, ...]] = self._data[item]
67
+ return (
68
+ FunctionCounts(cast(tuple[FunctionCount, ...], data), self.inclusive, truncate_rows=False)
69
+ if isinstance(data, tuple) else data
70
+ )
71
+
72
+ def __repr__(self) -> str:
73
+ count_len = 0
74
+ for c, _ in self:
75
+ # Account for sign in string length.
76
+ count_len = max(count_len, len(str(c)) + int(c < 0))
77
+
78
+ lines = []
79
+ linewidth = self._linewidth or torch._tensor_str.PRINT_OPTS.linewidth
80
+ fn_str_len = max(linewidth - count_len - 4, 40)
81
+ for c, fn in self:
82
+ if len(fn) > fn_str_len:
83
+ left_len = int((fn_str_len - 5) // 2)
84
+ fn = fn[:left_len] + " ... " + fn[-(fn_str_len - left_len - 5):]
85
+ lines.append(f" {c:>{count_len}} {fn}")
86
+
87
+ if self.truncate_rows and len(lines) > 18:
88
+ lines = lines[:9] + ["...".rjust(count_len + 2)] + lines[-9:]
89
+
90
+ if not self.inclusive:
91
+ lines.extend(["", f"Total: {self.sum()}"])
92
+
93
+ return "\n".join([super().__repr__()] + lines)
94
+
95
+ def __add__(
96
+ self,
97
+ other: "FunctionCounts",
98
+ ) -> "FunctionCounts":
99
+ return self._merge(other, lambda c: c)
100
+
101
+ def __sub__(
102
+ self,
103
+ other: "FunctionCounts",
104
+ ) -> "FunctionCounts":
105
+ return self._merge(other, operator.neg)
106
+
107
+ def __mul__(self, other: Union[int, float]) -> "FunctionCounts":
108
+ return self._from_dict({
109
+ fn: int(c * other) for c, fn in self._data
110
+ }, self.inclusive)
111
+
112
+ def transform(self, map_fn: Callable[[str], str]) -> "FunctionCounts":
113
+ """Apply `map_fn` to all of the function names.
114
+
115
+ This can be used to regularize function names (e.g. stripping irrelevant
116
+ parts of the file path), coalesce entries by mapping multiple functions
117
+ to the same name (in which case the counts are added together), etc.
118
+ """
119
+ counts: collections.defaultdict[str, int] = collections.defaultdict(int)
120
+ for c, fn in self._data:
121
+ counts[map_fn(fn)] += c
122
+
123
+ return self._from_dict(counts, self.inclusive)
124
+
125
+ def filter(self, filter_fn: Callable[[str], bool]) -> "FunctionCounts":
126
+ """Keep only the elements where `filter_fn` applied to function name returns True."""
127
+ return FunctionCounts(tuple(i for i in self if filter_fn(i.function)), self.inclusive)
128
+
129
+ def sum(self) -> int:
130
+ return sum(c for c, _ in self)
131
+
132
+ def denoise(self) -> "FunctionCounts":
133
+ """Remove known noisy instructions.
134
+
135
+ Several instructions in the CPython interpreter are rather noisy. These
136
+ instructions involve unicode to dictionary lookups which Python uses to
137
+ map variable names. FunctionCounts is generally a content agnostic
138
+ container, however this is sufficiently important for obtaining
139
+ reliable results to warrant an exception."""
140
+ return self.filter(lambda fn: "dictobject.c:lookdict_unicode" not in fn)
141
+
142
+ def _merge(
143
+ self,
144
+ second: "FunctionCounts",
145
+ merge_fn: Callable[[int], int]
146
+ ) -> "FunctionCounts":
147
+ assert self.inclusive == second.inclusive, "Cannot merge inclusive and exclusive counts."
148
+ counts: collections.defaultdict[str, int] = collections.defaultdict(int)
149
+ for c, fn in self:
150
+ counts[fn] += c
151
+
152
+ for c, fn in second:
153
+ counts[fn] += merge_fn(c)
154
+
155
+ return self._from_dict(counts, self.inclusive)
156
+
157
+ @staticmethod
158
+ def _from_dict(counts: dict[str, int], inclusive: bool) -> "FunctionCounts":
159
+ flat_counts = (FunctionCount(c, fn) for fn, c in counts.items() if c)
160
+ return FunctionCounts(tuple(sorted(flat_counts, reverse=True)), inclusive)
161
+
162
+
163
+ @dataclasses.dataclass(repr=False, eq=False, frozen=True)
164
+ class CallgrindStats:
165
+ """Top level container for Callgrind results collected by Timer.
166
+
167
+ Manipulation is generally done using the FunctionCounts class, which is
168
+ obtained by calling `CallgrindStats.stats(...)`. Several convenience
169
+ methods are provided as well; the most significant is
170
+ `CallgrindStats.as_standardized()`.
171
+ """
172
+ task_spec: common.TaskSpec
173
+ number_per_run: int
174
+ built_with_debug_symbols: bool
175
+ baseline_inclusive_stats: FunctionCounts
176
+ baseline_exclusive_stats: FunctionCounts
177
+ stmt_inclusive_stats: FunctionCounts
178
+ stmt_exclusive_stats: FunctionCounts
179
+ stmt_callgrind_out: Optional[str]
180
+
181
+ def __repr__(self) -> str:
182
+ base_stats = self.baseline_exclusive_stats
183
+ output = f"""
184
+ {super().__repr__()}
185
+ {self.task_spec.summarize()}
186
+ {'':>25}All{'':>10}Noisy symbols removed
187
+ Instructions: {self.counts(denoise=False):>12}{'':>15}{self.counts(denoise=True):>12}
188
+ Baseline: {base_stats.sum():>12}{'':>15}{base_stats.denoise().sum():>12}
189
+ {self.number_per_run} runs per measurement, {self.task_spec.num_threads} thread{'s' if self.task_spec.num_threads > 1 else ''}
190
+ """.strip()
191
+ if not self.built_with_debug_symbols:
192
+ output += textwrap.dedent("""
193
+ Warning: PyTorch was not built with debug symbols.
194
+ Source information may be limited. Rebuild with
195
+ REL_WITH_DEB_INFO=1 for more detailed results.""")
196
+ return output
197
+
198
+ def stats(self, inclusive: bool = False) -> FunctionCounts:
199
+ """Returns detailed function counts.
200
+
201
+ Conceptually, the FunctionCounts returned can be thought of as a tuple
202
+ of (count, path_and_function_name) tuples.
203
+
204
+ `inclusive` matches the semantics of callgrind. If True, the counts
205
+ include instructions executed by children. `inclusive=True` is useful
206
+ for identifying hot spots in code; `inclusive=False` is useful for
207
+ reducing noise when diffing counts from two different runs. (See
208
+ CallgrindStats.delta(...) for more details)
209
+ """
210
+ return self.stmt_inclusive_stats if inclusive else self.stmt_exclusive_stats
211
+
212
+ def counts(self, *, denoise: bool = False) -> int:
213
+ """Returns the total number of instructions executed.
214
+
215
+ See `FunctionCounts.denoise()` for an explanation of the `denoise` arg.
216
+ """
217
+ stats = self.stmt_exclusive_stats
218
+ return (stats.denoise() if denoise else stats).sum()
219
+
220
+ # FIXME: Once 3.7 is the minimum version, type annotate `other` per PEP 563
221
+ def delta(
222
+ self,
223
+ other: "CallgrindStats",
224
+ inclusive: bool = False,
225
+ ) -> FunctionCounts:
226
+ """Diff two sets of counts.
227
+
228
+ One common reason to collect instruction counts is to determine the
229
+ the effect that a particular change will have on the number of instructions
230
+ needed to perform some unit of work. If a change increases that number, the
231
+ next logical question is "why". This generally involves looking at what part
232
+ if the code increased in instruction count. This function automates that
233
+ process so that one can easily diff counts on both an inclusive and
234
+ exclusive basis.
235
+ """
236
+ return self.stats(inclusive=inclusive) - other.stats(inclusive=inclusive)
237
+
238
+ def as_standardized(self) -> "CallgrindStats":
239
+ """Strip library names and some prefixes from function strings.
240
+
241
+ When comparing two different sets of instruction counts, on stumbling
242
+ block can be path prefixes. Callgrind includes the full filepath
243
+ when reporting a function (as it should). However, this can cause
244
+ issues when diffing profiles. If a key component such as Python
245
+ or PyTorch was built in separate locations in the two profiles, which
246
+ can result in something resembling::
247
+
248
+ 23234231 /tmp/first_build_dir/thing.c:foo(...)
249
+ 9823794 /tmp/first_build_dir/thing.c:bar(...)
250
+ ...
251
+ 53453 .../aten/src/Aten/...:function_that_actually_changed(...)
252
+ ...
253
+ -9823794 /tmp/second_build_dir/thing.c:bar(...)
254
+ -23234231 /tmp/second_build_dir/thing.c:foo(...)
255
+
256
+ Stripping prefixes can ameliorate this issue by regularizing the
257
+ strings and causing better cancellation of equivalent call sites
258
+ when diffing.
259
+ """
260
+ def strip(stats: FunctionCounts) -> FunctionCounts:
261
+ transforms = (
262
+ # PyTorch may have been built in different locations.
263
+ (r"^.+build/\.\./", "build/../"),
264
+ (r"^.+/" + re.escape("build/aten/"), "build/aten/"),
265
+
266
+ # "Python" and "Objects" come from CPython.
267
+ (r"^.+/" + re.escape("Python/"), "Python/"),
268
+ (r"^.+/" + re.escape("Objects/"), "Objects/"),
269
+
270
+ # Strip library name. e.g. `libtorch.so`
271
+ (r"\s\[.+\]$", ""),
272
+ )
273
+
274
+ for before, after in transforms:
275
+ stats = stats.transform(lambda fn: re.sub(before, after, fn))
276
+
277
+ return stats
278
+
279
+ return CallgrindStats(
280
+ task_spec=self.task_spec,
281
+ number_per_run=self.number_per_run,
282
+ built_with_debug_symbols=self.built_with_debug_symbols,
283
+ baseline_inclusive_stats=strip(self.baseline_inclusive_stats),
284
+ baseline_exclusive_stats=strip(self.baseline_exclusive_stats),
285
+ stmt_inclusive_stats=strip(self.stmt_inclusive_stats),
286
+ stmt_exclusive_stats=strip(self.stmt_exclusive_stats),
287
+
288
+ # `as_standardized` will change symbol names, so the contents will
289
+ # no longer map directly to `callgrind.out`
290
+ stmt_callgrind_out=None,
291
+ )
292
+
293
+
294
+ class Serialization(enum.Enum):
295
+ PICKLE = 0
296
+ TORCH = 1
297
+ TORCH_JIT = 2
298
+
299
+
300
+ _GLOBALS_ALLOWED_TYPES: dict[Serialization, tuple[Any, ...]] = {
301
+ Serialization.PICKLE: (str, bytes, bool, int, float, complex),
302
+ Serialization.TORCH_JIT: (torch.jit.ScriptFunction, torch.jit.ScriptModule),
303
+ Serialization.TORCH: (torch.nn.Module,),
304
+ }
305
+
306
+
307
+ class CopyIfCallgrind:
308
+ """Signal that a global may be replaced with a deserialized copy.
309
+
310
+ See `GlobalsBridge` for why this matters.
311
+ """
312
+ def __init__(self, value: Any, *, setup: Optional[str] = None):
313
+ for method, supported_types in _GLOBALS_ALLOWED_TYPES.items():
314
+ if any(isinstance(value, t) for t in supported_types):
315
+ self._value: Any = value
316
+ self._setup: Optional[str] = setup
317
+ self._serialization: Serialization = method
318
+ break
319
+ else:
320
+ supported_str = "\n".join([
321
+ getattr(t, "__name__", repr(t))
322
+ for t in it.chain(_GLOBALS_ALLOWED_TYPES.values())])
323
+
324
+ raise ValueError(
325
+ f"Unsupported type: {type(value)}\n"
326
+ f"`collect_callgrind` restricts globals to the following types:\n"
327
+ f"{textwrap.indent(supported_str, ' ')}"
328
+ )
329
+
330
+ @property
331
+ def value(self) -> Any:
332
+ return self._value
333
+
334
+ @property
335
+ def setup(self) -> Optional[str]:
336
+ return self._setup
337
+
338
+ @property
339
+ def serialization(self) -> Serialization:
340
+ return self._serialization
341
+
342
+ @staticmethod
343
+ def unwrap_all(globals: dict[str, Any]) -> dict[str, Any]:
344
+ return {
345
+ k: (v.value if isinstance(v, CopyIfCallgrind) else v)
346
+ for k, v in globals.items()
347
+ }
348
+
349
+
350
+ class GlobalsBridge:
351
+ """Handle the transfer of (certain) globals when collecting Callgrind statistics.
352
+
353
+ Key takeaway: Any globals passed must be wrapped in `CopyIfCallgrind` to
354
+ work with `Timer.collect_callgrind`.
355
+
356
+ Consider the following code snippet:
357
+ ```
358
+ import pickle
359
+ import timeit
360
+
361
+ class Counter:
362
+ value = 0
363
+
364
+ def __call__(self):
365
+ self.value += 1
366
+
367
+ counter = Counter()
368
+ timeit.Timer("counter()", globals={"counter": counter}).timeit(10)
369
+ print(counter.value) # 10
370
+
371
+ timeit.Timer(
372
+ "counter()",
373
+ globals={"counter": pickle.loads(pickle.dumps(counter))}
374
+ ).timeit(20)
375
+ print(counter.value) # Still 10
376
+ ```
377
+
378
+ In the first case, `stmt` is executed using the objects in `globals`;
379
+ however, the addition of serialization and deserialization changes the
380
+ semantics and may meaningfully change behavior.
381
+
382
+ This is a practical consideration when collecting Callgrind statistics.
383
+ Unlike `exec` based execution (which `timeit` uses under the hood) which
384
+ can share in-memory data structures with the caller, Callgrind collection
385
+ requires an entirely new process in order to run under Valgrind. This means
386
+ that any data structures used for statement execution will have to be
387
+ serialized and deserialized in the subprocess.
388
+
389
+ In order to avoid surprising semantics from (user invisible) process
390
+ boundaries, what can be passed through `globals` is severely restricted
391
+ for `Timer.collect_callgrind`. It is expected that most setup should be
392
+ achievable (albeit perhaps less ergonomically) by passing a `setup`
393
+ string.
394
+
395
+ There are, however, exceptions. One such class are TorchScripted functions.
396
+ Because they require a concrete file with source code it is not possible
397
+ to define them using a `setup` string. Another group are torch.nn.Modules,
398
+ whose construction can be complex and prohibitively cumbersome to coerce
399
+ into a `setup` string. Finally, most builtin types are sufficiently well
400
+ behaved and sufficiently common to warrant allowing as well. (e.g.
401
+ `globals={"n": 1}` is very convenient.)
402
+
403
+ Fortunately, all have well defined serialization semantics. This class
404
+ is responsible for enabling the Valgrind subprocess to use elements in
405
+ `globals` so long as they are an allowed type.
406
+
407
+ Caveats:
408
+ The user is required to acknowledge this serialization by wrapping
409
+ elements in `globals` with `CopyIfCallgrind`.
410
+
411
+ While ScriptFunction and ScriptModule are expected to save and load
412
+ quite robustly, it is up to the user to ensure that an nn.Module can
413
+ un-pickle successfully.
414
+
415
+ `torch.Tensor` and `np.ndarray` are deliberately excluded. The
416
+ serialization/deserialization process perturbs the representation of a
417
+ tensor in ways that could result in incorrect measurements. For example,
418
+ if a tensor lives in pinned CPU memory, this fact would not be preserved
419
+ by a dump, and that will in turn change the performance of certain CUDA
420
+ operations.
421
+ """
422
+
423
+ def __init__(self, globals: dict[str, Any], data_dir: str) -> None:
424
+ self._globals: dict[str, CopyIfCallgrind] = {}
425
+ self._data_dir = data_dir
426
+ if not os.path.exists(data_dir):
427
+ os.mkdir(data_dir)
428
+
429
+ if globals.get("torch", torch) is not torch:
430
+ raise ValueError("`collect_callgrind` does not support mocking out `torch`.")
431
+
432
+ for name, value in globals.items():
433
+ if name in ("torch", "__builtins__"):
434
+ # Torch will be imported by the collection script, and
435
+ # __builtins__ is added by Timer.
436
+ continue
437
+
438
+ if not isinstance(value, CopyIfCallgrind):
439
+ raise ValueError(
440
+ "`collect_callgrind` requires that globals be wrapped in "
441
+ "`CopyIfCallgrind` so that serialization is explicit."
442
+ )
443
+
444
+ self._globals[name] = value
445
+
446
+ def construct(self) -> str:
447
+ load_lines = []
448
+ for name, wrapped_value in self._globals.items():
449
+ if wrapped_value.setup is not None:
450
+ load_lines.append(textwrap.dedent(wrapped_value.setup))
451
+
452
+ if wrapped_value.serialization == Serialization.PICKLE:
453
+ path = os.path.join(self._data_dir, f"{name}.pkl")
454
+ load_lines.append(
455
+ f"with open({repr(path)}, 'rb') as f:\n {name} = pickle.load(f)")
456
+ with open(path, "wb") as f:
457
+ pickle.dump(wrapped_value.value, f)
458
+
459
+ elif wrapped_value.serialization == Serialization.TORCH:
460
+ path = os.path.join(self._data_dir, f"{name}.pt")
461
+ # TODO: Figure out if we can use torch.serialization.add_safe_globals here
462
+ # Using weights_only=False after the change in
463
+ # https://dev-discuss.pytorch.org/t/bc-breaking-change-torch-load-is-being-flipped-to-use-weights-only-true-by-default-in-the-nightlies-after-137602/2573
464
+ load_lines.append(f"{name} = torch.load({repr(path)}, weights_only=False)")
465
+ torch.save(wrapped_value.value, path)
466
+
467
+ elif wrapped_value.serialization == Serialization.TORCH_JIT:
468
+ path = os.path.join(self._data_dir, f"{name}.pt")
469
+ load_lines.append(f"{name} = torch.jit.load({repr(path)})")
470
+ with open(path, "wb") as f:
471
+ torch.jit.save(wrapped_value.value, f) # type: ignore[no-untyped-call]
472
+
473
+ else:
474
+ raise NotImplementedError(
475
+ f"Unknown serialization method: {wrapped_value.serialization}")
476
+
477
+ return "\n".join(load_lines)
478
+
479
+
480
+ class _ValgrindWrapper:
481
+ def __init__(self) -> None:
482
+ self._bindings_module: Optional[CallgrindModuleType] = None
483
+ valgrind_symbols = (
484
+ "_valgrind_supported_platform",
485
+ "_valgrind_toggle",
486
+ "_valgrind_toggle_and_dump_stats",
487
+ )
488
+ if all(hasattr(torch._C, symbol) for symbol in valgrind_symbols):
489
+ self._supported_platform: bool = torch._C._valgrind_supported_platform()
490
+
491
+ else:
492
+ print("Callgrind bindings are not present in `torch._C`. JIT-ing bindings.")
493
+ self._bindings_module = cpp_jit.get_compat_bindings()
494
+ assert all(hasattr(self._bindings_module, symbol) for symbol in valgrind_symbols)
495
+ self._supported_platform = self._bindings_module._valgrind_supported_platform()
496
+
497
+ self._commands_available: dict[str, bool] = {}
498
+ if self._supported_platform:
499
+ # Only bother checking on supported platforms.
500
+ for cmd in ("valgrind", "callgrind_control", "callgrind_annotate"):
501
+ self._commands_available[cmd] = not subprocess.run(
502
+ ["which", cmd],
503
+ capture_output=True,
504
+ check=False,
505
+ ).returncode
506
+
507
+ self._build_type: Optional[str] = None
508
+ build_search = re.search("BUILD_TYPE=(.+),", torch.__config__.show()) # type: ignore[no-untyped-call]
509
+ if build_search is not None:
510
+ self._build_type = build_search.groups()[0].split(",")[0]
511
+
512
+ def _validate(self) -> None:
513
+ if not self._supported_platform:
514
+ raise OSError("Valgrind is not supported on this platform.")
515
+
516
+ missing_cmds = [cmd for cmd, available in self._commands_available.items() if not available]
517
+ if missing_cmds:
518
+ raise OSError("Missing: " + ", ".join(missing_cmds))
519
+
520
+ def collect_callgrind(
521
+ self,
522
+ task_spec: common.TaskSpec,
523
+ globals: dict[str, Any],
524
+ *,
525
+ number: int,
526
+ repeats: int,
527
+ collect_baseline: bool,
528
+ is_python: bool,
529
+ retain_out_file: bool,
530
+ ) -> tuple[CallgrindStats, ...]:
531
+ """Collect stats, and attach a reference run which can be used to filter interpreter overhead."""
532
+ self._validate()
533
+ assert is_python or not collect_baseline
534
+
535
+ *task_stats, baseline_stats = self._invoke(
536
+ task_spec=task_spec,
537
+ globals=globals,
538
+ number=number,
539
+ repeats=repeats,
540
+ collect_baseline=collect_baseline,
541
+ is_python=is_python,
542
+ retain_out_file=retain_out_file,
543
+ )
544
+ assert len(task_stats) == repeats
545
+
546
+ return tuple(
547
+ CallgrindStats(
548
+ task_spec=task_spec,
549
+ number_per_run=number,
550
+ built_with_debug_symbols=self._build_type == "RelWithDebInfo",
551
+ baseline_inclusive_stats=baseline_stats[0],
552
+ baseline_exclusive_stats=baseline_stats[1],
553
+ stmt_inclusive_stats=stmt_inclusive_stats,
554
+ stmt_exclusive_stats=stmt_exclusive_stats,
555
+ stmt_callgrind_out=out_contents,
556
+ )
557
+ for stmt_inclusive_stats, stmt_exclusive_stats, out_contents in task_stats
558
+ )
559
+
560
+ def _invoke(
561
+ self,
562
+ *,
563
+ task_spec: common.TaskSpec,
564
+ globals: dict[str, Any],
565
+ number: int,
566
+ repeats: int,
567
+ collect_baseline: bool,
568
+ is_python: bool,
569
+ retain_out_file: bool,
570
+ ) -> tuple[tuple[FunctionCounts, FunctionCounts, Optional[str]], ...]:
571
+ """Core invocation method for Callgrind collection.
572
+
573
+ Valgrind operates by effectively replacing the CPU with an emulated
574
+ version which allows it to instrument any code at the cost of severe
575
+ performance degradation. This has the practical effect that in order
576
+ to collect Callgrind statistics, a new process has to be created
577
+ running under `valgrind`. The steps for this process are:
578
+
579
+ 1) Create a scratch directory.
580
+ 2) Codegen a run script. (_ValgrindWrapper._construct_script)
581
+ Inside the run script:
582
+ * Validate that Python and torch match the parent process
583
+ * Validate that it is indeed running under valgrind
584
+ * Execute `setup` and warm up `stmt`
585
+ * Begin collecting stats
586
+ * Run the `stmt` loop
587
+ * Stop collecting stats
588
+ 3) Parse the run results.
589
+ 4) Cleanup the scratch directory.
590
+ """
591
+ working_dir = common._make_temp_dir(prefix="callgrind")
592
+ data_dir = os.path.join(working_dir, "data")
593
+ script_file = os.path.join(working_dir, "timer_callgrind.py")
594
+ callgrind_out = os.path.join(working_dir, "callgrind.out")
595
+ error_log = os.path.join(working_dir, "error.txt")
596
+ stat_log = os.path.join(working_dir, "callgrind_stat.txt")
597
+ stdout_stderr_log = os.path.join(working_dir, "stdout_stderr.log")
598
+
599
+ def run(args: list[str], **kwargs: Any) -> tuple[CompletedProcessType, str]:
600
+ # https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
601
+ f_stdout_stderr = open(stdout_stderr_log, "wb")
602
+ try:
603
+ invocation = subprocess.run(
604
+ args,
605
+ stdout=f_stdout_stderr,
606
+ stderr=subprocess.STDOUT,
607
+ **kwargs,
608
+ )
609
+ with open(stdout_stderr_log) as f:
610
+ return invocation, f.read()
611
+ finally:
612
+ f_stdout_stderr.close()
613
+
614
+ try:
615
+ if is_python:
616
+ if self._bindings_module is not None:
617
+ shutil.copy(
618
+ self._bindings_module.__file__,
619
+ os.path.join(working_dir, os.path.split(self._bindings_module.__file__)[1])
620
+ )
621
+
622
+ script_file = os.path.join(working_dir, "timer_callgrind.py")
623
+ with open(script_file, "w") as f:
624
+ f.write(self._construct_script(
625
+ task_spec,
626
+ globals=GlobalsBridge(globals, data_dir),
627
+ number=number,
628
+ repeats=repeats,
629
+ collect_baseline=collect_baseline,
630
+ error_log=error_log,
631
+ stat_log=stat_log,
632
+ bindings=self._bindings_module))
633
+
634
+ run_loop_cmd = ["python", script_file]
635
+ else:
636
+ assert not collect_baseline
637
+ run_loop_exec = cpp_jit.compile_callgrind_template(
638
+ stmt=task_spec.stmt,
639
+ setup=task_spec.setup,
640
+ global_setup=task_spec.global_setup,
641
+ )
642
+ run_loop_cmd = [
643
+ run_loop_exec,
644
+ "--number", str(number),
645
+ "--number-warmup", str(min(number, 10)),
646
+ "--repeats", str(repeats),
647
+ "--number-threads", str(task_spec.num_threads),
648
+ ]
649
+
650
+ valgrind_invocation, valgrind_invocation_output = run([
651
+ "valgrind",
652
+ "--tool=callgrind",
653
+ f"--callgrind-out-file={callgrind_out}",
654
+ "--dump-line=yes",
655
+ "--dump-instr=yes",
656
+ "--instr-atstart=yes",
657
+ "--collect-atstart=no",
658
+ ] + run_loop_cmd)
659
+
660
+ if valgrind_invocation.returncode:
661
+ error_report = ""
662
+ if os.path.exists(error_log):
663
+ with open(error_log) as f:
664
+ error_report = f.read()
665
+ if not error_report:
666
+ error_report = "Unknown error.\n" + valgrind_invocation_output
667
+
668
+ raise OSError(f"Failed to collect callgrind profile:\n{error_report}")
669
+
670
+ def parse_output(fpath: str, inclusive: bool) -> FunctionCounts:
671
+ _annotate_invocation, annotate_invocation_output = run([
672
+ "callgrind_annotate",
673
+ f"--inclusive={'yes' if inclusive else 'no'}",
674
+ "--threshold=100",
675
+ "--show-percs=no",
676
+ fpath
677
+ ], check=True)
678
+
679
+ total_pattern = re.compile(r"^([0-9,]+)\s+PROGRAM TOTALS")
680
+ begin_pattern = re.compile(r"Ir\s+file:function")
681
+ function_pattern = re.compile(r"^\s*([0-9,]+)\s+(.+:.+)$")
682
+
683
+ class ScanState(enum.Enum):
684
+ SCANNING_FOR_TOTAL = 0
685
+ SCANNING_FOR_START = 1
686
+ PARSING = 2
687
+
688
+ scan_state = ScanState.SCANNING_FOR_TOTAL
689
+ fn_counts = []
690
+ for l in annotate_invocation_output.splitlines(keepends=False):
691
+ if scan_state == ScanState.SCANNING_FOR_TOTAL:
692
+ total_match = total_pattern.match(l)
693
+ if total_match:
694
+ program_totals = int(total_match.groups()[0].replace(",", ""))
695
+ scan_state = ScanState.SCANNING_FOR_START
696
+
697
+ elif scan_state == ScanState.SCANNING_FOR_START:
698
+ if begin_pattern.match(l):
699
+ scan_state = ScanState.PARSING
700
+
701
+ else:
702
+ assert scan_state == ScanState.PARSING
703
+ fn_match = function_pattern.match(l)
704
+ if fn_match:
705
+ ir_str, file_function = fn_match.groups()
706
+ ir = int(ir_str.replace(",", ""))
707
+ if ir == program_totals: # type: ignore[possibly-undefined]
708
+ # Callgrind includes some top level red herring symbols when
709
+ # a program dumps multiple profiles.
710
+ continue
711
+ fn_counts.append(FunctionCount(ir, file_function))
712
+
713
+ elif re.match(r"-+", l):
714
+ # Ignore heading separator lines.
715
+ continue
716
+
717
+ else:
718
+ break
719
+
720
+ assert scan_state == ScanState.PARSING, f"Failed to parse {fpath}"
721
+ return FunctionCounts(tuple(sorted(fn_counts, reverse=True)), inclusive=inclusive)
722
+
723
+ def read_results(i: int) -> tuple[FunctionCounts, FunctionCounts, Optional[str]]:
724
+ if i == repeats and not collect_baseline:
725
+ # Null baseline.
726
+ return (
727
+ FunctionCounts((), inclusive=True),
728
+ FunctionCounts((), inclusive=False),
729
+ None,
730
+ )
731
+
732
+ fpath = f"{callgrind_out}.{i + 1}" # Callgrind one-indexes files.
733
+ callgrind_out_contents: Optional[str] = None
734
+ if retain_out_file:
735
+ with open(fpath) as f:
736
+ callgrind_out_contents = f.read()
737
+
738
+ return (
739
+ parse_output(fpath, inclusive=True),
740
+ parse_output(fpath, inclusive=False),
741
+ callgrind_out_contents
742
+ )
743
+
744
+ return tuple(read_results(i) for i in range(repeats + 1))
745
+ finally:
746
+ shutil.rmtree(working_dir)
747
+
748
+ @staticmethod
749
+ def _construct_script(
750
+ task_spec: common.TaskSpec,
751
+ globals: GlobalsBridge,
752
+ *,
753
+ number: int,
754
+ repeats: int,
755
+ collect_baseline: bool,
756
+ error_log: str,
757
+ stat_log: str,
758
+ bindings: Optional[CallgrindModuleType],
759
+ ) -> str:
760
+ def block_stmt(stmt: str, indent: int = 0) -> str:
761
+ """Partially unroll benchmark loop.
762
+
763
+ The naive template looks something like:
764
+ "for _ in range({number}): {stmt}"
765
+
766
+ However a loop in Python is surprisingly expensive, and significantly
767
+ increases the number of background Python instructions. So instead we
768
+ partially unroll the loops, with a block size of 100 chosen to keep
769
+ the instruction overhead from `range` low while also not ballooning
770
+ the size of the generated file.
771
+ """
772
+ block_size = 100
773
+ loop_count = number // block_size
774
+ if loop_count == 1:
775
+ # There is no point in having `for _ in range(1): ...` rather
776
+ # than just `...`, and this lets us save shave a few background
777
+ # instructions.
778
+ loop_count = 0
779
+ remainder = number - block_size * loop_count
780
+ blocked_stmt = ""
781
+
782
+ if loop_count:
783
+ unrolled_stmts = textwrap.indent("\n".join([stmt] * block_size), " " * 4)
784
+ blocked_stmt += f"for _ in range({loop_count}):\n{unrolled_stmts}\n"
785
+
786
+ if remainder:
787
+ blocked_stmt += "\n".join([stmt] * remainder)
788
+
789
+ return textwrap.indent(blocked_stmt, " " * indent)
790
+
791
+ pass_baseline = (
792
+ "callgrind_bindings._valgrind_toggle()\n"
793
+ f"{block_stmt('pass')}\n"
794
+ "callgrind_bindings._valgrind_toggle_and_dump_stats()"
795
+ )
796
+
797
+ return textwrap.dedent(r"""
798
+ import gc
799
+ import os
800
+ import pickle
801
+ import subprocess
802
+ import sys
803
+ import time
804
+
805
+ # Mitigate https://github.com/pytorch/pytorch/issues/37377
806
+ # which can sometimes cause the subprocess call to fail.
807
+ import numpy as np
808
+
809
+ import torch
810
+ torch.set_num_threads({num_threads})
811
+
812
+ {bindings_import}
813
+
814
+ PID = os.getpid()
815
+
816
+ def log_failure(msg):
817
+ with open({error_log_repr}, "wt") as f:
818
+ f.write(msg)
819
+ sys.exit(1)
820
+
821
+ def check_result(completed_process):
822
+ if completed_process.returncode:
823
+ log_failure(f"Command failed: {{' '.join(completed_process.args)}}")
824
+ return completed_process
825
+
826
+ # =============================================================================
827
+ # == Check that subprocess matches parent =====================================
828
+ # =============================================================================
829
+ if os.path.realpath(sys.executable) != "{parent_interpreter}":
830
+ log_failure(
831
+ "Interpreter mismatch:\n"
832
+ f" {{os.path.realpath(sys.executable)}}\n vs.\n {parent_interpreter}"
833
+ )
834
+
835
+ if torch.__file__ != "{torch_file}":
836
+ log_failure(
837
+ "PyTorch does not match expected file:\n"
838
+ f" {{torch.__file__}}\n vs.\n {torch_file}"
839
+ )
840
+
841
+ # =============================================================================
842
+ # == User specified setup =====================================================
843
+ # =============================================================================
844
+ # Load serialized globals
845
+ {load_globals}
846
+
847
+ # User setup str
848
+ {setup}
849
+
850
+ for _ in range({warmup_number}):
851
+ {indented_stmt}
852
+
853
+ # =============================================================================
854
+ # == Callgrind management =====================================================
855
+ # =============================================================================
856
+ with open("{stat_log}", "wb") as stat_file:
857
+ # If many instances of callgrind are running at once, the output of
858
+ # `callgrind_control` may exceed 16kb which would cause `subprocess.PIPE`
859
+ # to deadlock. So instead we use a file.
860
+ callgrind_stat = check_result(subprocess.run(
861
+ ["callgrind_control", "--stat"],
862
+ stdout=stat_file,
863
+ stderr=subprocess.STDOUT,
864
+ ))
865
+
866
+ with open("{stat_log}", "rt") as stat_file:
867
+ stat_lines = stat_file.read().splitlines()
868
+
869
+ if f"PID {{PID}}: python {{__file__}}" not in stat_lines:
870
+ log_failure("Process does not appear to be running callgrind.")
871
+
872
+ gc.collect()
873
+ time.sleep(0.01)
874
+
875
+ # =============================================================================
876
+ # == User code block ==========================================================
877
+ # =============================================================================
878
+ for _ in range({repeats}):
879
+ callgrind_bindings._valgrind_toggle()
880
+ {blocked_stmt}
881
+ callgrind_bindings._valgrind_toggle_and_dump_stats()
882
+ gc.collect()
883
+
884
+ {baseline}
885
+ """).strip().format(
886
+ indented_stmt=textwrap.indent(task_spec.stmt, " " * 4),
887
+ blocked_stmt=block_stmt(task_spec.stmt, indent=4),
888
+ baseline=(pass_baseline if collect_baseline else ""),
889
+ number=number,
890
+ repeats=repeats,
891
+ load_globals=globals.construct(),
892
+ setup=task_spec.setup,
893
+ warmup_number=min(number, 10),
894
+ num_threads=task_spec.num_threads,
895
+ error_log_repr=repr(error_log),
896
+ stat_log=stat_log,
897
+ parent_interpreter=os.path.realpath(sys.executable),
898
+ torch_file=torch.__file__,
899
+ bindings_import=(
900
+ "import torch._C as callgrind_bindings" if bindings is None
901
+ else f"import {bindings.__name__} as callgrind_bindings"),
902
+ )
903
+
904
+
905
+ CALLGRIND_SINGLETON: Optional[_ValgrindWrapper] = None
906
+ def wrapper_singleton() -> _ValgrindWrapper:
907
+ global CALLGRIND_SINGLETON
908
+ if CALLGRIND_SINGLETON is None:
909
+ CALLGRIND_SINGLETON = _ValgrindWrapper()
910
+ return CALLGRIND_SINGLETON
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h ADDED
The diff for this file is too large to render. See raw diff
 
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/bottleneck/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/bottleneck/__main__.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import argparse
3
+ import cProfile
4
+ import pstats
5
+ import sys
6
+ import os
7
+
8
+ import torch
9
+ from torch.autograd import profiler
10
+ from torch.utils.collect_env import get_env_info
11
+
12
+
13
+ def redirect_argv(new_argv):
14
+ sys.argv[:] = new_argv[:]
15
+
16
+
17
+ def compiled_with_cuda(sysinfo):
18
+ if sysinfo.cuda_compiled_version:
19
+ return f'compiled w/ CUDA {sysinfo.cuda_compiled_version}'
20
+ return 'not compiled w/ CUDA'
21
+
22
+
23
+ env_summary = """
24
+ --------------------------------------------------------------------------------
25
+ Environment Summary
26
+ --------------------------------------------------------------------------------
27
+ PyTorch {pytorch_version}{debug_str} {cuda_compiled}
28
+ Running with Python {py_version} and {cuda_runtime}
29
+
30
+ `{pip_version} list` truncated output:
31
+ {pip_list_output}
32
+ """.strip()
33
+
34
+
35
+ def run_env_analysis():
36
+ print('Running environment analysis...')
37
+ info = get_env_info()
38
+
39
+ result: dict[str, str] = {}
40
+
41
+ debug_str = ''
42
+ if info.is_debug_build:
43
+ debug_str = ' DEBUG'
44
+
45
+ cuda_avail = ''
46
+ if info.is_cuda_available:
47
+ cuda = info.cuda_runtime_version
48
+ if cuda is not None:
49
+ cuda_avail = 'CUDA ' + cuda
50
+ else:
51
+ cuda = 'CUDA unavailable'
52
+
53
+ pip_version = info.pip_version
54
+ pip_list_output = info.pip_packages
55
+ if pip_list_output is None:
56
+ pip_list_output = 'Unable to fetch'
57
+
58
+ result = {
59
+ 'debug_str': debug_str,
60
+ 'pytorch_version': info.torch_version,
61
+ 'cuda_compiled': compiled_with_cuda(info),
62
+ 'py_version': f'{sys.version_info[0]}.{sys.version_info[1]}',
63
+ 'cuda_runtime': cuda_avail,
64
+ 'pip_version': pip_version,
65
+ 'pip_list_output': pip_list_output,
66
+ }
67
+
68
+ return env_summary.format(**result)
69
+
70
+
71
+ def run_cprofile(code, globs, launch_blocking=False):
72
+ print('Running your script with cProfile')
73
+ prof = cProfile.Profile()
74
+ prof.enable()
75
+ exec(code, globs, None)
76
+ prof.disable()
77
+ return prof
78
+
79
+
80
+ cprof_summary = """
81
+ --------------------------------------------------------------------------------
82
+ cProfile output
83
+ --------------------------------------------------------------------------------
84
+ """.strip()
85
+
86
+
87
+ def print_cprofile_summary(prof, sortby='tottime', topk=15):
88
+ print(cprof_summary)
89
+ cprofile_stats = pstats.Stats(prof).sort_stats(sortby)
90
+ cprofile_stats.print_stats(topk)
91
+
92
+
93
+ def run_autograd_prof(code, globs):
94
+ def run_prof(use_cuda=False):
95
+ with profiler.profile(use_cuda=use_cuda) as prof:
96
+ exec(code, globs, None)
97
+ return prof
98
+
99
+ print('Running your script with the autograd profiler...')
100
+ result = [run_prof(use_cuda=False)]
101
+ if torch.cuda.is_available():
102
+ result.append(run_prof(use_cuda=True))
103
+ else:
104
+ result.append(None)
105
+
106
+ return result
107
+
108
+
109
+ autograd_prof_summary = """
110
+ --------------------------------------------------------------------------------
111
+ autograd profiler output ({mode} mode)
112
+ --------------------------------------------------------------------------------
113
+ {description}
114
+ {cuda_warning}
115
+ {output}
116
+ """.strip()
117
+
118
+
119
+ def print_autograd_prof_summary(prof, mode, sortby='cpu_time', topk=15):
120
+ valid_sortby = ['cpu_time', 'cuda_time', 'cpu_time_total', 'cuda_time_total', 'count']
121
+ if sortby not in valid_sortby:
122
+ warn = ('WARNING: invalid sorting option for autograd profiler results: {}\n'
123
+ 'Expected `cpu_time`, `cpu_time_total`, or `count`. '
124
+ 'Defaulting to `cpu_time`.')
125
+ print(warn.format(sortby))
126
+ sortby = 'cpu_time'
127
+
128
+ if mode == 'CUDA':
129
+ cuda_warning = ('\n\tBecause the autograd profiler uses the CUDA event API,\n'
130
+ '\tthe CUDA time column reports approximately max(cuda_time, cpu_time).\n'
131
+ '\tPlease ignore this output if your code does not use CUDA.\n')
132
+ else:
133
+ cuda_warning = ''
134
+
135
+ sorted_events = sorted(prof.function_events,
136
+ key=lambda x: getattr(x, sortby), reverse=True)
137
+ topk_events = sorted_events[:topk]
138
+
139
+ result = {
140
+ 'mode': mode,
141
+ 'description': f'top {topk} events sorted by {sortby}',
142
+ 'output': torch.autograd.profiler_util._build_table(topk_events),
143
+ 'cuda_warning': cuda_warning
144
+ }
145
+
146
+ print(autograd_prof_summary.format(**result))
147
+
148
+
149
+ descript = """
150
+ `bottleneck` is a tool that can be used as an initial step for debugging
151
+ bottlenecks in your program.
152
+
153
+ It summarizes runs of your script with the Python profiler and PyTorch\'s
154
+ autograd profiler. Because your script will be profiled, please ensure that it
155
+ exits in a finite amount of time.
156
+
157
+ For more complicated uses of the profilers, please see
158
+ https://docs.python.org/3/library/profile.html and
159
+ https://pytorch.org/docs/main/autograd.html#profiler for more information.
160
+ """.strip()
161
+
162
+
163
+ def parse_args():
164
+ parser = argparse.ArgumentParser(description=descript)
165
+ parser.add_argument('scriptfile', type=str,
166
+ help='Path to the script to be run. '
167
+ 'Usually run with `python path/to/script`.')
168
+ parser.add_argument('args', type=str, nargs=argparse.REMAINDER,
169
+ help='Command-line arguments to be passed to the script.')
170
+ return parser.parse_args()
171
+
172
+
173
+ def cpu_time_total(autograd_prof):
174
+ return sum(event.cpu_time_total for event in autograd_prof.function_events)
175
+
176
+
177
+ def main():
178
+ args = parse_args()
179
+
180
+ # Customizable constants.
181
+ scriptfile = args.scriptfile
182
+ scriptargs = [] if args.args is None else args.args
183
+ scriptargs.insert(0, scriptfile)
184
+ cprofile_sortby = 'tottime'
185
+ cprofile_topk = 15
186
+ autograd_prof_sortby = 'cpu_time_total'
187
+ autograd_prof_topk = 15
188
+
189
+ redirect_argv(scriptargs)
190
+
191
+ sys.path.insert(0, os.path.dirname(scriptfile))
192
+ with open(scriptfile, 'rb') as stream:
193
+ code = compile(stream.read(), scriptfile, 'exec')
194
+ globs = {
195
+ '__file__': scriptfile,
196
+ '__name__': '__main__',
197
+ '__package__': None,
198
+ '__cached__': None,
199
+ }
200
+
201
+ print(descript)
202
+
203
+ env_summary = run_env_analysis()
204
+
205
+ if torch.cuda.is_available():
206
+ torch.cuda.init()
207
+ cprofile_prof = run_cprofile(code, globs)
208
+ autograd_prof_cpu, autograd_prof_cuda = run_autograd_prof(code, globs)
209
+
210
+ print(env_summary)
211
+ print_cprofile_summary(cprofile_prof, cprofile_sortby, cprofile_topk)
212
+
213
+ if not torch.cuda.is_available():
214
+ print_autograd_prof_summary(autograd_prof_cpu, 'CPU', autograd_prof_sortby, autograd_prof_topk)
215
+ return
216
+
217
+ # Print both the result of the CPU-mode and CUDA-mode autograd profilers
218
+ # if their execution times are very different.
219
+ cuda_prof_exec_time = cpu_time_total(autograd_prof_cuda)
220
+ if len(autograd_prof_cpu.function_events) > 0:
221
+ cpu_prof_exec_time = cpu_time_total(autograd_prof_cpu)
222
+ pct_diff = (cuda_prof_exec_time - cpu_prof_exec_time) / cuda_prof_exec_time
223
+ if abs(pct_diff) > 0.05:
224
+ print_autograd_prof_summary(autograd_prof_cpu, 'CPU', autograd_prof_sortby, autograd_prof_topk)
225
+
226
+ print_autograd_prof_summary(autograd_prof_cuda, 'CUDA', autograd_prof_sortby, autograd_prof_topk)
227
+
228
+ if __name__ == '__main__':
229
+ main()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/__init__.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data.dataloader import (
2
+ _DatasetKind,
3
+ DataLoader,
4
+ default_collate,
5
+ default_convert,
6
+ get_worker_info,
7
+ )
8
+ from torch.utils.data.datapipes._decorator import (
9
+ argument_validation,
10
+ functional_datapipe,
11
+ guaranteed_datapipes_determinism,
12
+ non_deterministic,
13
+ runtime_validation,
14
+ runtime_validation_disabled,
15
+ )
16
+ from torch.utils.data.datapipes.datapipe import (
17
+ DataChunk,
18
+ DFIterDataPipe,
19
+ IterDataPipe,
20
+ MapDataPipe,
21
+ )
22
+ from torch.utils.data.dataset import (
23
+ ChainDataset,
24
+ ConcatDataset,
25
+ Dataset,
26
+ IterableDataset,
27
+ random_split,
28
+ StackDataset,
29
+ Subset,
30
+ TensorDataset,
31
+ )
32
+ from torch.utils.data.distributed import DistributedSampler
33
+ from torch.utils.data.sampler import (
34
+ BatchSampler,
35
+ RandomSampler,
36
+ Sampler,
37
+ SequentialSampler,
38
+ SubsetRandomSampler,
39
+ WeightedRandomSampler,
40
+ )
41
+
42
+
43
+ __all__ = [
44
+ "BatchSampler",
45
+ "ChainDataset",
46
+ "ConcatDataset",
47
+ "DFIterDataPipe",
48
+ "DataChunk",
49
+ "DataLoader",
50
+ "Dataset",
51
+ "DistributedSampler",
52
+ "IterDataPipe",
53
+ "IterableDataset",
54
+ "MapDataPipe",
55
+ "RandomSampler",
56
+ "Sampler",
57
+ "SequentialSampler",
58
+ "StackDataset",
59
+ "Subset",
60
+ "SubsetRandomSampler",
61
+ "TensorDataset",
62
+ "WeightedRandomSampler",
63
+ "_DatasetKind",
64
+ "argument_validation",
65
+ "default_collate",
66
+ "default_convert",
67
+ "functional_datapipe",
68
+ "get_worker_info",
69
+ "guaranteed_datapipes_determinism",
70
+ "non_deterministic",
71
+ "random_split",
72
+ "runtime_validation",
73
+ "runtime_validation_disabled",
74
+ ]
75
+
76
+ # Please keep this list sorted
77
+ assert __all__ == sorted(__all__)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""Utility classes & functions for data loading. Code in this folder is mostly used by ../dataloder.py.
3
+
4
+ A lot of multiprocessing is used in data loading, which only supports running
5
+ functions defined in global environment (py2 can't serialize static methods).
6
+ Therefore, for code tidiness we put these functions into different files in this
7
+ folder.
8
+ """
9
+
10
+ import atexit
11
+ import sys
12
+
13
+ # old private location of the ExceptionWrapper that some users rely on:
14
+ from torch._utils import ExceptionWrapper
15
+
16
+
17
+ IS_WINDOWS = sys.platform == "win32"
18
+
19
+
20
+ MP_STATUS_CHECK_INTERVAL = 5.0
21
+ r"""Interval (in seconds) to check status of processes to avoid hanging in
22
+ multiprocessing data loading. This is mainly used in getting data from
23
+ another process, in which case we need to periodically check whether the
24
+ sender is alive to prevent hanging."""
25
+
26
+
27
+ python_exit_status = False
28
+ r"""Whether Python is shutting down. This flag is guaranteed to be set before
29
+ the Python core library resources are freed, but Python may already be exiting
30
+ for some time when this is set.
31
+
32
+ Hook to set this flag is `_set_python_exit_flag`, and is inspired by a similar
33
+ hook in Python 3.7 multiprocessing library:
34
+ https://github.com/python/cpython/blob/d4d60134b29290049e28df54f23493de4f1824b6/Lib/multiprocessing/util.py#L277-L327
35
+ """
36
+
37
+
38
+ try:
39
+ import numpy
40
+
41
+ HAS_NUMPY = True
42
+ except ModuleNotFoundError:
43
+ HAS_NUMPY = False
44
+
45
+
46
+ def _set_python_exit_flag():
47
+ global python_exit_status
48
+ python_exit_status = True
49
+
50
+
51
+ atexit.register(_set_python_exit_flag)
52
+
53
+
54
+ from . import collate, fetch, pin_memory, signal_handling, worker
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/collate.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""Contains definitions of the methods used by the _BaseDataLoaderIter workers.
3
+
4
+ These methods are used to collate samples fetched from dataset into Tensor(s).
5
+ These **needs** to be in global scope since Py2 doesn't support serializing
6
+ static methods.
7
+
8
+ `default_collate` and `default_convert` are exposed to users via 'dataloader.py'.
9
+ """
10
+
11
+ import collections
12
+ import contextlib
13
+ import copy
14
+ import re
15
+ from typing import Callable, Optional, Union
16
+
17
+ import torch
18
+
19
+
20
+ np_str_obj_array_pattern = re.compile(r"[SaUO]")
21
+
22
+
23
+ def default_convert(data):
24
+ r"""
25
+ Convert each NumPy array element into a :class:`torch.Tensor`.
26
+
27
+ If the input is a `Sequence`, `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`.
28
+ If the input is not an NumPy array, it is left unchanged.
29
+ This is used as the default function for collation when both `batch_sampler` and `batch_size`
30
+ are NOT defined in :class:`~torch.utils.data.DataLoader`.
31
+
32
+ The general input type to output type mapping is similar to that
33
+ of :func:`~torch.utils.data.default_collate`. See the description there for more details.
34
+
35
+ Args:
36
+ data: a single data point to be converted
37
+
38
+ Examples:
39
+ >>> # xdoctest: +SKIP
40
+ >>> # Example with `int`
41
+ >>> default_convert(0)
42
+ 0
43
+ >>> # Example with NumPy array
44
+ >>> default_convert(np.array([0, 1]))
45
+ tensor([0, 1])
46
+ >>> # Example with NamedTuple
47
+ >>> Point = namedtuple('Point', ['x', 'y'])
48
+ >>> default_convert(Point(0, 0))
49
+ Point(x=0, y=0)
50
+ >>> default_convert(Point(np.array(0), np.array(0)))
51
+ Point(x=tensor(0), y=tensor(0))
52
+ >>> # Example with List
53
+ >>> default_convert([np.array([0, 1]), np.array([2, 3])])
54
+ [tensor([0, 1]), tensor([2, 3])]
55
+ """
56
+ elem_type = type(data)
57
+ if isinstance(data, torch.Tensor):
58
+ return data
59
+ elif (
60
+ elem_type.__module__ == "numpy"
61
+ and elem_type.__name__ != "str_"
62
+ and elem_type.__name__ != "string_"
63
+ ):
64
+ # array of string classes and object
65
+ if (
66
+ elem_type.__name__ == "ndarray"
67
+ and np_str_obj_array_pattern.search(data.dtype.str) is not None
68
+ ):
69
+ return data
70
+ return torch.as_tensor(data)
71
+ elif isinstance(data, collections.abc.Mapping):
72
+ try:
73
+ if isinstance(data, collections.abc.MutableMapping):
74
+ # The mapping type may have extra properties, so we can't just
75
+ # use `type(data)(...)` to create the new mapping.
76
+ # Create a clone and update it if the mapping type is mutable.
77
+ clone = copy.copy(data)
78
+ clone.update({key: default_convert(data[key]) for key in data})
79
+ return clone
80
+ else:
81
+ return elem_type({key: default_convert(data[key]) for key in data})
82
+ except TypeError:
83
+ # The mapping type may not support `copy()` / `update(mapping)`
84
+ # or `__init__(iterable)`.
85
+ return {key: default_convert(data[key]) for key in data}
86
+ elif isinstance(data, tuple) and hasattr(data, "_fields"): # namedtuple
87
+ return elem_type(*(default_convert(d) for d in data))
88
+ elif isinstance(data, tuple):
89
+ return [default_convert(d) for d in data] # Backwards compatibility.
90
+ elif isinstance(data, collections.abc.Sequence) and not isinstance(
91
+ data, (str, bytes)
92
+ ):
93
+ try:
94
+ if isinstance(data, collections.abc.MutableSequence):
95
+ # The sequence type may have extra properties, so we can't just
96
+ # use `type(data)(...)` to create the new sequence.
97
+ # Create a clone and update it if the sequence type is mutable.
98
+ clone = copy.copy(data) # type: ignore[arg-type]
99
+ for i, d in enumerate(data):
100
+ clone[i] = default_convert(d)
101
+ return clone
102
+ else:
103
+ return elem_type([default_convert(d) for d in data])
104
+ except TypeError:
105
+ # The sequence type may not support `copy()` / `__setitem__(index, item)`
106
+ # or `__init__(iterable)` (e.g., `range`).
107
+ return [default_convert(d) for d in data]
108
+ else:
109
+ return data
110
+
111
+
112
+ default_collate_err_msg_format = (
113
+ "default_collate: batch must contain tensors, numpy arrays, numbers, "
114
+ "dicts or lists; found {}"
115
+ )
116
+
117
+
118
+ def collate(
119
+ batch,
120
+ *,
121
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
122
+ ):
123
+ r"""
124
+ General collate function that handles collection type of element within each batch.
125
+
126
+ The function also opens function registry to deal with specific element types. `default_collate_fn_map`
127
+ provides default collate functions for tensors, numpy arrays, numbers and strings.
128
+
129
+ Args:
130
+ batch: a single batch to be collated
131
+ collate_fn_map: Optional dictionary mapping from element type to the corresponding collate function.
132
+ If the element type isn't present in this dictionary,
133
+ this function will go through each key of the dictionary in the insertion order to
134
+ invoke the corresponding collate function if the element type is a subclass of the key.
135
+
136
+ Examples:
137
+ >>> def collate_tensor_fn(batch, *, collate_fn_map):
138
+ ... # Extend this function to handle batch of tensors
139
+ ... return torch.stack(batch, 0)
140
+ >>> def custom_collate(batch):
141
+ ... collate_map = {torch.Tensor: collate_tensor_fn}
142
+ ... return collate(batch, collate_fn_map=collate_map)
143
+ >>> # Extend `default_collate` by in-place modifying `default_collate_fn_map`
144
+ >>> default_collate_fn_map.update({torch.Tensor: collate_tensor_fn})
145
+
146
+ Note:
147
+ Each collate function requires a positional argument for batch and a keyword argument
148
+ for the dictionary of collate functions as `collate_fn_map`.
149
+ """
150
+ elem = batch[0]
151
+ elem_type = type(elem)
152
+
153
+ if collate_fn_map is not None:
154
+ if elem_type in collate_fn_map:
155
+ return collate_fn_map[elem_type](batch, collate_fn_map=collate_fn_map)
156
+
157
+ for collate_type in collate_fn_map:
158
+ if isinstance(elem, collate_type):
159
+ return collate_fn_map[collate_type](
160
+ batch, collate_fn_map=collate_fn_map
161
+ )
162
+
163
+ if isinstance(elem, collections.abc.Mapping):
164
+ try:
165
+ if isinstance(elem, collections.abc.MutableMapping):
166
+ # The mapping type may have extra properties, so we can't just
167
+ # use `type(data)(...)` to create the new mapping.
168
+ # Create a clone and update it if the mapping type is mutable.
169
+ clone = copy.copy(elem)
170
+ clone.update(
171
+ {
172
+ key: collate(
173
+ [d[key] for d in batch], collate_fn_map=collate_fn_map
174
+ )
175
+ for key in elem
176
+ }
177
+ )
178
+ return clone
179
+ else:
180
+ return elem_type(
181
+ {
182
+ key: collate(
183
+ [d[key] for d in batch], collate_fn_map=collate_fn_map
184
+ )
185
+ for key in elem
186
+ }
187
+ )
188
+ except TypeError:
189
+ # The mapping type may not support `copy()` / `update(mapping)`
190
+ # or `__init__(iterable)`.
191
+ return {
192
+ key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map)
193
+ for key in elem
194
+ }
195
+ elif isinstance(elem, tuple) and hasattr(elem, "_fields"): # namedtuple
196
+ return elem_type(
197
+ *(
198
+ collate(samples, collate_fn_map=collate_fn_map)
199
+ for samples in zip(*batch)
200
+ )
201
+ )
202
+ elif isinstance(elem, collections.abc.Sequence):
203
+ # check to make sure that the elements in batch have consistent size
204
+ it = iter(batch)
205
+ elem_size = len(next(it))
206
+ if not all(len(elem) == elem_size for elem in it):
207
+ raise RuntimeError("each element in list of batch should be of equal size")
208
+ transposed = list(zip(*batch)) # It may be accessed twice, so we use a list.
209
+
210
+ if isinstance(elem, tuple):
211
+ return [
212
+ collate(samples, collate_fn_map=collate_fn_map)
213
+ for samples in transposed
214
+ ] # Backwards compatibility.
215
+ else:
216
+ try:
217
+ if isinstance(elem, collections.abc.MutableSequence):
218
+ # The sequence type may have extra properties, so we can't just
219
+ # use `type(data)(...)` to create the new sequence.
220
+ # Create a clone and update it if the sequence type is mutable.
221
+ clone = copy.copy(elem) # type: ignore[arg-type]
222
+ for i, samples in enumerate(transposed):
223
+ clone[i] = collate(samples, collate_fn_map=collate_fn_map)
224
+ return clone
225
+ else:
226
+ return elem_type(
227
+ [
228
+ collate(samples, collate_fn_map=collate_fn_map)
229
+ for samples in transposed
230
+ ]
231
+ )
232
+ except TypeError:
233
+ # The sequence type may not support `copy()` / `__setitem__(index, item)`
234
+ # or `__init__(iterable)` (e.g., `range`).
235
+ return [
236
+ collate(samples, collate_fn_map=collate_fn_map)
237
+ for samples in transposed
238
+ ]
239
+
240
+ raise TypeError(default_collate_err_msg_format.format(elem_type))
241
+
242
+
243
+ def collate_tensor_fn(
244
+ batch,
245
+ *,
246
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
247
+ ):
248
+ elem = batch[0]
249
+ out = None
250
+ if elem.is_nested:
251
+ raise RuntimeError(
252
+ "Batches of nested tensors are not currently supported by the default collate_fn; "
253
+ "please provide a custom collate_fn to handle them appropriately."
254
+ )
255
+ if elem.layout in {
256
+ torch.sparse_coo,
257
+ torch.sparse_csr,
258
+ torch.sparse_bsr,
259
+ torch.sparse_csc,
260
+ torch.sparse_bsc,
261
+ }:
262
+ raise RuntimeError(
263
+ "Batches of sparse tensors are not currently supported by the default collate_fn; "
264
+ "please provide a custom collate_fn to handle them appropriately."
265
+ )
266
+ if torch.utils.data.get_worker_info() is not None:
267
+ # If we're in a background process, concatenate directly into a
268
+ # shared memory tensor to avoid an extra copy
269
+ numel = sum(x.numel() for x in batch)
270
+ storage = elem._typed_storage()._new_shared(numel, device=elem.device)
271
+ out = elem.new(storage).resize_(len(batch), *list(elem.size()))
272
+ return torch.stack(batch, 0, out=out)
273
+
274
+
275
+ def collate_numpy_array_fn(
276
+ batch,
277
+ *,
278
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
279
+ ):
280
+ elem = batch[0]
281
+ # array of string classes and object
282
+ if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
283
+ raise TypeError(default_collate_err_msg_format.format(elem.dtype))
284
+
285
+ return collate([torch.as_tensor(b) for b in batch], collate_fn_map=collate_fn_map)
286
+
287
+
288
+ def collate_numpy_scalar_fn(
289
+ batch,
290
+ *,
291
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
292
+ ):
293
+ return torch.as_tensor(batch)
294
+
295
+
296
+ def collate_float_fn(
297
+ batch,
298
+ *,
299
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
300
+ ):
301
+ return torch.tensor(batch, dtype=torch.float64)
302
+
303
+
304
+ def collate_int_fn(
305
+ batch,
306
+ *,
307
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
308
+ ):
309
+ return torch.tensor(batch)
310
+
311
+
312
+ def collate_str_fn(
313
+ batch,
314
+ *,
315
+ collate_fn_map: Optional[dict[Union[type, tuple[type, ...]], Callable]] = None,
316
+ ):
317
+ return batch
318
+
319
+
320
+ default_collate_fn_map: dict[Union[type, tuple[type, ...]], Callable] = {
321
+ torch.Tensor: collate_tensor_fn
322
+ }
323
+ with contextlib.suppress(ImportError):
324
+ import numpy as np
325
+
326
+ # For both ndarray and memmap (subclass of ndarray)
327
+ default_collate_fn_map[np.ndarray] = collate_numpy_array_fn
328
+ # See scalars hierarchy: https://numpy.org/doc/stable/reference/arrays.scalars.html
329
+ # Skip string scalars
330
+ default_collate_fn_map[(np.bool_, np.number, np.object_)] = collate_numpy_scalar_fn
331
+ default_collate_fn_map[float] = collate_float_fn
332
+ default_collate_fn_map[int] = collate_int_fn
333
+ default_collate_fn_map[str] = collate_str_fn
334
+ default_collate_fn_map[bytes] = collate_str_fn
335
+
336
+
337
+ def default_collate(batch):
338
+ r"""
339
+ Take in a batch of data and put the elements within the batch into a tensor with an additional outer dimension - batch size.
340
+
341
+ The exact output type can be a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a
342
+ Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.
343
+ This is used as the default function for collation when
344
+ `batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`.
345
+
346
+ Here is the general input type (based on the type of the element within the batch) to output type mapping:
347
+
348
+ * :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size)
349
+ * NumPy Arrays -> :class:`torch.Tensor`
350
+ * `float` -> :class:`torch.Tensor`
351
+ * `int` -> :class:`torch.Tensor`
352
+ * `str` -> `str` (unchanged)
353
+ * `bytes` -> `bytes` (unchanged)
354
+ * `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]`
355
+ * `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]),
356
+ default_collate([V2_1, V2_2, ...]), ...]`
357
+ * `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]),
358
+ default_collate([V2_1, V2_2, ...]), ...]`
359
+
360
+ Args:
361
+ batch: a single batch to be collated
362
+
363
+ Examples:
364
+ >>> # xdoctest: +SKIP
365
+ >>> # Example with a batch of `int`s:
366
+ >>> default_collate([0, 1, 2, 3])
367
+ tensor([0, 1, 2, 3])
368
+ >>> # Example with a batch of `str`s:
369
+ >>> default_collate(['a', 'b', 'c'])
370
+ ['a', 'b', 'c']
371
+ >>> # Example with `Map` inside the batch:
372
+ >>> default_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}])
373
+ {'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])}
374
+ >>> # Example with `NamedTuple` inside the batch:
375
+ >>> Point = namedtuple('Point', ['x', 'y'])
376
+ >>> default_collate([Point(0, 0), Point(1, 1)])
377
+ Point(x=tensor([0, 1]), y=tensor([0, 1]))
378
+ >>> # Example with `Tuple` inside the batch:
379
+ >>> default_collate([(0, 1), (2, 3)])
380
+ [tensor([0, 2]), tensor([1, 3])]
381
+ >>> # Example with `List` inside the batch:
382
+ >>> default_collate([[0, 1], [2, 3]])
383
+ [tensor([0, 2]), tensor([1, 3])]
384
+ >>> # Two options to extend `default_collate` to handle specific type
385
+ >>> # Option 1: Write custom collate function and invoke `default_collate`
386
+ >>> def custom_collate(batch):
387
+ ... elem = batch[0]
388
+ ... if isinstance(elem, CustomType): # Some custom condition
389
+ ... return ...
390
+ ... else: # Fall back to `default_collate`
391
+ ... return default_collate(batch)
392
+ >>> # Option 2: In-place modify `default_collate_fn_map`
393
+ >>> def collate_customtype_fn(batch, *, collate_fn_map=None):
394
+ ... return ...
395
+ >>> default_collate_fn_map.update(CustomType, collate_customtype_fn)
396
+ >>> default_collate(batch) # Handle `CustomType` automatically
397
+ """
398
+ return collate(batch, collate_fn_map=default_collate_fn_map)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/fetch.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""Contains definitions of the methods used by the _BaseDataLoaderIter to fetch data from an iterable-style or map-style dataset.
3
+
4
+ This logic is shared in both single- and multi-processing data loading.
5
+ """
6
+
7
+
8
+ class _BaseDatasetFetcher:
9
+ def __init__(self, dataset, auto_collation, collate_fn, drop_last):
10
+ self.dataset = dataset
11
+ self.auto_collation = auto_collation
12
+ self.collate_fn = collate_fn
13
+ self.drop_last = drop_last
14
+
15
+ def fetch(self, possibly_batched_index):
16
+ raise NotImplementedError
17
+
18
+
19
+ class _IterableDatasetFetcher(_BaseDatasetFetcher):
20
+ def __init__(self, dataset, auto_collation, collate_fn, drop_last):
21
+ super().__init__(dataset, auto_collation, collate_fn, drop_last)
22
+ self.dataset_iter = iter(dataset)
23
+ self.ended = False
24
+
25
+ def fetch(self, possibly_batched_index):
26
+ if self.ended:
27
+ raise StopIteration
28
+
29
+ if self.auto_collation:
30
+ data = []
31
+ for _ in possibly_batched_index:
32
+ try:
33
+ data.append(next(self.dataset_iter))
34
+ except StopIteration:
35
+ self.ended = True
36
+ break
37
+ if len(data) == 0 or (
38
+ self.drop_last and len(data) < len(possibly_batched_index)
39
+ ):
40
+ raise StopIteration
41
+ else:
42
+ data = next(self.dataset_iter)
43
+ return self.collate_fn(data)
44
+
45
+
46
+ class _MapDatasetFetcher(_BaseDatasetFetcher):
47
+ def fetch(self, possibly_batched_index):
48
+ if self.auto_collation:
49
+ if hasattr(self.dataset, "__getitems__") and self.dataset.__getitems__:
50
+ data = self.dataset.__getitems__(possibly_batched_index)
51
+ else:
52
+ data = [self.dataset[idx] for idx in possibly_batched_index]
53
+ else:
54
+ data = self.dataset[possibly_batched_index]
55
+ return self.collate_fn(data)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/pin_memory.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""Contains definitions of the methods used by the _BaseDataLoaderIter to put fetched tensors into pinned memory.
3
+
4
+ These **needs** to be in global scope since Py2 doesn't support serializing
5
+ static methods.
6
+ """
7
+
8
+ import collections
9
+ import copy
10
+ import queue
11
+
12
+ import torch
13
+ from torch._utils import ExceptionWrapper
14
+
15
+ from . import MP_STATUS_CHECK_INTERVAL
16
+
17
+
18
+ def _pin_memory_loop(in_queue, out_queue, device_id, done_event, device):
19
+ # This setting is thread local, and prevents the copy in pin_memory from
20
+ # consuming all CPU cores.
21
+ torch.set_num_threads(1)
22
+
23
+ torch.multiprocessing._set_thread_name("pt_data_pin")
24
+
25
+ if device == "cuda":
26
+ torch.cuda.set_device(device_id)
27
+ elif device == "xpu":
28
+ torch.xpu.set_device(device_id) # type: ignore[attr-defined]
29
+ elif device == torch._C._get_privateuse1_backend_name():
30
+ custom_device_mod = getattr(torch, torch._C._get_privateuse1_backend_name())
31
+ custom_device_mod.set_device(device_id)
32
+ elif device is None:
33
+ torch.accelerator.set_device_index(device_id)
34
+
35
+ def do_one_step():
36
+ try:
37
+ r = in_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
38
+ except queue.Empty:
39
+ return
40
+ idx, data = r
41
+ if not done_event.is_set() and not isinstance(data, ExceptionWrapper):
42
+ try:
43
+ data = pin_memory(data, device)
44
+ except Exception:
45
+ data = ExceptionWrapper(
46
+ where=f"in pin memory thread for device {device_id}"
47
+ )
48
+ r = (idx, data)
49
+ while not done_event.is_set():
50
+ try:
51
+ out_queue.put(r, timeout=MP_STATUS_CHECK_INTERVAL)
52
+ break
53
+ except queue.Full:
54
+ continue
55
+
56
+ # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
57
+ # logic of this function.
58
+ while not done_event.is_set():
59
+ # Make sure that we don't preserve any object from one iteration
60
+ # to the next
61
+ do_one_step()
62
+
63
+
64
+ def pin_memory(data, device=None):
65
+ if isinstance(data, torch.Tensor):
66
+ return data.pin_memory(device)
67
+ elif isinstance(data, (str, bytes)):
68
+ return data
69
+ elif isinstance(data, collections.abc.Mapping):
70
+ try:
71
+ if isinstance(data, collections.abc.MutableMapping):
72
+ # The sequence type may have extra properties, so we can't just
73
+ # use `type(data)(...)` to create the new sequence.
74
+ # Create a clone and update it if the sequence type is mutable.
75
+ clone = copy.copy(data)
76
+ clone.update(
77
+ {k: pin_memory(sample, device) for k, sample in data.items()}
78
+ )
79
+ return clone
80
+ else:
81
+ return type(data)({k: pin_memory(sample, device) for k, sample in data.items()}) # type: ignore[call-arg]
82
+ except TypeError:
83
+ # The mapping type may not support `copy()` / `update(mapping)`
84
+ # or `__init__(iterable)`.
85
+ return {k: pin_memory(sample, device) for k, sample in data.items()}
86
+ elif isinstance(data, tuple) and hasattr(data, "_fields"): # namedtuple
87
+ return type(data)(*(pin_memory(sample, device) for sample in data))
88
+ elif isinstance(data, tuple):
89
+ return [
90
+ pin_memory(sample, device) for sample in data
91
+ ] # Backwards compatibility.
92
+ elif isinstance(data, collections.abc.Sequence):
93
+ try:
94
+ if isinstance(data, collections.abc.MutableSequence):
95
+ # The sequence type may have extra properties, so we can't just
96
+ # use `type(data)(...)` to create the new sequence.
97
+ # Create a clone and update it if the sequence type is mutable.
98
+ clone = copy.copy(data) # type: ignore[arg-type]
99
+ for i, item in enumerate(data):
100
+ clone[i] = pin_memory(item, device)
101
+ return clone
102
+ return type(data)([pin_memory(sample, device) for sample in data]) # type: ignore[call-arg]
103
+ except TypeError:
104
+ # The sequence type may not support `copy()` / `__setitem__(index, item)`
105
+ # or `__init__(iterable)` (e.g., `range`).
106
+ return [pin_memory(sample, device) for sample in data]
107
+ elif hasattr(data, "pin_memory"):
108
+ return data.pin_memory()
109
+ else:
110
+ return data
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/signal_handling.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""Signal handling for multiprocessing data loading.
3
+
4
+ NOTE [ Signal handling in multiprocessing data loading ]
5
+
6
+ In cases like DataLoader, if a worker process dies due to bus error/segfault
7
+ or just hang, the main process will hang waiting for data. This is difficult
8
+ to avoid on PyTorch side as it can be caused by limited shm, or other
9
+ libraries users call in the workers. In this file and `DataLoader.cpp`, we make
10
+ our best effort to provide some error message to users when such unfortunate
11
+ events happen.
12
+
13
+ When a _BaseDataLoaderIter starts worker processes, their pids are registered in a
14
+ defined in `DataLoader.cpp`: id(_BaseDataLoaderIter) => Collection[ Worker pids ]
15
+ via `_set_worker_pids`.
16
+
17
+ When an error happens in a worker process, the main process received a SIGCHLD,
18
+ and Python will eventually call the handler registered below
19
+ (in `_set_SIGCHLD_handler`). In the handler, the `_error_if_any_worker_fails`
20
+ call checks all registered worker pids and raise proper error message to
21
+ prevent main process from hanging waiting for data from worker.
22
+
23
+ Additionally, at the beginning of each worker's `_utils.worker._worker_loop`,
24
+ `_set_worker_signal_handlers` is called to register critical signal handlers
25
+ (e.g., for SIGSEGV, SIGBUS, SIGFPE, SIGTERM) in C, which just prints an error
26
+ message to stderr before triggering the default handler. So a message will also
27
+ be printed from the worker process when it is killed by such signals.
28
+
29
+ See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for the reasoning of
30
+ this signal handling design and other mechanism we implement to make our
31
+ multiprocessing data loading robust to errors.
32
+ """
33
+
34
+ import signal
35
+ import threading
36
+
37
+ # Some of the following imported functions are not used in this file, but are to
38
+ # be used `_utils.signal_handling.XXXXX`.
39
+ from torch._C import ( # noqa: F401
40
+ _error_if_any_worker_fails,
41
+ _remove_worker_pids,
42
+ _set_worker_pids,
43
+ _set_worker_signal_handlers,
44
+ )
45
+
46
+ from . import IS_WINDOWS
47
+
48
+
49
+ _SIGCHLD_handler_set = False
50
+ r"""Whether SIGCHLD handler is set for DataLoader worker failures. Only one
51
+ handler needs to be set for all DataLoaders in a process."""
52
+
53
+
54
+ def _set_SIGCHLD_handler():
55
+ # Windows doesn't support SIGCHLD handler
56
+ if IS_WINDOWS:
57
+ return
58
+ # can't set signal in child threads
59
+ if not isinstance(threading.current_thread(), threading._MainThread): # type: ignore[attr-defined]
60
+ return
61
+ global _SIGCHLD_handler_set
62
+ if _SIGCHLD_handler_set:
63
+ return
64
+ previous_handler = signal.getsignal(signal.SIGCHLD)
65
+ if not callable(previous_handler):
66
+ # This doesn't catch default handler, but SIGCHLD default handler is a
67
+ # no-op.
68
+ previous_handler = None
69
+
70
+ def handler(signum, frame):
71
+ # This following call uses `waitid` with WNOHANG from C side. Therefore,
72
+ # Python can still get and update the process status successfully.
73
+ _error_if_any_worker_fails()
74
+ if previous_handler is not None:
75
+ assert callable(previous_handler)
76
+ previous_handler(signum, frame)
77
+
78
+ signal.signal(signal.SIGCHLD, handler)
79
+ _SIGCHLD_handler_set = True
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/_utils/worker.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers.
3
+
4
+ These **needs** to be in global scope since Py2 doesn't support serializing
5
+ static methods.
6
+ """
7
+
8
+ import os
9
+ import queue
10
+ import random
11
+ from dataclasses import dataclass
12
+ from typing import Optional, TYPE_CHECKING, Union
13
+
14
+ import torch
15
+ from torch._utils import ExceptionWrapper
16
+
17
+ from . import HAS_NUMPY, IS_WINDOWS, MP_STATUS_CHECK_INTERVAL, signal_handling
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from torch.utils.data import Dataset
22
+
23
+ if IS_WINDOWS:
24
+ import ctypes
25
+ from ctypes.wintypes import BOOL, DWORD, HANDLE
26
+
27
+ # On Windows, the parent ID of the worker process remains unchanged when the manager process
28
+ # is gone, and the only way to check it through OS is to let the worker have a process handle
29
+ # of the manager and ask if the process status has changed.
30
+ class ManagerWatchdog:
31
+ def __init__(self) -> None:
32
+ self.manager_pid = os.getppid()
33
+
34
+ # mypy cannot detect this code is windows only
35
+ self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
36
+ self.kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)
37
+ self.kernel32.OpenProcess.restype = HANDLE
38
+ self.kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD)
39
+ self.kernel32.WaitForSingleObject.restype = DWORD
40
+
41
+ # Value obtained from https://msdn.microsoft.com/en-us/library/ms684880.aspx
42
+ SYNCHRONIZE = 0x00100000
43
+ self.manager_handle = self.kernel32.OpenProcess(
44
+ SYNCHRONIZE, 0, self.manager_pid
45
+ )
46
+
47
+ if not self.manager_handle:
48
+ raise ctypes.WinError(ctypes.get_last_error()) # type: ignore[attr-defined]
49
+
50
+ self.manager_dead = False
51
+
52
+ def is_alive(self):
53
+ if not self.manager_dead:
54
+ # Value obtained from https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032.aspx
55
+ self.manager_dead = (
56
+ self.kernel32.WaitForSingleObject(self.manager_handle, 0) == 0
57
+ )
58
+ return not self.manager_dead
59
+
60
+ else:
61
+
62
+ class ManagerWatchdog: # type: ignore[no-redef]
63
+ def __init__(self) -> None:
64
+ self.manager_pid = os.getppid()
65
+ self.manager_dead = False
66
+
67
+ def is_alive(self):
68
+ if not self.manager_dead:
69
+ self.manager_dead = os.getppid() != self.manager_pid
70
+ return not self.manager_dead
71
+
72
+
73
+ _worker_info: Optional["WorkerInfo"] = None
74
+
75
+
76
+ class WorkerInfo:
77
+ id: int
78
+ num_workers: int
79
+ seed: int
80
+ dataset: "Dataset"
81
+ __initialized = False
82
+
83
+ def __init__(self, **kwargs):
84
+ for k, v in kwargs.items():
85
+ setattr(self, k, v)
86
+ self.__keys = tuple(kwargs.keys())
87
+ self.__initialized = True
88
+
89
+ def __setattr__(self, key, val):
90
+ if self.__initialized:
91
+ raise RuntimeError(
92
+ f"Cannot assign attributes to {self.__class__.__name__} objects"
93
+ )
94
+ return super().__setattr__(key, val)
95
+
96
+ def __repr__(self):
97
+ items = [f"{k}={getattr(self, k)}" for k in self.__keys]
98
+ return f"{self.__class__.__name__}({', '.join(items)})"
99
+
100
+
101
+ def get_worker_info() -> Optional[WorkerInfo]:
102
+ r"""Returns the information about the current
103
+ :class:`~torch.utils.data.DataLoader` iterator worker process.
104
+
105
+ When called in a worker, this returns an object guaranteed to have the
106
+ following attributes:
107
+
108
+ * :attr:`id`: the current worker id.
109
+ * :attr:`num_workers`: the total number of workers.
110
+ * :attr:`seed`: the random seed set for the current worker. This value is
111
+ determined by main process RNG and the worker id. See
112
+ :class:`~torch.utils.data.DataLoader`'s documentation for more details.
113
+ * :attr:`dataset`: the copy of the dataset object in **this** process. Note
114
+ that this will be a different object in a different process than the one
115
+ in the main process.
116
+
117
+ When called in the main process, this returns ``None``.
118
+
119
+ .. note::
120
+ When used in a :attr:`worker_init_fn` passed over to
121
+ :class:`~torch.utils.data.DataLoader`, this method can be useful to
122
+ set up each worker process differently, for instance, using ``worker_id``
123
+ to configure the ``dataset`` object to only read a specific fraction of a
124
+ sharded dataset, or use ``seed`` to seed other libraries used in dataset
125
+ code.
126
+ """
127
+ return _worker_info
128
+
129
+
130
+ r"""Dummy class used to signal the end of an IterableDataset"""
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class _IterableDatasetStopIteration:
135
+ worker_id: int
136
+
137
+
138
+ r"""Dummy class used to resume the fetching when worker reuse is enabled"""
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class _ResumeIteration:
143
+ seed: Optional[int] = None
144
+
145
+
146
+ # The function `_generate_state` is adapted from `numpy.random.SeedSequence`
147
+ # from https://github.com/numpy/numpy/blob/main/numpy/random/bit_generator.pyx
148
+ # It's MIT licensed, here is the copyright:
149
+
150
+ # Copyright (c) 2015 Melissa E. O'Neill
151
+ # Copyright (c) 2019 NumPy Developers
152
+ #
153
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
154
+ # of this software and associated documentation files (the "Software"), to deal
155
+ # in the Software without restriction, including without limitation the rights
156
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
157
+ # copies of the Software, and to permit persons to whom the Software is
158
+ # furnished to do so, subject to the following conditions:
159
+ #
160
+ # The above copyright notice and this permission notice shall be included in
161
+ # all copies or substantial portions of the Software.
162
+ #
163
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
164
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
165
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
166
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
167
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
168
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
169
+ # SOFTWARE.
170
+
171
+
172
+ # This function generates an array of int32 as the seed for
173
+ # `numpy.random`, in order to prevent state collision due to same
174
+ # seed and algorithm for `numpy.random` and `random` modules.
175
+ # TODO: Implement `SeedSequence` like object for `torch.random`
176
+ def _generate_state(base_seed, worker_id):
177
+ INIT_A = 0x43B0D7E5
178
+ MULT_A = 0x931E8875
179
+ INIT_B = 0x8B51F9DD
180
+ MULT_B = 0x58F38DED
181
+ MIX_MULT_L = 0xCA01F9DD
182
+ MIX_MULT_R = 0x4973F715
183
+ XSHIFT = 4 * 8 // 2
184
+ MASK32 = 0xFFFFFFFF
185
+
186
+ entropy = [worker_id, base_seed & MASK32, base_seed >> 32, 0]
187
+ pool = [0] * 4
188
+
189
+ hash_const_A = INIT_A
190
+
191
+ def hash(value):
192
+ nonlocal hash_const_A
193
+ value = (value ^ hash_const_A) & MASK32
194
+ hash_const_A = (hash_const_A * MULT_A) & MASK32
195
+ value = (value * hash_const_A) & MASK32
196
+ value = (value ^ (value >> XSHIFT)) & MASK32
197
+ return value
198
+
199
+ def mix(x, y):
200
+ result_x = (MIX_MULT_L * x) & MASK32
201
+ result_y = (MIX_MULT_R * y) & MASK32
202
+ result = (result_x - result_y) & MASK32
203
+ result = (result ^ (result >> XSHIFT)) & MASK32
204
+ return result
205
+
206
+ # Add in the entropy to the pool.
207
+ for i in range(len(pool)):
208
+ pool[i] = hash(entropy[i])
209
+
210
+ # Mix all bits together so late bits can affect earlier bits.
211
+ for i_src in range(len(pool)):
212
+ for i_dst in range(len(pool)):
213
+ if i_src != i_dst:
214
+ pool[i_dst] = mix(pool[i_dst], hash(pool[i_src]))
215
+
216
+ hash_const_B = INIT_B
217
+ state = []
218
+ for i_dst in range(4):
219
+ data_val = pool[i_dst]
220
+ data_val = (data_val ^ hash_const_B) & MASK32
221
+ hash_const_B = (hash_const_B * MULT_B) & MASK32
222
+ data_val = (data_val * hash_const_B) & MASK32
223
+ data_val = (data_val ^ (data_val >> XSHIFT)) & MASK32
224
+ state.append(data_val)
225
+ return state
226
+
227
+
228
+ def _worker_loop(
229
+ dataset_kind,
230
+ dataset,
231
+ index_queue,
232
+ data_queue,
233
+ done_event,
234
+ auto_collation,
235
+ collate_fn,
236
+ drop_last,
237
+ base_seed,
238
+ init_fn,
239
+ worker_id,
240
+ num_workers,
241
+ persistent_workers,
242
+ shared_seed,
243
+ ):
244
+ # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
245
+ # logic of this function.
246
+
247
+ try:
248
+ # Initialize C side signal handlers for SIGBUS and SIGSEGV. Python signal
249
+ # module's handlers are executed after Python returns from C low-level
250
+ # handlers, likely when the same fatal signal had already happened
251
+ # again.
252
+ # https://docs.python.org/3/library/signal.html#execution-of-python-signal-handlers
253
+ signal_handling._set_worker_signal_handlers()
254
+
255
+ torch.multiprocessing._set_thread_name("pt_data_worker")
256
+
257
+ torch.set_num_threads(1)
258
+ seed = base_seed + worker_id
259
+ random.seed(seed)
260
+ torch.manual_seed(seed)
261
+ if HAS_NUMPY:
262
+ np_seed = _generate_state(base_seed, worker_id)
263
+ import numpy as np
264
+
265
+ np.random.seed(np_seed)
266
+
267
+ from torch.utils.data import IterDataPipe
268
+ from torch.utils.data.graph_settings import apply_random_seed
269
+
270
+ shared_rng = torch.Generator()
271
+ if isinstance(dataset, IterDataPipe):
272
+ assert shared_seed is not None
273
+ shared_rng.manual_seed(shared_seed)
274
+ dataset = apply_random_seed(dataset, shared_rng)
275
+
276
+ global _worker_info
277
+ _worker_info = WorkerInfo(
278
+ id=worker_id, num_workers=num_workers, seed=seed, dataset=dataset
279
+ )
280
+
281
+ from torch.utils.data import _DatasetKind
282
+
283
+ init_exception = None
284
+
285
+ try:
286
+ if init_fn is not None:
287
+ init_fn(worker_id)
288
+
289
+ fetcher = _DatasetKind.create_fetcher(
290
+ dataset_kind, dataset, auto_collation, collate_fn, drop_last
291
+ )
292
+ except Exception:
293
+ init_exception = ExceptionWrapper(
294
+ where=f"in DataLoader worker process {worker_id}"
295
+ )
296
+
297
+ # When using Iterable mode, some worker can exit earlier than others due
298
+ # to the IterableDataset behaving differently for different workers.
299
+ # When such things happen, an `_IterableDatasetStopIteration` object is
300
+ # sent over to the main process with the ID of this worker, so that the
301
+ # main process won't send more tasks to this worker, and will send
302
+ # `None` to this worker to properly exit it.
303
+ #
304
+ # Note that we cannot set `done_event` from a worker as it is shared
305
+ # among all processes. Instead, we set the `iteration_end` flag to
306
+ # signify that the iterator is exhausted. When either `done_event` or
307
+ # `iteration_end` is set, we skip all processing step and just wait for
308
+ # `None`.
309
+ iteration_end = False
310
+
311
+ watchdog = ManagerWatchdog()
312
+
313
+ while watchdog.is_alive():
314
+ try:
315
+ r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
316
+ except queue.Empty:
317
+ continue
318
+ if isinstance(r, _ResumeIteration):
319
+ # Acknowledge the main process
320
+ data_queue.put((r, None))
321
+ iteration_end = False
322
+
323
+ if isinstance(dataset, IterDataPipe):
324
+ assert r.seed is not None
325
+ shared_rng.manual_seed(r.seed)
326
+ dataset = apply_random_seed(dataset, shared_rng)
327
+
328
+ # Recreate the fetcher for worker-reuse policy
329
+ fetcher = _DatasetKind.create_fetcher(
330
+ dataset_kind, dataset, auto_collation, collate_fn, drop_last
331
+ )
332
+ continue
333
+ elif r is None:
334
+ # Received the final signal
335
+ assert done_event.is_set() or iteration_end
336
+ break
337
+ elif done_event.is_set() or iteration_end:
338
+ # `done_event` is set. But I haven't received the final signal
339
+ # (None) yet. I will keep continuing until get it, and skip the
340
+ # processing steps.
341
+ continue
342
+ idx, index = r
343
+ data: Union[_IterableDatasetStopIteration, ExceptionWrapper]
344
+ if init_exception is not None:
345
+ data = init_exception
346
+ init_exception = None
347
+ else:
348
+ try:
349
+ data = fetcher.fetch(index) # type: ignore[possibly-undefined]
350
+ except Exception as e:
351
+ if (
352
+ isinstance(e, StopIteration)
353
+ and dataset_kind == _DatasetKind.Iterable
354
+ ):
355
+ data = _IterableDatasetStopIteration(worker_id)
356
+ # Set `iteration_end`
357
+ # (1) to save future `next(...)` calls, and
358
+ # (2) to avoid sending multiple `_IterableDatasetStopIteration`s.
359
+ iteration_end = True
360
+ else:
361
+ # It is important that we don't store exc_info in a variable.
362
+ # `ExceptionWrapper` does the correct thing.
363
+ # See NOTE [ Python Traceback Reference Cycle Problem ]
364
+ data = ExceptionWrapper(
365
+ where=f"in DataLoader worker process {worker_id}"
366
+ )
367
+ data_queue.put((idx, data))
368
+ del data, idx, index, r # save memory
369
+ except KeyboardInterrupt:
370
+ # Main process will raise KeyboardInterrupt anyways.
371
+ pass
372
+ if done_event.is_set():
373
+ data_queue.cancel_join_thread()
374
+ data_queue.close()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/backward_compatibility.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing_extensions import deprecated as _deprecated
3
+
4
+
5
+ @_deprecated(
6
+ "Usage of `backward_compatibility.worker_init_fn` is deprecated "
7
+ "as `DataLoader` automatically applies sharding in every worker",
8
+ category=FutureWarning,
9
+ )
10
+ def worker_init_fn(worker_id):
11
+ pass
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/dataloader.py ADDED
@@ -0,0 +1,1664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter.
3
+
4
+ To support these two classes, in `./_utils` we define many utility methods and
5
+ functions to be run in multiprocessing. E.g., the data loading worker loop is
6
+ in `./_utils/worker.py`.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import itertools
12
+ import logging
13
+ import multiprocessing as python_multiprocessing
14
+ import os
15
+ import queue
16
+ import threading
17
+ import warnings
18
+ from typing import Any, Callable, Generic, Optional, TYPE_CHECKING, TypeVar, Union
19
+ from typing_extensions import Self
20
+
21
+ import torch
22
+ import torch.distributed as dist
23
+ import torch.utils.data.graph_settings
24
+ from torch._utils import ExceptionWrapper
25
+ from torch.utils.data import _utils
26
+ from torch.utils.data.datapipes.datapipe import (
27
+ _IterDataPipeSerializationWrapper,
28
+ _MapDataPipeSerializationWrapper,
29
+ IterDataPipe,
30
+ MapDataPipe,
31
+ )
32
+ from torch.utils.data.dataset import Dataset, IterableDataset
33
+ from torch.utils.data.sampler import (
34
+ BatchSampler,
35
+ RandomSampler,
36
+ Sampler,
37
+ SequentialSampler,
38
+ )
39
+
40
+
41
+ if TYPE_CHECKING:
42
+ from collections.abc import Iterable
43
+
44
+ __all__ = [
45
+ "DataLoader",
46
+ "get_worker_info",
47
+ "default_collate",
48
+ "default_convert",
49
+ ]
50
+
51
+
52
+ _T = TypeVar("_T")
53
+ _T_co = TypeVar("_T_co", covariant=True)
54
+ _worker_init_fn_t = Callable[[int], None]
55
+
56
+ # Ideally we would parameterize `DataLoader` by the return type of `collate_fn`, but there is currently no way to have that
57
+ # type parameter set to a default value if the user doesn't pass in a custom 'collate_fn'.
58
+ # See https://github.com/python/mypy/issues/3737.
59
+ _collate_fn_t = Callable[[list[_T]], Any]
60
+
61
+
62
+ # These functions used to be defined in this file. However, it was moved to
63
+ # _utils/collate.py. Although it is rather hard to access this from user land
64
+ # (one has to explicitly directly `import torch.utils.data.dataloader`), there
65
+ # probably is user code out there using it. This aliasing maintains BC in this
66
+ # aspect.
67
+ default_collate: _collate_fn_t = _utils.collate.default_collate
68
+ default_convert = _utils.collate.default_convert
69
+
70
+ get_worker_info = _utils.worker.get_worker_info
71
+
72
+ logger = logging.getLogger(__name__)
73
+
74
+
75
+ class _DatasetKind:
76
+ Map = 0
77
+ Iterable = 1
78
+
79
+ @staticmethod
80
+ def create_fetcher(kind, dataset, auto_collation, collate_fn, drop_last):
81
+ if kind == _DatasetKind.Map:
82
+ return _utils.fetch._MapDatasetFetcher(
83
+ dataset, auto_collation, collate_fn, drop_last
84
+ )
85
+ else:
86
+ return _utils.fetch._IterableDatasetFetcher(
87
+ dataset, auto_collation, collate_fn, drop_last
88
+ )
89
+
90
+
91
+ class _InfiniteConstantSampler(Sampler):
92
+ r"""Analogous to ``itertools.repeat(None, None)``.
93
+
94
+ Used as sampler for :class:`~torch.utils.data.IterableDataset`.
95
+ """
96
+
97
+ def __iter__(self):
98
+ while True:
99
+ yield None
100
+
101
+
102
+ def _get_distributed_settings():
103
+ if dist.is_available() and dist.is_initialized():
104
+ return dist.get_world_size(), dist.get_rank()
105
+ else:
106
+ return 1, 0
107
+
108
+
109
+ def _sharding_worker_init_fn(worker_init_fn, world_size, rank_id, worker_id):
110
+ global_worker_id = worker_id
111
+ info = torch.utils.data.get_worker_info()
112
+ assert info is not None
113
+ total_workers = info.num_workers
114
+ datapipe = info.dataset
115
+ assert isinstance(datapipe, (IterDataPipe, MapDataPipe))
116
+ # To distribute elements across distributed process evenly, we should shard data on distributed
117
+ # processes first then shard on worker processes
118
+ total_workers *= world_size
119
+ global_worker_id = global_worker_id * world_size + rank_id
120
+ # For BC, use default SHARDING_PRIORITIES
121
+ torch.utils.data.graph_settings.apply_sharding(
122
+ datapipe, total_workers, global_worker_id
123
+ )
124
+ if worker_init_fn is not None:
125
+ worker_init_fn(worker_id)
126
+
127
+
128
+ def _share_dist_seed(generator, pg):
129
+ _shared_seed = torch.empty((), dtype=torch.int64).random_(generator=generator)
130
+ if isinstance(pg, dist.ProcessGroup):
131
+ dist.broadcast(_shared_seed, src=0, group=pg)
132
+ return _shared_seed.item()
133
+
134
+
135
+ class DataLoader(Generic[_T_co]):
136
+ r"""
137
+ Data loader combines a dataset and a sampler, and provides an iterable over the given dataset.
138
+
139
+ The :class:`~torch.utils.data.DataLoader` supports both map-style and
140
+ iterable-style datasets with single- or multi-process loading, customizing
141
+ loading order and optional automatic batching (collation) and memory pinning.
142
+
143
+ See :py:mod:`torch.utils.data` documentation page for more details.
144
+
145
+ Args:
146
+ dataset (Dataset): dataset from which to load the data.
147
+ batch_size (int, optional): how many samples per batch to load
148
+ (default: ``1``).
149
+ shuffle (bool, optional): set to ``True`` to have the data reshuffled
150
+ at every epoch (default: ``False``).
151
+ sampler (Sampler or Iterable, optional): defines the strategy to draw
152
+ samples from the dataset. Can be any ``Iterable`` with ``__len__``
153
+ implemented. If specified, :attr:`shuffle` must not be specified.
154
+ batch_sampler (Sampler or Iterable, optional): like :attr:`sampler`, but
155
+ returns a batch of indices at a time. Mutually exclusive with
156
+ :attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`,
157
+ and :attr:`drop_last`.
158
+ num_workers (int, optional): how many subprocesses to use for data
159
+ loading. ``0`` means that the data will be loaded in the main process.
160
+ (default: ``0``)
161
+ collate_fn (Callable, optional): merges a list of samples to form a
162
+ mini-batch of Tensor(s). Used when using batched loading from a
163
+ map-style dataset.
164
+ pin_memory (bool, optional): If ``True``, the data loader will copy Tensors
165
+ into device/CUDA pinned memory before returning them. If your data elements
166
+ are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,
167
+ see the example below.
168
+ drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
169
+ if the dataset size is not divisible by the batch size. If ``False`` and
170
+ the size of dataset is not divisible by the batch size, then the last batch
171
+ will be smaller. (default: ``False``)
172
+ timeout (numeric, optional): if positive, the timeout value for collecting a batch
173
+ from workers. Should always be non-negative. (default: ``0``)
174
+ worker_init_fn (Callable, optional): If not ``None``, this will be called on each
175
+ worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as
176
+ input, after seeding and before data loading. (default: ``None``)
177
+ multiprocessing_context (str or multiprocessing.context.BaseContext, optional): If
178
+ ``None``, the default
179
+ `multiprocessing context <https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods>`_ # noqa: D401
180
+ of your operating system will
181
+ be used. (default: ``None``)
182
+ generator (torch.Generator, optional): If not ``None``, this RNG will be used
183
+ by RandomSampler to generate random indexes and multiprocessing to generate
184
+ ``base_seed`` for workers. (default: ``None``)
185
+ prefetch_factor (int, optional, keyword-only arg): Number of batches loaded
186
+ in advance by each worker. ``2`` means there will be a total of
187
+ 2 * num_workers batches prefetched across all workers. (default value depends
188
+ on the set value for num_workers. If value of num_workers=0 default is ``None``.
189
+ Otherwise, if value of ``num_workers > 0`` default is ``2``).
190
+ persistent_workers (bool, optional): If ``True``, the data loader will not shut down
191
+ the worker processes after a dataset has been consumed once. This allows to
192
+ maintain the workers `Dataset` instances alive. (default: ``False``)
193
+ pin_memory_device (str, optional): the device to :attr:`pin_memory` on if ``pin_memory`` is
194
+ ``True``. If not given, the current :ref:`accelerator<accelerators>` will be the
195
+ default. This argument is discouraged and subject to deprecated.
196
+ in_order (bool, optional): If ``False``, the data loader will not enforce that batches
197
+ are returned in a first-in, first-out order. Only applies when ``num_workers > 0``. (default: ``True``)
198
+
199
+
200
+ .. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn`
201
+ cannot be an unpicklable object, e.g., a lambda function. See
202
+ :ref:`multiprocessing-best-practices` on more details related
203
+ to multiprocessing in PyTorch.
204
+
205
+ .. warning:: ``len(dataloader)`` heuristic is based on the length of the sampler used.
206
+ When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`,
207
+ it instead returns an estimate based on ``len(dataset) / batch_size``, with proper
208
+ rounding depending on :attr:`drop_last`, regardless of multi-process loading
209
+ configurations. This represents the best guess PyTorch can make because PyTorch
210
+ trusts user :attr:`dataset` code in correctly handling multi-process
211
+ loading to avoid duplicate data.
212
+
213
+ However, if sharding results in multiple workers having incomplete last batches,
214
+ this estimate can still be inaccurate, because (1) an otherwise complete batch can
215
+ be broken into multiple ones and (2) more than one batch worth of samples can be
216
+ dropped when :attr:`drop_last` is set. Unfortunately, PyTorch can not detect such
217
+ cases in general.
218
+
219
+ See `Dataset Types`_ for more details on these two types of datasets and how
220
+ :class:`~torch.utils.data.IterableDataset` interacts with
221
+ `Multi-process data loading`_.
222
+
223
+ .. warning:: See :ref:`reproducibility`, and :ref:`dataloader-workers-random-seed`, and
224
+ :ref:`data-loading-randomness` notes for random seed related questions.
225
+
226
+ .. warning:: Setting `in_order` to `False` can harm reproducibility and may lead to a skewed data
227
+ distribution being fed to the trainer in cases with imbalanced data.
228
+ """
229
+
230
+ dataset: Dataset[_T_co]
231
+ batch_size: Optional[int]
232
+ num_workers: int
233
+ pin_memory: bool
234
+ drop_last: bool
235
+ timeout: float
236
+ sampler: Union[Sampler, Iterable]
237
+ pin_memory_device: str
238
+ prefetch_factor: Optional[int]
239
+ _iterator: Optional[_BaseDataLoaderIter]
240
+ __initialized = False
241
+
242
+ def __init__(
243
+ self,
244
+ dataset: Dataset[_T_co],
245
+ batch_size: Optional[int] = 1,
246
+ shuffle: Optional[bool] = None,
247
+ sampler: Union[Sampler, Iterable, None] = None,
248
+ batch_sampler: Union[Sampler[list], Iterable[list], None] = None,
249
+ num_workers: int = 0,
250
+ collate_fn: Optional[_collate_fn_t] = None,
251
+ pin_memory: bool = False,
252
+ drop_last: bool = False,
253
+ timeout: float = 0,
254
+ worker_init_fn: Optional[_worker_init_fn_t] = None,
255
+ multiprocessing_context=None,
256
+ generator=None,
257
+ *,
258
+ prefetch_factor: Optional[int] = None,
259
+ persistent_workers: bool = False,
260
+ pin_memory_device: str = "",
261
+ in_order: bool = True,
262
+ ) -> None:
263
+ torch._C._log_api_usage_once("python.data_loader")
264
+
265
+ if num_workers < 0:
266
+ raise ValueError(
267
+ "num_workers option should be non-negative; "
268
+ "use num_workers=0 to disable multiprocessing."
269
+ )
270
+
271
+ if timeout < 0:
272
+ raise ValueError("timeout option should be non-negative")
273
+
274
+ if num_workers == 0 and prefetch_factor is not None:
275
+ raise ValueError(
276
+ "prefetch_factor option could only be specified in multiprocessing."
277
+ "let num_workers > 0 to enable multiprocessing, otherwise set prefetch_factor to None."
278
+ )
279
+ elif num_workers > 0 and prefetch_factor is None:
280
+ prefetch_factor = 2
281
+ elif prefetch_factor is not None and prefetch_factor < 0:
282
+ raise ValueError("prefetch_factor option should be non-negative")
283
+
284
+ if persistent_workers and num_workers == 0:
285
+ raise ValueError("persistent_workers option needs num_workers > 0")
286
+
287
+ self.dataset = dataset
288
+ self.num_workers = num_workers
289
+ self.prefetch_factor = prefetch_factor
290
+ self.pin_memory = pin_memory
291
+ self.pin_memory_device = pin_memory_device
292
+ self.timeout = timeout
293
+ self.worker_init_fn = worker_init_fn
294
+ self.multiprocessing_context = multiprocessing_context
295
+ self.in_order = in_order
296
+
297
+ # Adds forward compatibilities so classic DataLoader can work with DataPipes:
298
+ # _DataPipeSerializationWrapper container makes it easier to serialize without redefining pickler
299
+ if isinstance(self.dataset, IterDataPipe):
300
+ self.dataset = _IterDataPipeSerializationWrapper(self.dataset)
301
+ elif isinstance(self.dataset, MapDataPipe):
302
+ self.dataset = _MapDataPipeSerializationWrapper(self.dataset)
303
+
304
+ # Arg-check dataset related before checking samplers because we want to
305
+ # tell users that iterable-style datasets are incompatible with custom
306
+ # samplers first, so that they don't learn that this combo doesn't work
307
+ # after spending time fixing the custom sampler errors.
308
+ if isinstance(dataset, IterableDataset):
309
+ self._dataset_kind = _DatasetKind.Iterable
310
+ # NOTE [ Custom Samplers and IterableDataset ]
311
+ #
312
+ # `IterableDataset` does not support custom `batch_sampler` or
313
+ # `sampler` since the key is irrelevant (unless we support
314
+ # generator-style dataset one day...).
315
+ #
316
+ # For `sampler`, we always create a dummy sampler. This is an
317
+ # infinite sampler even when the dataset may have an implemented
318
+ # finite `__len__` because in multi-process data loading, naive
319
+ # settings will return duplicated data (which may be desired), and
320
+ # thus using a sampler with length matching that of dataset will
321
+ # cause data lost (you may have duplicates of the first couple
322
+ # batches, but never see anything afterwards). Therefore,
323
+ # `Iterabledataset` always uses an infinite sampler, an instance of
324
+ # `_InfiniteConstantSampler` defined above.
325
+ #
326
+ # A custom `batch_sampler` essentially only controls the batch size.
327
+ # However, it is unclear how useful it would be since an iterable-style
328
+ # dataset can handle that within itself. Moreover, it is pointless
329
+ # in multi-process data loading as the assignment order of batches
330
+ # to workers is an implementation detail so users can not control
331
+ # how to batchify each worker's iterable. Thus, we disable this
332
+ # option. If this turns out to be useful in future, we can re-enable
333
+ # this, and support custom samplers that specify the assignments to
334
+ # specific workers.
335
+ if isinstance(dataset, IterDataPipe):
336
+ if shuffle is not None:
337
+ dataset = torch.utils.data.graph_settings.apply_shuffle_settings(
338
+ dataset, shuffle=shuffle
339
+ )
340
+ # We cannot check `shuffle is not None` here, since previously `shuffle=False` was the default.
341
+ elif shuffle not in {False, None}:
342
+ raise ValueError(
343
+ f"DataLoader with IterableDataset: expected unspecified shuffle option, but got shuffle={shuffle}"
344
+ )
345
+
346
+ if sampler is not None:
347
+ # See NOTE [ Custom Samplers and IterableDataset ]
348
+ raise ValueError(
349
+ f"DataLoader with IterableDataset: expected unspecified sampler option, but got sampler={sampler}"
350
+ )
351
+ elif batch_sampler is not None:
352
+ # See NOTE [ Custom Samplers and IterableDataset ]
353
+ raise ValueError(
354
+ "DataLoader with IterableDataset: expected unspecified "
355
+ f"batch_sampler option, but got batch_sampler={batch_sampler}"
356
+ )
357
+ else:
358
+ shuffle = bool(shuffle)
359
+ self._dataset_kind = _DatasetKind.Map
360
+
361
+ if sampler is not None and shuffle:
362
+ raise ValueError("sampler option is mutually exclusive with shuffle")
363
+
364
+ if batch_sampler is not None:
365
+ # auto_collation with custom batch_sampler
366
+ if batch_size != 1 or shuffle or sampler is not None or drop_last:
367
+ raise ValueError(
368
+ "batch_sampler option is mutually exclusive "
369
+ "with batch_size, shuffle, sampler, and "
370
+ "drop_last"
371
+ )
372
+ batch_size = None
373
+ drop_last = False
374
+ elif batch_size is None:
375
+ # no auto_collation
376
+ if drop_last:
377
+ raise ValueError(
378
+ "batch_size=None option disables auto-batching "
379
+ "and is mutually exclusive with drop_last"
380
+ )
381
+
382
+ if sampler is None: # give default samplers
383
+ if self._dataset_kind == _DatasetKind.Iterable:
384
+ # See NOTE [ Custom Samplers and IterableDataset ]
385
+ sampler = _InfiniteConstantSampler()
386
+ else: # map-style
387
+ if shuffle:
388
+ sampler = RandomSampler(dataset, generator=generator) # type: ignore[arg-type]
389
+ else:
390
+ sampler = SequentialSampler(dataset) # type: ignore[arg-type]
391
+
392
+ if batch_size is not None and batch_sampler is None:
393
+ # auto_collation without custom batch_sampler
394
+ batch_sampler = BatchSampler(sampler, batch_size, drop_last)
395
+
396
+ self.batch_size = batch_size
397
+ self.drop_last = drop_last
398
+ self.sampler = sampler
399
+ self.batch_sampler = batch_sampler
400
+ self.generator = generator
401
+
402
+ if collate_fn is None:
403
+ if self._auto_collation:
404
+ collate_fn = _utils.collate.default_collate
405
+ else:
406
+ collate_fn = _utils.collate.default_convert
407
+
408
+ self.collate_fn = collate_fn
409
+ self.persistent_workers = persistent_workers
410
+
411
+ self.__initialized = True
412
+ self._IterableDataset_len_called = (
413
+ None # See NOTE [ IterableDataset and __len__ ]
414
+ )
415
+
416
+ self._iterator = None
417
+
418
+ self.check_worker_number_rationality()
419
+
420
+ torch.set_vital("Dataloader", "enabled", "True") # type: ignore[attr-defined]
421
+
422
+ def _get_iterator(self) -> _BaseDataLoaderIter:
423
+ if self.num_workers == 0:
424
+ return _SingleProcessDataLoaderIter(self)
425
+ else:
426
+ self.check_worker_number_rationality()
427
+ return _MultiProcessingDataLoaderIter(self)
428
+
429
+ @property
430
+ def multiprocessing_context(self):
431
+ return self.__multiprocessing_context
432
+
433
+ @multiprocessing_context.setter
434
+ def multiprocessing_context(self, multiprocessing_context):
435
+ if multiprocessing_context is not None:
436
+ if self.num_workers > 0:
437
+ if isinstance(multiprocessing_context, str):
438
+ valid_start_methods = torch.multiprocessing.get_all_start_methods()
439
+ if multiprocessing_context not in valid_start_methods:
440
+ raise ValueError(
441
+ "multiprocessing_context option "
442
+ f"should specify a valid start method in {valid_start_methods!r}, but got "
443
+ f"multiprocessing_context={multiprocessing_context!r}"
444
+ )
445
+ multiprocessing_context = torch.multiprocessing.get_context(
446
+ multiprocessing_context
447
+ )
448
+
449
+ if not isinstance(
450
+ multiprocessing_context, python_multiprocessing.context.BaseContext
451
+ ):
452
+ raise TypeError(
453
+ "multiprocessing_context option should be a valid context "
454
+ "object or a string specifying the start method, but got "
455
+ f"multiprocessing_context={multiprocessing_context}"
456
+ )
457
+ else:
458
+ raise ValueError(
459
+ "multiprocessing_context can only be used with "
460
+ "multi-process loading (num_workers > 0), but got "
461
+ f"num_workers={self.num_workers}"
462
+ )
463
+
464
+ self.__multiprocessing_context = multiprocessing_context
465
+
466
+ def __setattr__(self, attr, val):
467
+ if self.__initialized and attr in (
468
+ "batch_size",
469
+ "batch_sampler",
470
+ "sampler",
471
+ "drop_last",
472
+ "dataset",
473
+ "persistent_workers",
474
+ ):
475
+ raise ValueError(
476
+ f"{attr} attribute should not be set after {self.__class__.__name__} is initialized"
477
+ )
478
+
479
+ super().__setattr__(attr, val)
480
+
481
+ def __iter__(self) -> _BaseDataLoaderIter:
482
+ # When using a single worker the returned iterator should be
483
+ # created everytime to avoid resetting its state
484
+ # However, in the case of a multiple workers iterator
485
+ # the iterator is only created once in the lifetime of the
486
+ # DataLoader object so that workers can be reused
487
+ if self.persistent_workers and self.num_workers > 0:
488
+ if self._iterator is None:
489
+ self._iterator = self._get_iterator()
490
+ else:
491
+ self._iterator._reset(self)
492
+ return self._iterator
493
+ else:
494
+ return self._get_iterator()
495
+
496
+ @property
497
+ def _auto_collation(self):
498
+ return self.batch_sampler is not None
499
+
500
+ @property
501
+ def _index_sampler(self):
502
+ # The actual sampler used for generating indices for `_DatasetFetcher`
503
+ # (see _utils/fetch.py) to read data at each time. This would be
504
+ # `.batch_sampler` if in auto-collation mode, and `.sampler` otherwise.
505
+ # We can't change `.sampler` and `.batch_sampler` attributes for BC
506
+ # reasons.
507
+ if self._auto_collation:
508
+ return self.batch_sampler
509
+ else:
510
+ return self.sampler
511
+
512
+ def __len__(self) -> int:
513
+ if self._dataset_kind == _DatasetKind.Iterable:
514
+ # NOTE [ IterableDataset and __len__ ]
515
+ #
516
+ # For `IterableDataset`, `__len__` could be inaccurate when one naively
517
+ # does multi-processing data loading, since the samples will be duplicated.
518
+ # However, no real use case should be actually using that behavior, so
519
+ # it should count as a user error. We should generally trust user
520
+ # code to do the proper thing (e.g., configure each replica differently
521
+ # in `__iter__`), and give us the correct `__len__` if they choose to
522
+ # implement it (this will still throw if the dataset does not implement
523
+ # a `__len__`).
524
+ #
525
+ # To provide a further warning, we track if `__len__` was called on the
526
+ # `DataLoader`, save the returned value in `self._len_called`, and warn
527
+ # if the iterator ends up yielding more than this number of samples.
528
+
529
+ # Cannot statically verify that dataset is Sized
530
+ length = self._IterableDataset_len_called = len(self.dataset) # type: ignore[assignment, arg-type]
531
+ if (
532
+ self.batch_size is not None
533
+ ): # IterableDataset doesn't allow custom sampler or batch_sampler
534
+ from math import ceil
535
+
536
+ if self.drop_last:
537
+ length = length // self.batch_size
538
+ else:
539
+ length = ceil(length / self.batch_size)
540
+ return length
541
+ else:
542
+ return len(self._index_sampler)
543
+
544
+ def check_worker_number_rationality(self):
545
+ # This function check whether the dataloader's worker number is rational based on
546
+ # current system's resource. Current rule is that if the number of workers this
547
+ # Dataloader will create is bigger than the number of logical cpus that is allowed to
548
+ # use, than we will pop up a warning to let user pay attention.
549
+ #
550
+ # eg. If current system has 2 physical CPUs with 16 cores each. And each core support 2
551
+ # threads, then the total logical cpus here is 2 * 16 * 2 = 64. Let's say current
552
+ # DataLoader process can use half of them which is 32, then the rational max number of
553
+ # worker that initiated from this process is 32.
554
+ # Now, let's say the created DataLoader has num_works = 40, which is bigger than 32.
555
+ # So the warning message is triggered to notify the user to lower the worker number if
556
+ # necessary.
557
+ #
558
+ #
559
+ # [Note] Please note that this function repects `cpuset` only when os.sched_getaffinity is
560
+ # available (available in most of Linux system, but not OSX and Windows).
561
+ # When os.sched_getaffinity is not available, os.cpu_count() is called instead, but
562
+ # it doesn't repect cpuset.
563
+ # We don't take threading into account since each worker process is single threaded
564
+ # at this time.
565
+ #
566
+ # We don't set any threading flags (eg. OMP_NUM_THREADS, MKL_NUM_THREADS, etc)
567
+ # other than `torch.set_num_threads` to 1 in the worker process, if the passing
568
+ # in functions use 3rd party modules that rely on those threading flags to determine
569
+ # how many thread to create (eg. numpy, etc), then it is caller's responsibility to
570
+ # set those flags correctly.
571
+ def _create_warning_msg(num_worker_suggest, num_worker_created, cpuset_checked):
572
+ suggested_max_worker_msg = (
573
+ (
574
+ (
575
+ "Our suggested max number of worker in current system is {}{}, which is smaller "
576
+ "than what this DataLoader is going to create."
577
+ ).format(
578
+ num_worker_suggest,
579
+ (
580
+ ""
581
+ if cpuset_checked
582
+ else " (`cpuset` is not taken into account)"
583
+ ),
584
+ )
585
+ )
586
+ if num_worker_suggest is not None
587
+ else (
588
+ "DataLoader is not able to compute a suggested max number of worker in current system."
589
+ )
590
+ )
591
+
592
+ warn_msg = (
593
+ f"This DataLoader will create {num_worker_created} worker processes in total. {suggested_max_worker_msg} "
594
+ "Please be aware that excessive worker creation might get DataLoader running slow or even freeze, "
595
+ "lower the worker number to avoid potential slowness/freeze if necessary."
596
+ )
597
+ return warn_msg
598
+
599
+ if not self.num_workers or self.num_workers == 0:
600
+ return
601
+
602
+ # try to compute a suggested max number of worker based on system's resource
603
+ max_num_worker_suggest = None
604
+ cpuset_checked = False
605
+ if hasattr(os, "sched_getaffinity"):
606
+ try:
607
+ max_num_worker_suggest = len(os.sched_getaffinity(0))
608
+ cpuset_checked = True
609
+ except Exception:
610
+ pass
611
+ if max_num_worker_suggest is None:
612
+ # os.cpu_count() could return Optional[int]
613
+ # get cpu count first and check None in order to satisfy mypy check
614
+ cpu_count = os.cpu_count()
615
+ if cpu_count is not None:
616
+ max_num_worker_suggest = cpu_count
617
+
618
+ if max_num_worker_suggest is None:
619
+ warnings.warn(
620
+ _create_warning_msg(
621
+ max_num_worker_suggest, self.num_workers, cpuset_checked
622
+ )
623
+ )
624
+ return
625
+
626
+ if self.num_workers > max_num_worker_suggest:
627
+ warnings.warn(
628
+ _create_warning_msg(
629
+ max_num_worker_suggest, self.num_workers, cpuset_checked
630
+ )
631
+ )
632
+
633
+
634
+ class _BaseDataLoaderIter:
635
+ def __init__(self, loader: DataLoader) -> None:
636
+ self._dataset = loader.dataset
637
+ self._shared_seed = None
638
+ self._pg = None
639
+ if isinstance(self._dataset, IterDataPipe):
640
+ if dist.is_available() and dist.is_initialized():
641
+ self._pg = dist.new_group(backend="gloo")
642
+ self._shared_seed = _share_dist_seed(loader.generator, self._pg)
643
+ shared_rng = torch.Generator()
644
+ shared_rng.manual_seed(self._shared_seed)
645
+ self._dataset = torch.utils.data.graph_settings.apply_random_seed(
646
+ self._dataset, shared_rng
647
+ )
648
+ self._dataset_kind = loader._dataset_kind
649
+ self._IterableDataset_len_called = loader._IterableDataset_len_called
650
+ self._auto_collation = loader._auto_collation
651
+ self._drop_last = loader.drop_last
652
+ self._index_sampler = loader._index_sampler
653
+ self._num_workers = loader.num_workers
654
+ ws, rank = _get_distributed_settings()
655
+ self._world_size = ws
656
+ self._rank = rank
657
+ # If pin_memory_device not set, default behaviour is current accelerator.
658
+ # If pin_memory_device is set but pin_memory is not set, the default
659
+ # behaviour false.
660
+ if len(loader.pin_memory_device) == 0:
661
+ if loader.pin_memory and not torch.accelerator.is_available():
662
+ warn_msg = (
663
+ "'pin_memory' argument is set as true but no accelerator is found, "
664
+ "then device pinned memory won't be used."
665
+ )
666
+ warnings.warn(warn_msg)
667
+
668
+ self._pin_memory = loader.pin_memory and torch.accelerator.is_available()
669
+ self._pin_memory_device = None
670
+ # Currently, pin_memory would raise error on the MPS backend (see
671
+ # https://github.com/pytorch/pytorch/issues/86060), so forcibly
672
+ # disable pin_memory on MPS. Remove this restriction once pinned
673
+ # memory allocation for MPS is fixed.
674
+ if (
675
+ self._pin_memory
676
+ and (acc := torch.accelerator.current_accelerator()) is not None
677
+ and acc.type == "mps"
678
+ ):
679
+ self._pin_memory = False
680
+ warn_msg = (
681
+ "'pin_memory' argument is set as true but not supported on MPS now, "
682
+ "then device pinned memory won't be used."
683
+ )
684
+ warnings.warn(warn_msg)
685
+ else:
686
+ if not loader.pin_memory:
687
+ warn_msg = (
688
+ "'pin_memory_device' is set but 'pin_memory' argument is not set, "
689
+ "then device pinned memory won't be used."
690
+ "please set 'pin_memory' to true, if you need to use the device pin memory"
691
+ )
692
+ warnings.warn(warn_msg)
693
+
694
+ self._pin_memory = loader.pin_memory
695
+ self._pin_memory_device = loader.pin_memory_device
696
+ self._timeout = loader.timeout
697
+ self._collate_fn = loader.collate_fn
698
+ self._sampler_iter = iter(self._index_sampler)
699
+ self._base_seed = (
700
+ torch.empty((), dtype=torch.int64)
701
+ .random_(generator=loader.generator)
702
+ .item()
703
+ )
704
+ self._persistent_workers = loader.persistent_workers
705
+ self._num_yielded = 0
706
+ self._profile_name = f"enumerate(DataLoader)#{self.__class__.__name__}.__next__"
707
+
708
+ def __iter__(self) -> Self:
709
+ return self
710
+
711
+ def _reset(self, loader, first_iter=False):
712
+ self._sampler_iter = iter(self._index_sampler)
713
+ self._num_yielded = 0
714
+ self._IterableDataset_len_called = loader._IterableDataset_len_called
715
+ if isinstance(self._dataset, IterDataPipe):
716
+ self._shared_seed = _share_dist_seed(loader.generator, self._pg)
717
+ shared_rng = torch.Generator()
718
+ shared_rng.manual_seed(self._shared_seed)
719
+ self._dataset = torch.utils.data.graph_settings.apply_random_seed(
720
+ self._dataset, shared_rng
721
+ )
722
+
723
+ def _next_index(self):
724
+ return next(self._sampler_iter) # may raise StopIteration
725
+
726
+ def _next_data(self):
727
+ raise NotImplementedError
728
+
729
+ def __next__(self) -> Any:
730
+ with torch.autograd.profiler.record_function(self._profile_name):
731
+ if self._sampler_iter is None:
732
+ # TODO(https://github.com/pytorch/pytorch/issues/76750)
733
+ self._reset() # type: ignore[call-arg]
734
+ data = self._next_data()
735
+ self._num_yielded += 1
736
+ if (
737
+ self._dataset_kind == _DatasetKind.Iterable
738
+ and self._IterableDataset_len_called is not None
739
+ and self._num_yielded > self._IterableDataset_len_called
740
+ ):
741
+ warn_msg = (
742
+ f"Length of IterableDataset {self._dataset} was reported to be {self._IterableDataset_len_called}"
743
+ f"(when accessing len(dataloader)), but {self._num_yielded} samples have been fetched. "
744
+ )
745
+ if self._num_workers > 0:
746
+ warn_msg += (
747
+ "For multiprocessing data-loading, this could be caused by not properly configuring the "
748
+ "IterableDataset replica at each worker. Please see "
749
+ "https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples."
750
+ )
751
+ warnings.warn(warn_msg)
752
+ return data
753
+
754
+ def __len__(self) -> int:
755
+ return len(self._index_sampler)
756
+
757
+ def __getstate__(self):
758
+ # TODO: add limited pickling support for sharing an iterator
759
+ # across multiple threads for HOGWILD.
760
+ # Probably the best way to do this is by moving the sample pushing
761
+ # to a separate thread and then just sharing the data queue
762
+ # but signalling the end is tricky without a non-blocking API
763
+ raise NotImplementedError("{} cannot be pickled", self.__class__.__name__)
764
+
765
+
766
+ class _SingleProcessDataLoaderIter(_BaseDataLoaderIter):
767
+ def __init__(self, loader):
768
+ super().__init__(loader)
769
+ assert self._timeout == 0
770
+ assert self._num_workers == 0
771
+
772
+ # Adds forward compatibilities so classic DataLoader can work with DataPipes:
773
+ # Taking care of distributed sharding
774
+ if isinstance(self._dataset, (IterDataPipe, MapDataPipe)):
775
+ # For BC, use default SHARDING_PRIORITIES
776
+ torch.utils.data.graph_settings.apply_sharding(
777
+ self._dataset, self._world_size, self._rank
778
+ )
779
+
780
+ self._dataset_fetcher = _DatasetKind.create_fetcher(
781
+ self._dataset_kind,
782
+ self._dataset,
783
+ self._auto_collation,
784
+ self._collate_fn,
785
+ self._drop_last,
786
+ )
787
+
788
+ def _next_data(self):
789
+ index = self._next_index() # may raise StopIteration
790
+ data = self._dataset_fetcher.fetch(index) # may raise StopIteration
791
+ if self._pin_memory:
792
+ data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)
793
+ return data
794
+
795
+
796
+ class _MultiProcessingDataLoaderIter(_BaseDataLoaderIter):
797
+ r"""Iterates once over the DataLoader's dataset, as specified by the sampler."""
798
+
799
+ # NOTE [ Data Loader Multiprocessing Shutdown Logic ]
800
+ #
801
+ # Preliminary:
802
+ #
803
+ # Our data model looks like this (queues are indicated with curly brackets):
804
+ #
805
+ # main process ||
806
+ # | ||
807
+ # {index_queue} ||
808
+ # | ||
809
+ # worker processes || DATA
810
+ # | ||
811
+ # {worker_result_queue} || FLOW
812
+ # | ||
813
+ # pin_memory_thread of main process || DIRECTION
814
+ # | ||
815
+ # {data_queue} ||
816
+ # | ||
817
+ # data output \/
818
+ #
819
+ # P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if
820
+ # `pin_memory=False`.
821
+ #
822
+ #
823
+ # Terminating multiprocessing logic requires very careful design. In
824
+ # particular, we need to make sure that
825
+ #
826
+ # 1. The iterator gracefully exits the workers when its last reference is
827
+ # gone or it is depleted.
828
+ #
829
+ # In this case, the workers should be gracefully exited because the
830
+ # main process may still need to continue to run, and we want cleaning
831
+ # up code in the workers to be executed (e.g., releasing GPU memory).
832
+ # Naturally, we implement the shutdown logic in `__del__` of
833
+ # DataLoaderIterator.
834
+ #
835
+ # We delay the discussion on the logic in this case until later.
836
+ #
837
+ # 2. The iterator exits the workers when the loader process and/or worker
838
+ # processes exits normally or with error.
839
+ #
840
+ # We set all workers and `pin_memory_thread` to have `daemon=True`.
841
+ #
842
+ # You may ask, why can't we make the workers non-daemonic, and
843
+ # gracefully exit using the same logic as we have in `__del__` when the
844
+ # iterator gets deleted (see 1 above)?
845
+ #
846
+ # First of all, `__del__` is **not** guaranteed to be called when
847
+ # interpreter exits. Even if it is called, by the time it executes,
848
+ # many Python core library resources may already be freed, and even
849
+ # simple things like acquiring an internal lock of a queue may hang.
850
+ # Therefore, in this case, we actually need to prevent `__del__` from
851
+ # being executed, and rely on the automatic termination of daemonic
852
+ # children.
853
+ #
854
+ # Thus, we register an `atexit` hook that sets a global flag
855
+ # `_utils.python_exit_status`. Since `atexit` hooks are executed in the
856
+ # reverse order of registration, we are guaranteed that this flag is
857
+ # set before library resources we use are freed (which, at least in
858
+ # CPython, is done via an `atexit` handler defined in
859
+ # `multiprocessing/util.py`
860
+ # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/util.py#L320-L362
861
+ # registered when an object requiring this mechanism is first
862
+ # created, e.g., `mp.Queue`
863
+ # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/context.py#L100-L103
864
+ # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/queues.py#L29
865
+ # )
866
+ #
867
+ # So in `__del__`, we check if `_utils.python_exit_status` is set or
868
+ # `None` (freed), and perform no-op if so.
869
+ #
870
+ # However, simply letting library clean-up codes run can also be bad,
871
+ # because such codes (i.e., `multiprocessing.util._exit_function()`)
872
+ # include join putting threads for `mp.Queue`, which can be blocking.
873
+ # Hence, the main process putting threads are called with
874
+ # `cancel_join_thread` at creation. See later section
875
+ # [ 3b. A process won't hang when putting into a queue; ]
876
+ # for more details.
877
+ #
878
+ # Here are two example cases where library clean-up codes can run
879
+ # before `__del__` is called:
880
+ #
881
+ # 1. If we hold onto a reference to the iterator, it more often
882
+ # than not tries to do `multiprocessing` library cleaning before
883
+ # clearing the alive referenced objects (https://github.com/pytorch/pytorch/issues/48666)
884
+ # and thus prevents our cleaning-up code to run first.
885
+ #
886
+ # 2. A similar issue araises when a `DataLoader` is used in a subprocess.
887
+ # When a process ends, it shuts the all its daemonic children
888
+ # down with a SIGTERM (instead of joining them without a timeout).
889
+ # Simiarly for threads, but by a different mechanism. This fact,
890
+ # together with a few implementation details of multiprocessing, forces
891
+ # us to make workers daemonic. All of our problems arise when a
892
+ # DataLoader is used in a subprocess, and are caused by multiprocessing
893
+ # code which looks more or less like this:
894
+ #
895
+ # try:
896
+ # your_function_using_a_dataloader()
897
+ # finally:
898
+ # multiprocessing.util._exit_function()
899
+ #
900
+ # The joining/termination mentioned above happens inside
901
+ # `_exit_function()`. Now, if `your_function_using_a_dataloader()`
902
+ # throws, the stack trace stored in the exception will prevent the
903
+ # frame which uses `DataLoaderIter` to be freed. If the frame has any
904
+ # reference to the `DataLoaderIter` (e.g., in a method of the iter),
905
+ # its `__del__`, which starts the shutdown procedure, will not be
906
+ # called. That, in turn, means that workers aren't notified. Attempting
907
+ # to join in `_exit_function` will then result in a hang.
908
+ #
909
+ # For context, `_exit_function` is also registered as an `atexit` call.
910
+ # So it is unclear to me (@ssnl) why this is needed in a finally block.
911
+ # The code dates back to 2008 and there is no comment on the original
912
+ # PEP 371 or patch https://bugs.python.org/issue3050 (containing both
913
+ # the finally block and the `atexit` registration) that explains this.
914
+ #
915
+ #
916
+ # Finally, another choice is to just shutdown workers with logic in 1
917
+ # above whenever we see an error in `next`. This isn't ideal because
918
+ # a. It prevents users from using try-catch to resume data loading.
919
+ # b. It doesn't prevent hanging if users have references to the
920
+ # iterator.
921
+ #
922
+ # 3. All processes exit if any of them die unexpectedly by fatal signals.
923
+ #
924
+ # As shown above, the workers are set as daemonic children of the main
925
+ # process. However, automatic cleaning-up of such child processes only
926
+ # happens if the parent process exits gracefully (e.g., not via fatal
927
+ # signals like SIGKILL). So we must ensure that each process will exit
928
+ # even the process that should send/receive data to/from it were
929
+ # killed, i.e.,
930
+ #
931
+ # a. A process won't hang when getting from a queue.
932
+ #
933
+ # Even with carefully designed data dependencies (i.e., a `put()`
934
+ # always corresponding to a `get()`), hanging on `get()` can still
935
+ # happen when data in queue is corrupted (e.g., due to
936
+ # `cancel_join_thread` or unexpected exit).
937
+ #
938
+ # For child exit, we set a timeout whenever we try to get data
939
+ # from `data_queue`, and check the workers' status on each timeout
940
+ # and error.
941
+ # See `_DataLoaderiter._get_batch()` and
942
+ # `_DataLoaderiter._try_get_data()` for details.
943
+ #
944
+ # Additionally, for child exit on non-Windows platforms, we also
945
+ # register a SIGCHLD handler (which is supported on Windows) on
946
+ # the main process, which checks if any of the workers fail in the
947
+ # (Python) handler. This is more efficient and faster in detecting
948
+ # worker failures, compared to only using the above mechanism.
949
+ # See `DataLoader.cpp` and `_utils/signal_handling.py` for details.
950
+ #
951
+ # For `.get()` calls where the sender(s) is not the workers, we
952
+ # guard them with timeouts, and check the status of the sender
953
+ # when timeout happens:
954
+ # + in the workers, the `_utils.worker.ManagerWatchdog` class
955
+ # checks the status of the main process.
956
+ # + if `pin_memory=True`, when getting from `pin_memory_thread`,
957
+ # check `pin_memory_thread` status periodically until `.get()`
958
+ # returns or see that `pin_memory_thread` died.
959
+ #
960
+ # b. A process won't hang when putting into a queue;
961
+ #
962
+ # We use `mp.Queue` which has a separate background thread to put
963
+ # objects from an unbounded buffer array. The background thread is
964
+ # daemonic and usually automatically joined when the process
965
+ # *exits*.
966
+ #
967
+ # In case that the receiver has ended abruptly while
968
+ # reading from the pipe, the join will hang forever. The usual
969
+ # solution for this in Python is calling `q.cancel_join_thread`,
970
+ # which prevents automatically joining it when finalizing
971
+ # (exiting).
972
+ #
973
+ # Nonetheless, `cancel_join_thread` must only be called when the
974
+ # queue is **not** going to be read from or write into by another
975
+ # process, because it may hold onto a lock or leave corrupted data
976
+ # in the queue, leading other readers/writers to hang.
977
+ #
978
+ # Hence,
979
+ # + For worker processes, we only do so (for their output
980
+ # queues, i.e., `worker_result_queue`) before exiting.
981
+ # + For `pin_memory_thread`, its output queue `data_queue` is a
982
+ # `queue.Queue` that does blocking `put` if the queue is full.
983
+ # So there is no above problem, but as a result, in
984
+ # `_pin_memory_loop`, we do need to wrap the `put` in a loop
985
+ # that breaks not only upon success, but also when the main
986
+ # process stops reading, i.e., is shutting down.
987
+ # + For loader process, we `cancel_join_thread()` for all
988
+ # `_index_queues` because the whole purpose of workers and
989
+ # `pin_memory_thread` is to serve the loader process. If
990
+ # loader process is already exiting, we don't really care if
991
+ # the queues are corrupted.
992
+ #
993
+ #
994
+ # Now let's get back to 1:
995
+ # how we gracefully exit the workers when the last reference to the
996
+ # iterator is gone.
997
+ #
998
+ # To achieve this, we implement the following logic along with the design
999
+ # choices mentioned above:
1000
+ #
1001
+ # `workers_done_event`:
1002
+ # A `multiprocessing.Event` shared among the main process and all worker
1003
+ # processes. This is used to signal the workers that the iterator is
1004
+ # shutting down. After it is set, they will not send processed data to
1005
+ # queues anymore, and only wait for the final `None` before exiting.
1006
+ # `done_event` isn't strictly needed. I.e., we can just check for `None`
1007
+ # from the input queue, but it allows us to skip wasting resources
1008
+ # processing data if we are already shutting down.
1009
+ #
1010
+ # `pin_memory_thread_done_event`:
1011
+ # A `threading.Event` for a similar purpose to that of
1012
+ # `workers_done_event`, but is for the `pin_memory_thread`. The reason
1013
+ # that separate events are needed is that `pin_memory_thread` reads from
1014
+ # the output queue of the workers. But the workers, upon seeing that
1015
+ # `workers_done_event` is set, only wants to see the final `None`, and is
1016
+ # not required to flush all data in the output queue (e.g., it may call
1017
+ # `cancel_join_thread` on that queue if its `IterableDataset` iterator
1018
+ # happens to exhaust coincidentally, which is out of the control of the
1019
+ # main process). Thus, since we will exit `pin_memory_thread` before the
1020
+ # workers (see below), two separete events are used.
1021
+ #
1022
+ # NOTE: In short, the protocol is that the main process will set these
1023
+ # `done_event`s and then the corresponding processes/threads a `None`,
1024
+ # and that they may exit at any time after receiving the `None`.
1025
+ #
1026
+ # NOTE: Using `None` as the final signal is valid, since normal data will
1027
+ # always be a 2-tuple with the 1st element being the index of the data
1028
+ # transferred (different from dataset index/key), and the 2nd being
1029
+ # either the dataset key or the data sample (depending on which part
1030
+ # of the data model the queue is at).
1031
+ #
1032
+ # [ worker processes ]
1033
+ # While loader process is alive:
1034
+ # Get from `index_queue`.
1035
+ # If get anything else,
1036
+ # Check `workers_done_event`.
1037
+ # If set, continue to next iteration
1038
+ # i.e., keep getting until see the `None`, then exit.
1039
+ # Otherwise, process data:
1040
+ # If is fetching from an `IterableDataset` and the iterator
1041
+ # is exhausted, send an `_IterableDatasetStopIteration`
1042
+ # object to signal iteration end. The main process, upon
1043
+ # receiving such an object, will send `None` to this
1044
+ # worker and not use the corresponding `index_queue`
1045
+ # anymore.
1046
+ # If timed out,
1047
+ # No matter `workers_done_event` is set (still need to see `None`)
1048
+ # or not, must continue to next iteration.
1049
+ # (outside loop)
1050
+ # If `workers_done_event` is set, (this can be False with `IterableDataset`)
1051
+ # `data_queue.cancel_join_thread()`. (Everything is ending here:
1052
+ # main process won't read from it;
1053
+ # other workers will also call
1054
+ # `cancel_join_thread`.)
1055
+ #
1056
+ # [ pin_memory_thread ]
1057
+ # # No need to check main thread. If this thread is alive, the main loader
1058
+ # # thread must be alive, because this thread is set as daemonic.
1059
+ # While `pin_memory_thread_done_event` is not set:
1060
+ # Get from `worker_result_queue`.
1061
+ # If timed out, continue to get in the next iteration.
1062
+ # Otherwise, process data.
1063
+ # While `pin_memory_thread_done_event` is not set:
1064
+ # Put processed data to `data_queue` (a `queue.Queue` with blocking put)
1065
+ # If timed out, continue to put in the next iteration.
1066
+ # Otherwise, break, i.e., continuing to the out loop.
1067
+ #
1068
+ # NOTE: we don't check the status of the main thread because
1069
+ # 1. if the process is killed by fatal signal, `pin_memory_thread`
1070
+ # ends.
1071
+ # 2. in other cases, either the cleaning-up in __del__ or the
1072
+ # automatic exit of daemonic thread will take care of it.
1073
+ # This won't busy-wait either because `.get(timeout)` does not
1074
+ # busy-wait.
1075
+ #
1076
+ # [ main process ]
1077
+ # In the DataLoader Iter's `__del__`
1078
+ # b. Exit `pin_memory_thread`
1079
+ # i. Set `pin_memory_thread_done_event`.
1080
+ # ii Put `None` in `worker_result_queue`.
1081
+ # iii. Join the `pin_memory_thread`.
1082
+ # iv. `worker_result_queue.cancel_join_thread()`.
1083
+ #
1084
+ # c. Exit the workers.
1085
+ # i. Set `workers_done_event`.
1086
+ # ii. Put `None` in each worker's `index_queue`.
1087
+ # iii. Join the workers.
1088
+ # iv. Call `.cancel_join_thread()` on each worker's `index_queue`.
1089
+ #
1090
+ # NOTE: (c) is better placed after (b) because it may leave corrupted
1091
+ # data in `worker_result_queue`, which `pin_memory_thread`
1092
+ # reads from, in which case the `pin_memory_thread` can only
1093
+ # happen at timing out, which is slow. Nonetheless, same thing
1094
+ # happens if a worker is killed by signal at unfortunate times,
1095
+ # but in other cases, we are better off having a non-corrupted
1096
+ # `worker_result_queue` for `pin_memory_thread`.
1097
+ #
1098
+ # NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b)
1099
+ # can be omitted
1100
+ #
1101
+ # NB: `done_event`s isn't strictly needed. E.g., we can just check for
1102
+ # `None` from `index_queue`, but it allows us to skip wasting resources
1103
+ # processing indices already in `index_queue` if we are already shutting
1104
+ # down.
1105
+
1106
+ def __init__(self, loader):
1107
+ super().__init__(loader)
1108
+
1109
+ self._prefetch_factor = loader.prefetch_factor
1110
+ self._in_order = loader.in_order
1111
+
1112
+ assert self._num_workers > 0
1113
+ assert self._prefetch_factor > 0
1114
+
1115
+ if loader.multiprocessing_context is None:
1116
+ multiprocessing_context = torch.multiprocessing
1117
+ else:
1118
+ multiprocessing_context = loader.multiprocessing_context
1119
+
1120
+ self._worker_init_fn = loader.worker_init_fn
1121
+
1122
+ # Adds forward compatibilities so classic DataLoader can work with DataPipes:
1123
+ # Additional worker init function will take care of sharding in MP and Distributed
1124
+ if isinstance(self._dataset, (IterDataPipe, MapDataPipe)):
1125
+ self._worker_init_fn = functools.partial(
1126
+ _sharding_worker_init_fn,
1127
+ self._worker_init_fn,
1128
+ self._world_size,
1129
+ self._rank,
1130
+ )
1131
+
1132
+ # No certainty which module multiprocessing_context is
1133
+ self._worker_result_queue = multiprocessing_context.Queue() # type: ignore[var-annotated]
1134
+ self._worker_pids_set = False
1135
+ self._shutdown = False
1136
+ self._workers_done_event = multiprocessing_context.Event()
1137
+
1138
+ self._index_queues = []
1139
+ self._workers = []
1140
+ for i in range(self._num_workers):
1141
+ # No certainty which module multiprocessing_context is
1142
+ index_queue = multiprocessing_context.Queue() # type: ignore[var-annotated]
1143
+ # Need to `cancel_join_thread` here!
1144
+ # See sections (2) and (3b) above.
1145
+ index_queue.cancel_join_thread()
1146
+ w = multiprocessing_context.Process(
1147
+ target=_utils.worker._worker_loop,
1148
+ args=(
1149
+ self._dataset_kind,
1150
+ self._dataset,
1151
+ index_queue,
1152
+ self._worker_result_queue,
1153
+ self._workers_done_event,
1154
+ self._auto_collation,
1155
+ self._collate_fn,
1156
+ self._drop_last,
1157
+ self._base_seed,
1158
+ self._worker_init_fn,
1159
+ i,
1160
+ self._num_workers,
1161
+ self._persistent_workers,
1162
+ self._shared_seed,
1163
+ ),
1164
+ )
1165
+ w.daemon = True
1166
+ # NB: Process.start() actually take some time as it needs to
1167
+ # start a process and pass the arguments over via a pipe.
1168
+ # Therefore, we only add a worker to self._workers list after
1169
+ # it started, so that we do not call .join() if program dies
1170
+ # before it starts, and __del__ tries to join but will get:
1171
+ # AssertionError: can only join a started process.
1172
+ w.start()
1173
+ self._index_queues.append(index_queue)
1174
+ self._workers.append(w)
1175
+
1176
+ if self._pin_memory:
1177
+ self._pin_memory_thread_done_event = threading.Event()
1178
+
1179
+ # Queue is not type-annotated
1180
+ self._data_queue = queue.Queue() # type: ignore[var-annotated]
1181
+ current_device = -1
1182
+ if self._pin_memory_device == "cuda":
1183
+ current_device = torch.cuda.current_device()
1184
+ elif self._pin_memory_device == "xpu":
1185
+ current_device = torch.xpu.current_device()
1186
+ elif self._pin_memory_device == torch._C._get_privateuse1_backend_name():
1187
+ custom_device_mod = getattr(
1188
+ torch, torch._C._get_privateuse1_backend_name()
1189
+ )
1190
+ current_device = custom_device_mod.current_device()
1191
+ elif self._pin_memory_device is None:
1192
+ current_device = torch.accelerator.current_device_index()
1193
+ pin_memory_thread = threading.Thread(
1194
+ target=_utils.pin_memory._pin_memory_loop,
1195
+ args=(
1196
+ self._worker_result_queue,
1197
+ self._data_queue,
1198
+ current_device,
1199
+ self._pin_memory_thread_done_event,
1200
+ self._pin_memory_device,
1201
+ ),
1202
+ )
1203
+ pin_memory_thread.daemon = True
1204
+ pin_memory_thread.start()
1205
+ # Similar to workers (see comment above), we only register
1206
+ # pin_memory_thread once it is started.
1207
+ self._pin_memory_thread = pin_memory_thread
1208
+ else:
1209
+ self._data_queue = self._worker_result_queue # type: ignore[assignment]
1210
+
1211
+ # In some rare cases, persistent workers (daemonic processes)
1212
+ # would be terminated before `__del__` of iterator is invoked
1213
+ # when main process exits
1214
+ # It would cause failure when pin_memory_thread tries to read
1215
+ # corrupted data from worker_result_queue
1216
+ # atexit is used to shutdown thread and child processes in the
1217
+ # right sequence before main process exits
1218
+ if self._persistent_workers and self._pin_memory:
1219
+ import atexit
1220
+
1221
+ for w in self._workers:
1222
+ atexit.register(_MultiProcessingDataLoaderIter._clean_up_worker, w)
1223
+
1224
+ # .pid can be None only before process is spawned (not the case, so ignore)
1225
+ _utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self._workers)) # type: ignore[misc]
1226
+ _utils.signal_handling._set_SIGCHLD_handler()
1227
+ self._worker_pids_set = True
1228
+ self._reset(loader, first_iter=True)
1229
+
1230
+ def _reset(self, loader, first_iter=False):
1231
+ super()._reset(loader, first_iter)
1232
+ self._send_idx = 0 # idx of the next task to be sent to workers
1233
+ self._rcvd_idx = 0 # idx of the next task to be returned in __next__
1234
+ # information about data not yet yielded, i.e., tasks w/ indices in range [rcvd_idx, send_idx).
1235
+ # map: task idx => - (worker_id,) if data isn't fetched (outstanding)
1236
+ # \ (worker_id, data) if data is already fetched (out-of-order)
1237
+ self._task_info = {}
1238
+ self._tasks_outstanding = (
1239
+ 0 # always equal to count(v for v in task_info.values() if len(v) == 1)
1240
+ )
1241
+ # A list of booleans representing whether each worker still has work to
1242
+ # do, i.e., not having exhausted its iterable dataset object. It always
1243
+ # contains all `True`s if not using an iterable-style dataset
1244
+ # (i.e., if kind != Iterable).
1245
+ # Not that this indicates that a worker still has work to do *for this epoch*.
1246
+ # It does not mean that a worker is dead. In case of `_persistent_workers`,
1247
+ # the worker will be reset to available in the next epoch.
1248
+ self._workers_status = [True for i in range(self._num_workers)]
1249
+ # A list of integers representing how many tasks are outstanding for each worker
1250
+ # Incremented when a task is dispatched to the worker
1251
+ # Decremented when that data has been given to the main thread
1252
+ # Each worker should have at most self._prefetch_factor tasks outstanding
1253
+ self._workers_num_tasks = [0 for i in range(self._num_workers)]
1254
+ # Reset the worker queue cycle so it resumes next epoch at worker 0
1255
+ self._worker_queue_idx_cycle = itertools.cycle(range(self._num_workers))
1256
+ # We resume the prefetching in case it was enabled
1257
+ if not first_iter:
1258
+ for idx in range(self._num_workers):
1259
+ self._index_queues[idx].put(
1260
+ _utils.worker._ResumeIteration(self._shared_seed)
1261
+ )
1262
+ resume_iteration_cnt = self._num_workers
1263
+ while resume_iteration_cnt > 0:
1264
+ return_idx, return_data = self._get_data()
1265
+ if isinstance(return_idx, _utils.worker._ResumeIteration):
1266
+ assert return_data is None
1267
+ resume_iteration_cnt -= 1
1268
+ # prime the prefetch loop
1269
+ for _ in range(self._prefetch_factor * self._num_workers):
1270
+ self._try_put_index()
1271
+
1272
+ def _try_get_data(self, timeout=_utils.MP_STATUS_CHECK_INTERVAL):
1273
+ # Tries to fetch data from `self._data_queue` once for a given timeout.
1274
+ # This can also be used as inner loop of fetching without timeout, with
1275
+ # the sender status as the loop condition.
1276
+ #
1277
+ # This raises a `RuntimeError` if any worker died expectedly. This error
1278
+ # can come from either the SIGCHLD handler in `_utils/signal_handling.py`
1279
+ # (only for non-Windows platforms), or the manual check below on errors
1280
+ # and timeouts.
1281
+ #
1282
+ # Returns a 2-tuple:
1283
+ # (bool: whether successfully get data, any: data if successful else None)
1284
+ try:
1285
+ data = self._data_queue.get(timeout=timeout)
1286
+ return (True, data)
1287
+ except Exception as e:
1288
+ # At timeout and error, we manually check whether any worker has
1289
+ # failed. Note that this is the only mechanism for Windows to detect
1290
+ # worker failures.
1291
+ failed_workers = []
1292
+ for worker_id, w in enumerate(self._workers):
1293
+ if self._workers_status[worker_id] and not w.is_alive():
1294
+ failed_workers.append(w)
1295
+ self._mark_worker_as_unavailable(worker_id)
1296
+ if len(failed_workers) > 0:
1297
+ pids_str = ", ".join(str(w.pid) for w in failed_workers)
1298
+ raise RuntimeError(
1299
+ f"DataLoader worker (pid(s) {pids_str}) exited unexpectedly"
1300
+ ) from e
1301
+ if isinstance(e, queue.Empty):
1302
+ return (False, None)
1303
+
1304
+ import errno
1305
+ import tempfile
1306
+
1307
+ try:
1308
+ # Raise an exception if we are this close to the FDs limit.
1309
+ # Apparently, trying to open only one file is not a sufficient
1310
+ # test.
1311
+ # See NOTE [ DataLoader on Linux and open files limit ]
1312
+ fds_limit_margin = 10
1313
+ [tempfile.NamedTemporaryFile() for i in range(fds_limit_margin)]
1314
+ except OSError as e:
1315
+ if e.errno == errno.EMFILE:
1316
+ raise RuntimeError(
1317
+ "Too many open files. Communication with the"
1318
+ " workers is no longer possible. Please increase the"
1319
+ " limit using `ulimit -n` in the shell or change the"
1320
+ " sharing strategy by calling"
1321
+ " `torch.multiprocessing.set_sharing_strategy('file_system')`"
1322
+ " at the beginning of your code"
1323
+ ) from None
1324
+ raise
1325
+
1326
+ # NOTE [ DataLoader on Linux and open files limit ]
1327
+ #
1328
+ # On Linux when DataLoader is used with multiprocessing we pass the data between
1329
+ # the root process and the workers through SHM files. We remove those files from
1330
+ # the filesystem as soon as they are created and keep them alive by
1331
+ # passing around their file descriptors through AF_UNIX sockets. (See
1332
+ # docs/source/multiprocessing.rst and 'Multiprocessing Technical Notes` in
1333
+ # the wiki (https://github.com/pytorch/pytorch/wiki).)
1334
+ #
1335
+ # This sometimes leads us to exceeding the open files limit. When that happens,
1336
+ # and the offending file descriptor is coming over a socket, the `socket` Python
1337
+ # package silently strips the file descriptor from the message, setting only the
1338
+ # `MSG_CTRUNC` flag (which might be a bit misleading since the manpage says that
1339
+ # it _indicates that some control data were discarded due to lack of space in
1340
+ # the buffer for ancillary data_). This might reflect the C implementation of
1341
+ # AF_UNIX sockets.
1342
+ #
1343
+ # This behaviour can be reproduced with the script and instructions at the
1344
+ # bottom of this note.
1345
+ #
1346
+ # When that happens, the standard Python `multiprocessing` (and not
1347
+ # `torch.multiprocessing`) raises a `RuntimeError: received 0 items of ancdata`
1348
+ #
1349
+ # Sometimes, instead of the FD being stripped, you may get an `OSError:
1350
+ # Too many open files`, both in the script below and in DataLoader. However,
1351
+ # this is rare and seems to be nondeterministic.
1352
+ #
1353
+ #
1354
+ # #!/usr/bin/env python3
1355
+ # import sys
1356
+ # import socket
1357
+ # import os
1358
+ # import array
1359
+ # import shutil
1360
+ # import socket
1361
+ #
1362
+ #
1363
+ # if len(sys.argv) != 4:
1364
+ # print("Usage: ", sys.argv[0], " tmp_dirname iteration (send|recv)")
1365
+ # sys.exit(1)
1366
+ #
1367
+ # if __name__ == '__main__':
1368
+ # dirname = sys.argv[1]
1369
+ # sock_path = dirname + "/sock"
1370
+ # iterations = int(sys.argv[2])
1371
+ # def dummy_path(i):
1372
+ # return dirname + "/" + str(i) + ".dummy"
1373
+ #
1374
+ #
1375
+ # if sys.argv[3] == 'send':
1376
+ # while not os.path.exists(sock_path):
1377
+ # pass
1378
+ # client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
1379
+ # client.connect(sock_path)
1380
+ # for i in range(iterations):
1381
+ # fd = os.open(dummy_path(i), os.O_WRONLY | os.O_CREAT)
1382
+ # ancdata = array.array('i', [fd])
1383
+ # msg = bytes([i % 256])
1384
+ # print("Sending fd ", fd, " (iteration #", i, ")")
1385
+ # client.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ancdata)])
1386
+ #
1387
+ #
1388
+ # else:
1389
+ # assert sys.argv[3] == 'recv'
1390
+ #
1391
+ # if os.path.exists(dirname):
1392
+ # raise Exception("Directory exists")
1393
+ #
1394
+ # os.mkdir(dirname)
1395
+ #
1396
+ # print("Opening socket...")
1397
+ # server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
1398
+ # server.bind(sock_path)
1399
+ #
1400
+ # print("Listening...")
1401
+ # for i in range(iterations):
1402
+ # a = array.array('i')
1403
+ # msg, ancdata, flags, addr = server.recvmsg(1, socket.CMSG_SPACE(a.itemsize))
1404
+ # assert(len(ancdata) == 1)
1405
+ # cmsg_level, cmsg_type, cmsg_data = ancdata[0]
1406
+ # a.frombytes(cmsg_data)
1407
+ # print("Received fd ", a[0], " (iteration #", i, ")")
1408
+ #
1409
+ # shutil.rmtree(dirname)
1410
+ #
1411
+ # Steps to reproduce:
1412
+ #
1413
+ # 1. Run two shells and set lower file descriptor limit in the receiving one:
1414
+ # (shell1) ulimit -n 1020
1415
+ # (shell2) ulimit -n 1022
1416
+ #
1417
+ # 2. Run the script above with the `recv` option in the first shell
1418
+ # (shell1) ./test_socket.py sock_tmp 1017 recv
1419
+ #
1420
+ # 3. Run the script with the `send` option in the second shell:
1421
+ # (shell2) ./test_socket.py sock_tmp 1017 send
1422
+
1423
+ def _get_data(self):
1424
+ # Fetches data from `self._data_queue`.
1425
+ #
1426
+ # We check workers' status every `MP_STATUS_CHECK_INTERVAL` seconds,
1427
+ # which we achieve by running `self._try_get_data(timeout=MP_STATUS_CHECK_INTERVAL)`
1428
+ # in a loop. This is the only mechanism to detect worker failures for
1429
+ # Windows. For other platforms, a SIGCHLD handler is also used for
1430
+ # worker failure detection.
1431
+ #
1432
+ # If `pin_memory=True`, we also need check if `pin_memory_thread` had
1433
+ # died at timeouts.
1434
+ if self._timeout > 0:
1435
+ success, data = self._try_get_data(self._timeout)
1436
+ if success:
1437
+ return data
1438
+ else:
1439
+ raise RuntimeError(
1440
+ f"DataLoader timed out after {self._timeout} seconds"
1441
+ )
1442
+ elif self._pin_memory:
1443
+ while self._pin_memory_thread.is_alive():
1444
+ success, data = self._try_get_data()
1445
+ if success:
1446
+ return data
1447
+ else:
1448
+ # while condition is false, i.e., pin_memory_thread died.
1449
+ raise RuntimeError("Pin memory thread exited unexpectedly")
1450
+ # In this case, `self._data_queue` is a `queue.Queue`,. But we don't
1451
+ # need to call `.task_done()` because we don't use `.join()`.
1452
+ else:
1453
+ while True:
1454
+ success, data = self._try_get_data()
1455
+ if success:
1456
+ return data
1457
+
1458
+ def _next_data(self):
1459
+ while True:
1460
+ # If the worker responsible for `self._rcvd_idx` has already ended
1461
+ # and was unable to fulfill this task (due to exhausting an `IterableDataset`),
1462
+ # we try to advance `self._rcvd_idx` to find the next valid index.
1463
+ #
1464
+ # This part needs to run in the loop because both the `self._get_data()`
1465
+ # call and `_IterableDatasetStopIteration` check below can mark
1466
+ # extra worker(s) as dead.
1467
+ while self._rcvd_idx < self._send_idx:
1468
+ info = self._task_info.get(self._rcvd_idx, None)
1469
+ if info:
1470
+ worker_id = info[0]
1471
+ if (
1472
+ len(info) == 2 or self._workers_status[worker_id]
1473
+ ): # has data or is still active
1474
+ break
1475
+ del self._task_info[self._rcvd_idx]
1476
+ self._rcvd_idx += 1
1477
+ else:
1478
+ # no valid `self._rcvd_idx` is found (i.e., didn't break)
1479
+ if not self._persistent_workers:
1480
+ self._shutdown_workers()
1481
+ raise StopIteration
1482
+
1483
+ # Now `self._rcvd_idx` is the batch index we want to fetch
1484
+
1485
+ # Check if the next sample has already been generated
1486
+ if len(self._task_info[self._rcvd_idx]) == 2:
1487
+ worker_id, data = self._task_info.pop(self._rcvd_idx)
1488
+ self._rcvd_idx += 1
1489
+ return self._process_data(data, worker_id)
1490
+
1491
+ assert not self._shutdown and self._tasks_outstanding > 0
1492
+ idx, data = self._get_data()
1493
+ self._tasks_outstanding -= 1
1494
+ if self._dataset_kind == _DatasetKind.Iterable:
1495
+ # Check for _IterableDatasetStopIteration
1496
+ if isinstance(data, _utils.worker._IterableDatasetStopIteration):
1497
+ if self._persistent_workers:
1498
+ self._workers_status[data.worker_id] = False
1499
+ else:
1500
+ self._mark_worker_as_unavailable(data.worker_id)
1501
+ self._try_put_index()
1502
+ continue
1503
+
1504
+ if idx != self._rcvd_idx:
1505
+ if not self._in_order:
1506
+ # don't store it for later, process now
1507
+ # delete from self._task_info immediately
1508
+ # this keeps the object size manageable
1509
+ worker_id = self._task_info.pop(idx)[0]
1510
+ return self._process_data(data, worker_id)
1511
+ # store out-of-order samples
1512
+ self._task_info[idx] += (data,)
1513
+ else:
1514
+ worker_id = self._task_info.pop(idx)[0]
1515
+ self._rcvd_idx += 1
1516
+ return self._process_data(data, worker_id)
1517
+
1518
+ def _try_put_index(self):
1519
+ max_tasks = self._prefetch_factor * self._num_workers
1520
+ assert self._tasks_outstanding < max_tasks
1521
+
1522
+ try:
1523
+ index = self._next_index()
1524
+ except StopIteration:
1525
+ return
1526
+ for _ in range(self._num_workers): # find the next active worker, if any
1527
+ worker_queue_idx = next(self._worker_queue_idx_cycle)
1528
+ if self._workers_status[worker_queue_idx]:
1529
+ if self._in_order:
1530
+ break
1531
+ elif self._workers_num_tasks[worker_queue_idx] < max_tasks // sum(
1532
+ self._workers_status
1533
+ ):
1534
+ # when self._in_order is False, distribute work to a worker if it has capacity
1535
+ # _workers_status is updated only in this thread, so the sum is guaranteed > 0
1536
+ break
1537
+ else:
1538
+ # not found (i.e., didn't break)
1539
+ return
1540
+
1541
+ self._index_queues[worker_queue_idx].put((self._send_idx, index)) # type: ignore[possibly-undefined]
1542
+ self._task_info[self._send_idx] = (worker_queue_idx,)
1543
+ self._workers_num_tasks[worker_queue_idx] += 1
1544
+ self._tasks_outstanding += 1
1545
+ self._send_idx += 1
1546
+
1547
+ def _process_data(self, data, worker_idx):
1548
+ self._workers_num_tasks[worker_idx] -= 1
1549
+ self._try_put_index()
1550
+ if isinstance(data, ExceptionWrapper):
1551
+ data.reraise()
1552
+ return data
1553
+
1554
+ def _mark_worker_as_unavailable(self, worker_id, shutdown=False):
1555
+ # Mark a worker as having finished its work e.g., due to
1556
+ # exhausting an `IterableDataset`. This should be used only when this
1557
+ # `_MultiProcessingDataLoaderIter` is going to continue running.
1558
+
1559
+ assert self._workers_status[worker_id] or (
1560
+ self._persistent_workers and shutdown
1561
+ )
1562
+
1563
+ # Signal termination to that specific worker.
1564
+ q = self._index_queues[worker_id]
1565
+ # Indicate that no more data will be put on this queue by the current
1566
+ # process.
1567
+ q.put(None)
1568
+
1569
+ # Note that we don't actually join the worker here, nor do we remove the
1570
+ # worker's pid from C side struct because (1) joining may be slow, and
1571
+ # (2) since we don't join, the worker may still raise error, and we
1572
+ # prefer capturing those, rather than ignoring them, even though they
1573
+ # are raised after the worker has finished its job.
1574
+ # Joinning is deferred to `_shutdown_workers`, which it is called when
1575
+ # all workers finish their jobs (e.g., `IterableDataset` replicas) or
1576
+ # when this iterator is garbage collected.
1577
+
1578
+ self._workers_status[worker_id] = False
1579
+
1580
+ assert self._workers_done_event.is_set() == shutdown
1581
+
1582
+ def _shutdown_workers(self):
1583
+ # Called when shutting down this `_MultiProcessingDataLoaderIter`.
1584
+ # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on
1585
+ # the logic of this function.
1586
+ if (
1587
+ _utils is None
1588
+ or _utils.python_exit_status is True
1589
+ or _utils.python_exit_status is None
1590
+ ):
1591
+ # See (2) of the note. If Python is shutting down, do no-op.
1592
+ return
1593
+ # Normal exit when last reference is gone / iterator is depleted.
1594
+ # See (1) and the second half of the note.
1595
+ if not self._shutdown:
1596
+ self._shutdown = True
1597
+ try:
1598
+ # Normal exit when last reference is gone / iterator is depleted.
1599
+ # See (1) and the second half of the note.
1600
+
1601
+ # Exit `pin_memory_thread` first because exiting workers may leave
1602
+ # corrupted data in `worker_result_queue` which `pin_memory_thread`
1603
+ # reads from.
1604
+ if hasattr(self, "_pin_memory_thread"):
1605
+ # Use hasattr in case error happens before we set the attribute.
1606
+ self._pin_memory_thread_done_event.set()
1607
+ # Send something to pin_memory_thread in case it is waiting
1608
+ # so that it can wake up and check `pin_memory_thread_done_event`
1609
+ self._worker_result_queue.put((None, None))
1610
+ self._pin_memory_thread.join()
1611
+ self._worker_result_queue.cancel_join_thread()
1612
+ self._worker_result_queue.close()
1613
+
1614
+ # Exit workers now.
1615
+ self._workers_done_event.set()
1616
+ for worker_id in range(len(self._workers)):
1617
+ # Get number of workers from `len(self._workers)` instead of
1618
+ # `self._num_workers` in case we error before starting all
1619
+ # workers.
1620
+ # If we are using workers_status with persistent_workers
1621
+ # we have to shut it down because the worker is paused
1622
+ if self._persistent_workers or self._workers_status[worker_id]:
1623
+ self._mark_worker_as_unavailable(worker_id, shutdown=True)
1624
+ for w in self._workers:
1625
+ # We should be able to join here, but in case anything went
1626
+ # wrong, we set a timeout and if the workers fail to join,
1627
+ # they are killed in the `finally` block.
1628
+ w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)
1629
+ for q in self._index_queues:
1630
+ q.cancel_join_thread()
1631
+ q.close()
1632
+ finally:
1633
+ # Even though all this function does is putting into queues that
1634
+ # we have called `cancel_join_thread` on, weird things can
1635
+ # happen when a worker is killed by a signal, e.g., hanging in
1636
+ # `Event.set()`. So we need to guard this with SIGCHLD handler,
1637
+ # and remove pids from the C side data structure only at the
1638
+ # end.
1639
+ #
1640
+ # FIXME: Unfortunately, for Windows, we are missing a worker
1641
+ # error detection mechanism here in this function, as it
1642
+ # doesn't provide a SIGCHLD handler.
1643
+ if self._worker_pids_set:
1644
+ _utils.signal_handling._remove_worker_pids(id(self))
1645
+ self._worker_pids_set = False
1646
+ for w in self._workers:
1647
+ if w.is_alive():
1648
+ # Existing mechanisms try to make the workers exit
1649
+ # peacefully, but in case that we unfortunately reach
1650
+ # here, which we shouldn't, (e.g., pytorch/pytorch#39570),
1651
+ # we kill the worker.
1652
+ w.terminate()
1653
+
1654
+ # staticmethod is used to remove reference to `_MultiProcessingDataLoaderIter`
1655
+ @staticmethod
1656
+ def _clean_up_worker(w):
1657
+ try:
1658
+ w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)
1659
+ finally:
1660
+ if w.is_alive():
1661
+ w.terminate()
1662
+
1663
+ def __del__(self):
1664
+ self._shutdown_workers()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from torch.utils.data.datapipes import dataframe as dataframe, iter as iter, map as map
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/_decorator.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+ from functools import wraps
4
+ from typing import Any, Callable, get_type_hints, Optional, Union
5
+
6
+ from torch.utils.data.datapipes._typing import _DataPipeMeta
7
+ from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe
8
+
9
+
10
+ ######################################################
11
+ # Functional API
12
+ ######################################################
13
+ class functional_datapipe:
14
+ name: str
15
+
16
+ def __init__(self, name: str, enable_df_api_tracing=False) -> None:
17
+ """
18
+ Define a functional datapipe.
19
+
20
+ Args:
21
+ enable_df_api_tracing - if set, any returned DataPipe would accept
22
+ DataFrames API in tracing mode.
23
+ """
24
+ self.name = name
25
+ self.enable_df_api_tracing = enable_df_api_tracing
26
+
27
+ def __call__(self, cls):
28
+ if issubclass(cls, IterDataPipe):
29
+ if isinstance(cls, type): # type: ignore[arg-type]
30
+ if not isinstance(cls, _DataPipeMeta):
31
+ raise TypeError(
32
+ "`functional_datapipe` can only decorate IterDataPipe"
33
+ )
34
+ # with non_deterministic decorator
35
+ else:
36
+ if not isinstance(cls, non_deterministic) and not (
37
+ hasattr(cls, "__self__")
38
+ and isinstance(cls.__self__, non_deterministic)
39
+ ):
40
+ raise TypeError(
41
+ "`functional_datapipe` can only decorate IterDataPipe"
42
+ )
43
+ IterDataPipe.register_datapipe_as_function(
44
+ self.name, cls, enable_df_api_tracing=self.enable_df_api_tracing
45
+ )
46
+ elif issubclass(cls, MapDataPipe):
47
+ MapDataPipe.register_datapipe_as_function(self.name, cls)
48
+
49
+ return cls
50
+
51
+
52
+ ######################################################
53
+ # Determinism
54
+ ######################################################
55
+ _determinism: bool = False
56
+
57
+
58
+ class guaranteed_datapipes_determinism:
59
+ prev: bool
60
+
61
+ def __init__(self) -> None:
62
+ global _determinism
63
+ self.prev = _determinism
64
+ _determinism = True
65
+
66
+ def __enter__(self) -> None:
67
+ pass
68
+
69
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
70
+ global _determinism
71
+ _determinism = self.prev
72
+
73
+
74
+ class non_deterministic:
75
+ cls: Optional[type[IterDataPipe]] = None
76
+ # TODO: Lambda for picking
77
+ deterministic_fn: Callable[[], bool]
78
+
79
+ def __init__(self, arg: Union[type[IterDataPipe], Callable[[], bool]]) -> None:
80
+ # 1. Decorator doesn't have any argument
81
+ if isinstance(arg, type): # type: ignore[arg-type]
82
+ if not issubclass(arg, IterDataPipe): # type: ignore[arg-type]
83
+ raise TypeError(
84
+ "Only `IterDataPipe` can be decorated with `non_deterministic`"
85
+ f", but {arg.__name__} is found"
86
+ )
87
+ self.cls = arg # type: ignore[assignment]
88
+ # 2. Decorator has an argument of a function
89
+ # This class should behave differently given different inputs. Use this
90
+ # function to verify the determinism for each instance.
91
+ # When the function returns True, the instance is non-deterministic. Otherwise,
92
+ # the instance is a deterministic DataPipe.
93
+ elif isinstance(arg, Callable): # type:ignore[arg-type]
94
+ self.deterministic_fn = arg # type: ignore[assignment, misc]
95
+ else:
96
+ raise TypeError(f"{arg} can not be decorated by non_deterministic")
97
+
98
+ def __call__(self, *args, **kwargs):
99
+ global _determinism
100
+ # Decorate IterDataPipe
101
+ if self.cls is not None:
102
+ if _determinism:
103
+ raise TypeError(
104
+ f"{self.cls.__name__} is non-deterministic, but you set 'guaranteed_datapipes_determinism'. "
105
+ "You can turn off determinism for this DataPipe if that is acceptable "
106
+ "for your application"
107
+ )
108
+ return self.cls(*args, **kwargs) # type: ignore[call-arg]
109
+
110
+ # Decorate with a functional argument
111
+ if not (
112
+ isinstance(args[0], type)
113
+ and issubclass(args[0], IterDataPipe) # type: ignore[arg-type]
114
+ ):
115
+ raise TypeError(
116
+ f"Only `IterDataPipe` can be decorated, but {args[0].__name__} is found"
117
+ )
118
+ self.cls = args[0]
119
+ return self.deterministic_wrapper_fn
120
+
121
+ def deterministic_wrapper_fn(self, *args, **kwargs) -> IterDataPipe:
122
+ res = self.deterministic_fn(*args, **kwargs) # type: ignore[call-arg, misc]
123
+ if not isinstance(res, bool):
124
+ raise TypeError(
125
+ "deterministic_fn of `non_deterministic` decorator is required "
126
+ f"to return a boolean value, but {type(res)} is found"
127
+ )
128
+ global _determinism
129
+ if _determinism and res:
130
+ raise TypeError(
131
+ f"{self.cls.__name__} is non-deterministic with the inputs, but you set " # type: ignore[union-attr]
132
+ "'guaranteed_datapipes_determinism'. You can turn off determinism "
133
+ "for this DataPipe if that is acceptable for your application"
134
+ )
135
+ return self.cls(*args, **kwargs) # type: ignore[call-arg, misc]
136
+
137
+
138
+ ######################################################
139
+ # Type validation
140
+ ######################################################
141
+ # Validate each argument of DataPipe with hint as a subtype of the hint.
142
+ def argument_validation(f):
143
+ signature = inspect.signature(f)
144
+ hints = get_type_hints(f)
145
+
146
+ @wraps(f)
147
+ def wrapper(*args, **kwargs):
148
+ bound = signature.bind(*args, **kwargs)
149
+ for argument_name, value in bound.arguments.items():
150
+ if argument_name in hints and isinstance(
151
+ hints[argument_name], _DataPipeMeta
152
+ ):
153
+ hint = hints[argument_name]
154
+ if not isinstance(value, IterDataPipe):
155
+ raise TypeError(
156
+ f"Expected argument '{argument_name}' as a IterDataPipe, but found {type(value)}"
157
+ )
158
+ if not value.type.issubtype(hint.type):
159
+ raise TypeError(
160
+ f"Expected type of argument '{argument_name}' as a subtype of "
161
+ f"hint {hint.type}, but found {value.type}"
162
+ )
163
+
164
+ return f(*args, **kwargs)
165
+
166
+ return wrapper
167
+
168
+
169
+ # Default value is True
170
+ _runtime_validation_enabled: bool = True
171
+
172
+
173
+ class runtime_validation_disabled:
174
+ prev: bool
175
+
176
+ def __init__(self) -> None:
177
+ global _runtime_validation_enabled
178
+ self.prev = _runtime_validation_enabled
179
+ _runtime_validation_enabled = False
180
+
181
+ def __enter__(self) -> None:
182
+ pass
183
+
184
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
185
+ global _runtime_validation_enabled
186
+ _runtime_validation_enabled = self.prev
187
+
188
+
189
+ # Runtime checking
190
+ # Validate output data is subtype of return hint
191
+ def runtime_validation(f):
192
+ # TODO:
193
+ # Can be extended to validate '__getitem__' and nonblocking
194
+ if f.__name__ != "__iter__":
195
+ raise TypeError(
196
+ f"Can not decorate function {f.__name__} with 'runtime_validation'"
197
+ )
198
+
199
+ @wraps(f)
200
+ def wrapper(self):
201
+ global _runtime_validation_enabled
202
+ if not _runtime_validation_enabled:
203
+ yield from f(self)
204
+ else:
205
+ it = f(self)
206
+ for d in it:
207
+ if not self.type.issubtype_of_instance(d):
208
+ raise RuntimeError(
209
+ f"Expected an instance as subtype of {self.type}, but found {d}({type(d)})"
210
+ )
211
+ yield d
212
+
213
+ return wrapper
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/_hook_iterator.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import inspect
4
+ from enum import Enum
5
+
6
+ import torch
7
+
8
+
9
+ class _SnapshotState(Enum):
10
+ r"""
11
+ These are the snapshotting-related states that IterDataPipes can be in.
12
+
13
+ `NotStarted` - allows you to restore a snapshot and create an iterator with reset
14
+ `Restored` - cannot restore again, allows you to create an iterator without resetting the DataPipe
15
+ `Iterating` - can restore, will reset if you create a new iterator
16
+ """
17
+
18
+ NotStarted = 0
19
+ Restored = 1
20
+ Iterating = 2
21
+
22
+
23
+ def _simplify_obj_name(obj) -> str:
24
+ """Simplify the display strings of objects for the purpose of rendering within DataPipe error messages."""
25
+ if inspect.isfunction(obj):
26
+ return obj.__name__
27
+ else:
28
+ return repr(obj)
29
+
30
+
31
+ def _strip_datapipe_from_name(name: str) -> str:
32
+ return name.replace("IterDataPipe", "").replace("MapDataPipe", "")
33
+
34
+
35
+ def _generate_input_args_string(obj):
36
+ """Generate a string for the input arguments of an object."""
37
+ signature = inspect.signature(obj.__class__)
38
+ input_param_names = set(signature.parameters.keys())
39
+ result = []
40
+ for name, value in inspect.getmembers(obj):
41
+ if name in input_param_names:
42
+ result.append((name, _simplify_obj_name(value)))
43
+ return ", ".join([f"{name}={value}" for name, value in result])
44
+
45
+
46
+ def _generate_iterdatapipe_msg(datapipe, simplify_dp_name: bool = False):
47
+ output_string = (
48
+ f"{datapipe.__class__.__name__}({_generate_input_args_string(datapipe)})"
49
+ )
50
+ if simplify_dp_name:
51
+ output_string = _strip_datapipe_from_name(output_string)
52
+ return output_string
53
+
54
+
55
+ def _gen_invalid_iterdatapipe_msg(datapipe):
56
+ return (
57
+ "This iterator has been invalidated because another iterator has been created "
58
+ f"from the same IterDataPipe: {_generate_iterdatapipe_msg(datapipe)}\n"
59
+ "This may be caused multiple references to the same IterDataPipe. We recommend "
60
+ "using `.fork()` if that is necessary."
61
+ )
62
+
63
+
64
+ _feedback_msg = (
65
+ "\nFor feedback regarding this single iterator per IterDataPipe constraint, feel free "
66
+ "to comment on this issue: https://github.com/pytorch/data/issues/45."
67
+ )
68
+
69
+
70
+ def _check_iterator_valid(datapipe, iterator_id, next_method_exists=False) -> None:
71
+ r"""
72
+ Given an instance of a DataPipe and an iterator ID, check if the IDs match, and if not, raises an exception.
73
+
74
+ In the case of ChildDataPipe, the ID gets compared to the one stored in `main_datapipe` as well.
75
+ """
76
+ if next_method_exists:
77
+ # This is the case where `IterDataPipe` has both `__iter__` and `__next__`.
78
+ # The `_valid_iterator_id` should either be never set (`None`), or set by at most one
79
+ # iterator (`0`). Otherwise, it means there are multiple iterators.
80
+ if datapipe._valid_iterator_id is not None and datapipe._valid_iterator_id != 0:
81
+ extra_msg = "\nNote that this exception is raised inside your IterDataPipe's a `__next__` method"
82
+ raise RuntimeError(
83
+ _gen_invalid_iterdatapipe_msg(datapipe) + extra_msg + _feedback_msg
84
+ )
85
+ elif (
86
+ hasattr(datapipe, "_is_child_datapipe") and datapipe._is_child_datapipe is True
87
+ ):
88
+ if hasattr(datapipe, "_check_valid_iterator_id"):
89
+ if not datapipe._check_valid_iterator_id(iterator_id):
90
+ raise RuntimeError(
91
+ "This iterator has been invalidated, because a new iterator has been created "
92
+ f"from one of the ChildDataPipes of "
93
+ f"{_generate_iterdatapipe_msg(datapipe.main_datapipe)}."
94
+ + _feedback_msg
95
+ )
96
+ else:
97
+ raise RuntimeError(
98
+ "ChildDataPipe must have method `_check_valid_iterator_id`."
99
+ )
100
+ elif datapipe._valid_iterator_id != iterator_id:
101
+ raise RuntimeError(_gen_invalid_iterdatapipe_msg(datapipe) + _feedback_msg)
102
+
103
+
104
+ def _set_datapipe_valid_iterator_id(datapipe):
105
+ """Given a DataPipe, updates its valid iterator ID and reset the DataPipe."""
106
+ if hasattr(datapipe, "_is_child_datapipe") and datapipe._is_child_datapipe is True:
107
+ if hasattr(datapipe, "_set_main_datapipe_valid_iterator_id"):
108
+ datapipe._set_main_datapipe_valid_iterator_id() # reset() is called within this method when appropriate
109
+ else:
110
+ raise RuntimeError(
111
+ "ChildDataPipe must have method `_set_main_datapipe_valid_iterator_id`."
112
+ )
113
+ else:
114
+ if datapipe._valid_iterator_id is None:
115
+ datapipe._valid_iterator_id = 0
116
+ else:
117
+ datapipe._valid_iterator_id += 1
118
+ datapipe.reset()
119
+ return datapipe._valid_iterator_id
120
+
121
+
122
+ def hook_iterator(namespace):
123
+ r"""
124
+ Define a hook that is applied to all `__iter__` of metaclass `_DataPipeMeta`.
125
+
126
+ This is done for the purpose of profiling and checking if an iterator is still valid.
127
+ """
128
+
129
+ def profiler_record_fn_context(datapipe):
130
+ if not hasattr(datapipe, "_profile_name"):
131
+ datapipe._profile_name = _generate_iterdatapipe_msg(
132
+ datapipe, simplify_dp_name=True
133
+ )
134
+ return torch.autograd.profiler.record_function(datapipe._profile_name)
135
+
136
+ class IteratorDecorator:
137
+ r"""
138
+ Wrap the iterator and modifying its `__next__` method.
139
+
140
+ This decorator is applied to DataPipes of which `__iter__` method is NOT a generator function.
141
+ Those `__iter__` method commonly returns `self` but not necessarily.
142
+ """
143
+
144
+ def __init__(self, iterator, datapipe, iterator_id, has_next_method):
145
+ self.iterator = iterator
146
+ self.datapipe = datapipe
147
+ self.iterator_id = iterator_id
148
+ self._profiler_enabled = torch.autograd._profiler_enabled()
149
+ # Check if `__iter__` returns `self` and `DataPipe` has `__next__`
150
+ self.self_and_has_next_method = (
151
+ self.iterator is self.datapipe and has_next_method
152
+ )
153
+
154
+ def __iter__(self):
155
+ return self
156
+
157
+ def _get_next(self):
158
+ """Return next with logic related to iterator validity, profiler, and incrementation of samples yielded."""
159
+ _check_iterator_valid(self.datapipe, self.iterator_id)
160
+ result = next(self.iterator)
161
+ if not self.self_and_has_next_method:
162
+ self.datapipe._number_of_samples_yielded += 1
163
+ return result
164
+
165
+ def __next__(self):
166
+ # TODO: Add try-except to in-place reduce traceback from the Exception
167
+ # See: https://github.com/pytorch/data/issues/284
168
+ if self._profiler_enabled:
169
+ with profiler_record_fn_context(self.datapipe):
170
+ return self._get_next()
171
+ else: # Decided against using `contextlib.nullcontext` for performance reasons
172
+ return self._get_next()
173
+
174
+ def __getattr__(self, name):
175
+ return getattr(self.iterator, name)
176
+
177
+ func = namespace["__iter__"]
178
+
179
+ # ``__iter__`` of IterDataPipe is a generator function
180
+ if inspect.isgeneratorfunction(func):
181
+
182
+ @functools.wraps(func)
183
+ def wrap_generator(*args, **kwargs):
184
+ gen = func(*args, **kwargs)
185
+ datapipe = args[0]
186
+ if datapipe._fast_forward_iterator:
187
+ it = datapipe._fast_forward_iterator
188
+ datapipe._fast_forward_iterator = None
189
+ datapipe._snapshot_state = _SnapshotState.Iterating
190
+ while True:
191
+ try:
192
+ yield next(it)
193
+ except StopIteration:
194
+ return
195
+ iterator_id = _set_datapipe_valid_iterator_id(
196
+ datapipe
197
+ ) # This ID is tied to each created iterator
198
+ _profiler_enabled = torch.autograd._profiler_enabled()
199
+ try:
200
+ if _profiler_enabled:
201
+ with profiler_record_fn_context(datapipe):
202
+ response = gen.send(None)
203
+ else:
204
+ response = gen.send(None)
205
+
206
+ while True:
207
+ datapipe._number_of_samples_yielded += 1
208
+ request = yield response
209
+ # Pass through here every time `__next__` is called
210
+ if _profiler_enabled:
211
+ with profiler_record_fn_context(datapipe):
212
+ _check_iterator_valid(datapipe, iterator_id)
213
+ response = gen.send(request)
214
+ else: # Decided against using `contextlib.nullcontext` for performance reasons
215
+ _check_iterator_valid(datapipe, iterator_id)
216
+ response = gen.send(request)
217
+ except StopIteration:
218
+ return
219
+ except Exception as e:
220
+ # TODO: Simplify the traceback message to skip over `response = gen.send(None)`
221
+ # Part of https://github.com/pytorch/data/issues/284
222
+ datapipe = args[0]
223
+ msg = "thrown by __iter__ of"
224
+ single_iterator_msg = "single iterator per IterDataPipe constraint"
225
+ if hasattr(e.args, "__len__"):
226
+ full_msg = f"{msg} {datapipe.__class__.__name__}({_generate_input_args_string(datapipe)})"
227
+ if len(e.args) == 0 or not isinstance(
228
+ e.args[0], str
229
+ ): # If an exception message doesn't exist
230
+ e.args = (f"\nThis exception is {full_msg}",)
231
+ elif msg not in e.args[0] and single_iterator_msg not in e.args[0]:
232
+ e.args = (
233
+ e.args[0] + f"\nThis exception is {full_msg}",
234
+ ) + e.args[1:]
235
+ raise
236
+
237
+ namespace["__iter__"] = wrap_generator
238
+ else: # ``__iter__`` of IterDataPipe is NOT a generator function
239
+ # IterDataPipe is an iterator with both ``__iter__`` and ``__next__``
240
+ # And ``__iter__`` may or may not return `self`
241
+ if "__next__" in namespace: # If `__next__` exists, put a wrapper around it
242
+ next_func = namespace["__next__"]
243
+
244
+ @functools.wraps(next_func)
245
+ def wrap_next(*args, **kwargs):
246
+ datapipe = args[0]
247
+ if torch.autograd._profiler_enabled():
248
+ with profiler_record_fn_context(datapipe):
249
+ result = next_func(*args, **kwargs)
250
+ else:
251
+ result = next_func(*args, **kwargs)
252
+ datapipe._number_of_samples_yielded += 1
253
+ return result
254
+
255
+ namespace["__next__"] = wrap_next
256
+
257
+ # Note that if the `__next__` and `__iter__` do something completely unrelated. It may cause issue but
258
+ # the user will be violating the iterator protocol. Potential issue:
259
+ # 1. Valid iterator ID may not update or checked properly
260
+ # 2. The number of samples yielded will be miscounted
261
+
262
+ # Regardless if `__next__` exists or not, `__iter__` needs a wrapper to track the number of valid iterators
263
+ @functools.wraps(func)
264
+ def wrap_iter(*args, **kwargs):
265
+ iter_ret = func(*args, **kwargs)
266
+ datapipe = args[0]
267
+ datapipe._snapshot_state = _SnapshotState.Iterating
268
+ if datapipe._fast_forward_iterator:
269
+ iter_ret = datapipe._fast_forward_iterator
270
+ datapipe._fast_forward_iterator = None
271
+ return iter_ret
272
+ iterator_id = _set_datapipe_valid_iterator_id(
273
+ datapipe
274
+ ) # This ID is tied to each created iterator
275
+ return IteratorDecorator(
276
+ iter_ret, datapipe, iterator_id, "__next__" in namespace
277
+ )
278
+
279
+ namespace["__iter__"] = wrap_iter
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/_typing.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Taking reference from official Python typing
3
+ # https://github.com/python/cpython/blob/master/Lib/typing.py
4
+
5
+ import collections
6
+ import functools
7
+ import numbers
8
+ import sys
9
+
10
+ # Please check [Note: TypeMeta and TypeAlias]
11
+ # In case of metaclass conflict due to ABCMeta or _ProtocolMeta
12
+ # For Python 3.9, only Protocol in typing uses metaclass
13
+ from abc import ABCMeta
14
+ from collections.abc import Iterator
15
+
16
+ # TODO: Use TypeAlias when Python 3.6 is deprecated
17
+ from typing import ( # type: ignore[attr-defined]
18
+ _eval_type,
19
+ _GenericAlias,
20
+ _tp_cache,
21
+ _type_check,
22
+ _type_repr,
23
+ Any,
24
+ ForwardRef,
25
+ Generic,
26
+ get_type_hints,
27
+ TypeVar,
28
+ Union,
29
+ )
30
+
31
+ from torch.utils.data.datapipes._hook_iterator import _SnapshotState, hook_iterator
32
+
33
+
34
+ class GenericMeta(ABCMeta): # type: ignore[no-redef]
35
+ pass
36
+
37
+
38
+ class Integer(numbers.Integral):
39
+ pass
40
+
41
+
42
+ class Boolean(numbers.Integral):
43
+ pass
44
+
45
+
46
+ # Python 'type' object is not subscriptable
47
+ # Tuple[int, List, dict] -> valid
48
+ # tuple[int, list, dict] -> invalid
49
+ # Map Python 'type' to abstract base class
50
+ TYPE2ABC = {
51
+ bool: Boolean,
52
+ int: Integer,
53
+ float: numbers.Real,
54
+ complex: numbers.Complex,
55
+ dict: dict,
56
+ list: list,
57
+ set: set,
58
+ tuple: tuple,
59
+ None: type(None),
60
+ }
61
+
62
+
63
+ def issubtype(left, right, recursive=True):
64
+ r"""
65
+ Check if the left-side type is a subtype of the right-side type.
66
+
67
+ If any of type is a composite type like `Union` and `TypeVar` with
68
+ bounds, it would be expanded into a list of types and check all
69
+ of left-side types are subtypes of either one from right-side types.
70
+ """
71
+ left = TYPE2ABC.get(left, left)
72
+ right = TYPE2ABC.get(right, right)
73
+
74
+ if right is Any or left == right:
75
+ return True
76
+
77
+ if isinstance(right, _GenericAlias):
78
+ if getattr(right, "__origin__", None) is Generic:
79
+ return True
80
+
81
+ if right == type(None):
82
+ return False
83
+
84
+ # Right-side type
85
+ constraints = _decompose_type(right)
86
+
87
+ if len(constraints) == 0 or Any in constraints:
88
+ return True
89
+
90
+ if left is Any:
91
+ return False
92
+
93
+ # Left-side type
94
+ variants = _decompose_type(left)
95
+
96
+ # all() will return True for empty variants
97
+ if len(variants) == 0:
98
+ return False
99
+
100
+ return all(
101
+ _issubtype_with_constraints(variant, constraints, recursive)
102
+ for variant in variants
103
+ )
104
+
105
+
106
+ def _decompose_type(t, to_list=True):
107
+ if isinstance(t, TypeVar):
108
+ if t.__bound__ is not None:
109
+ ts = [t.__bound__]
110
+ else:
111
+ # For T_co, __constraints__ is ()
112
+ ts = list(t.__constraints__)
113
+ elif hasattr(t, "__origin__") and t.__origin__ == Union:
114
+ ts = t.__args__
115
+ else:
116
+ if not to_list:
117
+ return None
118
+ ts = [t]
119
+ # Ignored: Generator has incompatible item type "object"; expected "Type[Any]"
120
+ ts = [TYPE2ABC.get(_t, _t) for _t in ts] # type: ignore[misc]
121
+ return ts
122
+
123
+
124
+ def _issubtype_with_constraints(variant, constraints, recursive=True):
125
+ r"""
126
+ Check if the variant is a subtype of either one from constraints.
127
+
128
+ For composite types like `Union` and `TypeVar` with bounds, they
129
+ would be expanded for testing.
130
+ """
131
+ if variant in constraints:
132
+ return True
133
+
134
+ # [Note: Subtype for Union and TypeVar]
135
+ # Python typing is able to flatten Union[Union[...]] or Union[TypeVar].
136
+ # But it couldn't flatten the following scenarios:
137
+ # - Union[int, TypeVar[Union[...]]]
138
+ # - TypeVar[TypeVar[...]]
139
+ # So, variant and each constraint may be a TypeVar or a Union.
140
+ # In these cases, all of inner types from the variant are required to be
141
+ # extraced and verified as a subtype of any constraint. And, all of
142
+ # inner types from any constraint being a TypeVar or a Union are
143
+ # also required to be extracted and verified if the variant belongs to
144
+ # any of them.
145
+
146
+ # Variant
147
+ vs = _decompose_type(variant, to_list=False)
148
+
149
+ # Variant is TypeVar or Union
150
+ if vs is not None:
151
+ return all(_issubtype_with_constraints(v, constraints, recursive) for v in vs)
152
+
153
+ # Variant is not TypeVar or Union
154
+ if hasattr(variant, "__origin__") and variant.__origin__ is not None:
155
+ v_origin = variant.__origin__
156
+ # In Python-3.9 typing library untyped generics do not have args
157
+ v_args = getattr(variant, "__args__", None)
158
+ else:
159
+ v_origin = variant
160
+ v_args = None
161
+
162
+ # Constraints
163
+ for constraint in constraints:
164
+ cs = _decompose_type(constraint, to_list=False)
165
+
166
+ # Constraint is TypeVar or Union
167
+ if cs is not None:
168
+ if _issubtype_with_constraints(variant, cs, recursive):
169
+ return True
170
+ # Constraint is not TypeVar or Union
171
+ else:
172
+ # __origin__ can be None for plain list, tuple, ... in Python 3.6
173
+ if hasattr(constraint, "__origin__") and constraint.__origin__ is not None:
174
+ c_origin = constraint.__origin__
175
+ if v_origin == c_origin:
176
+ if not recursive:
177
+ return True
178
+ # In Python-3.9 typing library untyped generics do not have args
179
+ c_args = getattr(constraint, "__args__", None)
180
+ if c_args is None or len(c_args) == 0:
181
+ return True
182
+ if (
183
+ v_args is not None
184
+ and len(v_args) == len(c_args)
185
+ and all(
186
+ issubtype(v_arg, c_arg)
187
+ for v_arg, c_arg in zip(v_args, c_args)
188
+ )
189
+ ):
190
+ return True
191
+ # Tuple[int] -> Tuple
192
+ else:
193
+ if v_origin == constraint:
194
+ return True
195
+
196
+ return False
197
+
198
+
199
+ def issubinstance(data, data_type):
200
+ if not issubtype(type(data), data_type, recursive=False):
201
+ return False
202
+
203
+ # In Python-3.9 typing library __args__ attribute is not defined for untyped generics
204
+ dt_args = getattr(data_type, "__args__", None)
205
+ if isinstance(data, tuple):
206
+ if dt_args is None or len(dt_args) == 0:
207
+ return True
208
+ if len(dt_args) != len(data):
209
+ return False
210
+ return all(issubinstance(d, t) for d, t in zip(data, dt_args))
211
+ elif isinstance(data, (list, set)):
212
+ if dt_args is None or len(dt_args) == 0:
213
+ return True
214
+ t = dt_args[0]
215
+ return all(issubinstance(d, t) for d in data)
216
+ elif isinstance(data, dict):
217
+ if dt_args is None or len(dt_args) == 0:
218
+ return True
219
+ kt, vt = dt_args
220
+ return all(
221
+ issubinstance(k, kt) and issubinstance(v, vt) for k, v in data.items()
222
+ )
223
+
224
+ return True
225
+
226
+
227
+ # [Note: TypeMeta and TypeAlias]
228
+ # In order to keep compatibility for Python 3.6, use Meta for the typing.
229
+ # TODO: When PyTorch drops the support for Python 3.6, it can be converted
230
+ # into the Alias system and using `__class_getitem__` for DataPipe. The
231
+ # typing system will gain benefit of performance and resolving metaclass
232
+ # conflicts as elaborated in https://www.python.org/dev/peps/pep-0560/
233
+
234
+
235
+ class _DataPipeType:
236
+ r"""Save type annotation in `param`."""
237
+
238
+ def __init__(self, param):
239
+ self.param = param
240
+
241
+ def __repr__(self):
242
+ return _type_repr(self.param)
243
+
244
+ def __eq__(self, other):
245
+ if isinstance(other, _DataPipeType):
246
+ return self.param == other.param
247
+ return NotImplemented
248
+
249
+ def __hash__(self):
250
+ return hash(self.param)
251
+
252
+ def issubtype(self, other):
253
+ if isinstance(other.param, _GenericAlias):
254
+ if getattr(other.param, "__origin__", None) is Generic:
255
+ return True
256
+ if isinstance(other, _DataPipeType):
257
+ return issubtype(self.param, other.param)
258
+ if isinstance(other, type):
259
+ return issubtype(self.param, other)
260
+ raise TypeError(f"Expected '_DataPipeType' or 'type', but found {type(other)}")
261
+
262
+ def issubtype_of_instance(self, other):
263
+ return issubinstance(other, self.param)
264
+
265
+
266
+ # Default type for DataPipe without annotation
267
+ _T_co = TypeVar("_T_co", covariant=True)
268
+ _DEFAULT_TYPE = _DataPipeType(Generic[_T_co])
269
+
270
+
271
+ class _DataPipeMeta(GenericMeta):
272
+ r"""
273
+ Metaclass for `DataPipe`.
274
+
275
+ Add `type` attribute and `__init_subclass__` based on the type, and validate the return hint of `__iter__`.
276
+
277
+ Note that there is subclass `_IterDataPipeMeta` specifically for `IterDataPipe`.
278
+ """
279
+
280
+ type: _DataPipeType
281
+
282
+ def __new__(cls, name, bases, namespace, **kwargs):
283
+ return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
284
+
285
+ # TODO: the statements below are not reachable by design as there is a bug and typing is low priority for now.
286
+ cls.__origin__ = None
287
+ if "type" in namespace:
288
+ return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
289
+
290
+ namespace["__type_class__"] = False
291
+ # For plain derived class without annotation
292
+ for base in bases:
293
+ if isinstance(base, _DataPipeMeta):
294
+ return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
295
+
296
+ namespace.update(
297
+ {"type": _DEFAULT_TYPE, "__init_subclass__": _dp_init_subclass}
298
+ )
299
+ return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
300
+
301
+ def __init__(self, name, bases, namespace, **kwargs):
302
+ super().__init__(name, bases, namespace, **kwargs) # type: ignore[call-overload]
303
+
304
+ # TODO: Fix isinstance bug
305
+ @_tp_cache
306
+ def _getitem_(self, params):
307
+ if params is None:
308
+ raise TypeError(f"{self.__name__}[t]: t can not be None")
309
+ if isinstance(params, str):
310
+ params = ForwardRef(params)
311
+ if not isinstance(params, tuple):
312
+ params = (params,)
313
+
314
+ msg = f"{self.__name__}[t]: t must be a type"
315
+ params = tuple(_type_check(p, msg) for p in params)
316
+
317
+ if isinstance(self.type.param, _GenericAlias):
318
+ orig = getattr(self.type.param, "__origin__", None)
319
+ if isinstance(orig, type) and orig is not Generic:
320
+ p = self.type.param[params] # type: ignore[index]
321
+ t = _DataPipeType(p)
322
+ l = len(str(self.type)) + 2
323
+ name = self.__name__[:-l]
324
+ name = name + "[" + str(t) + "]"
325
+ bases = (self,) + self.__bases__
326
+ return self.__class__(
327
+ name,
328
+ bases,
329
+ {
330
+ "__init_subclass__": _dp_init_subclass,
331
+ "type": t,
332
+ "__type_class__": True,
333
+ },
334
+ )
335
+
336
+ if len(params) > 1:
337
+ raise TypeError(
338
+ f"Too many parameters for {self} actual {len(params)}, expected 1"
339
+ )
340
+
341
+ t = _DataPipeType(params[0])
342
+
343
+ if not t.issubtype(self.type):
344
+ raise TypeError(
345
+ f"Can not subclass a DataPipe[{t}] from DataPipe[{self.type}]"
346
+ )
347
+
348
+ # Types are equal, fast path for inheritance
349
+ if self.type == t:
350
+ return self
351
+
352
+ name = self.__name__ + "[" + str(t) + "]"
353
+ bases = (self,) + self.__bases__
354
+
355
+ return self.__class__(
356
+ name,
357
+ bases,
358
+ {"__init_subclass__": _dp_init_subclass, "__type_class__": True, "type": t},
359
+ )
360
+
361
+ # TODO: Fix isinstance bug
362
+ def _eq_(self, other):
363
+ if not isinstance(other, _DataPipeMeta):
364
+ return NotImplemented
365
+ if self.__origin__ is None or other.__origin__ is None: # type: ignore[has-type]
366
+ return self is other
367
+ return (
368
+ self.__origin__ == other.__origin__ # type: ignore[has-type]
369
+ and self.type == other.type
370
+ )
371
+
372
+ # TODO: Fix isinstance bug
373
+ def _hash_(self):
374
+ return hash((self.__name__, self.type))
375
+
376
+
377
+ class _IterDataPipeMeta(_DataPipeMeta):
378
+ r"""
379
+ Metaclass for `IterDataPipe` and inherits from `_DataPipeMeta`.
380
+
381
+ Add various functions for behaviors specific to `IterDataPipe`.
382
+ """
383
+
384
+ def __new__(cls, name, bases, namespace, **kwargs):
385
+ if "reset" in namespace:
386
+ reset_func = namespace["reset"]
387
+
388
+ @functools.wraps(reset_func)
389
+ def conditional_reset(*args, **kwargs):
390
+ r"""
391
+ Only execute DataPipe's `reset()` method if `_SnapshotState` is `Iterating` or `NotStarted`.
392
+
393
+ This allows recently restored DataPipe to preserve its restored state during the initial `__iter__` call.
394
+ """
395
+ datapipe = args[0]
396
+ if datapipe._snapshot_state in (
397
+ _SnapshotState.Iterating,
398
+ _SnapshotState.NotStarted,
399
+ ):
400
+ # Reset `NotStarted` is necessary because the `source_datapipe` of a DataPipe might have
401
+ # already begun iterating.
402
+ datapipe._number_of_samples_yielded = 0
403
+ datapipe._fast_forward_iterator = None
404
+ reset_func(*args, **kwargs)
405
+ datapipe._snapshot_state = _SnapshotState.Iterating
406
+
407
+ namespace["reset"] = conditional_reset
408
+
409
+ if "__iter__" in namespace:
410
+ hook_iterator(namespace)
411
+ return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
412
+
413
+
414
+ def _dp_init_subclass(sub_cls, *args, **kwargs):
415
+ # Add function for datapipe instance to reinforce the type
416
+ sub_cls.reinforce_type = reinforce_type
417
+
418
+ # TODO:
419
+ # - add global switch for type checking at compile-time
420
+
421
+ # Ignore internal type class
422
+ if getattr(sub_cls, "__type_class__", False):
423
+ return
424
+
425
+ # Check if the string type is valid
426
+ if isinstance(sub_cls.type.param, ForwardRef):
427
+ base_globals = sys.modules[sub_cls.__module__].__dict__
428
+ try:
429
+ param = _eval_type(sub_cls.type.param, base_globals, locals())
430
+ sub_cls.type.param = param
431
+ except TypeError as e:
432
+ raise TypeError(
433
+ f"{sub_cls.type.param.__forward_arg__} is not supported by Python typing"
434
+ ) from e
435
+
436
+ if "__iter__" in sub_cls.__dict__:
437
+ iter_fn = sub_cls.__dict__["__iter__"]
438
+ hints = get_type_hints(iter_fn)
439
+ if "return" in hints:
440
+ return_hint = hints["return"]
441
+ # Plain Return Hint for Python 3.6
442
+ if return_hint == Iterator:
443
+ return
444
+ if not (
445
+ hasattr(return_hint, "__origin__")
446
+ and (
447
+ return_hint.__origin__ == Iterator
448
+ or return_hint.__origin__ == collections.abc.Iterator
449
+ )
450
+ ):
451
+ raise TypeError(
452
+ "Expected 'Iterator' as the return annotation for `__iter__` of {}"
453
+ ", but found {}".format(
454
+ sub_cls.__name__, _type_repr(hints["return"])
455
+ )
456
+ )
457
+ data_type = return_hint.__args__[0]
458
+ if not issubtype(data_type, sub_cls.type.param):
459
+ raise TypeError(
460
+ f"Expected return type of '__iter__' as a subtype of {sub_cls.type},"
461
+ f" but found {_type_repr(data_type)} for {sub_cls.__name__}"
462
+ )
463
+
464
+
465
+ def reinforce_type(self, expected_type):
466
+ r"""
467
+ Reinforce the type for DataPipe instance.
468
+
469
+ And the 'expected_type' is required to be a subtype of the original type
470
+ hint to restrict the type requirement of DataPipe instance.
471
+ """
472
+ if isinstance(expected_type, tuple):
473
+ expected_type = tuple[expected_type] # type: ignore[valid-type]
474
+ _type_check(expected_type, msg="'expected_type' must be a type")
475
+
476
+ if not issubtype(expected_type, self.type.param):
477
+ raise TypeError(
478
+ f"Expected 'expected_type' as subtype of {self.type}, but found {_type_repr(expected_type)}"
479
+ )
480
+
481
+ self.type = _DataPipeType(expected_type)
482
+ return self
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data.datapipes.dataframe.dataframes import (
2
+ CaptureDataFrame,
3
+ DFIterDataPipe,
4
+ )
5
+ from torch.utils.data.datapipes.dataframe.datapipes import DataFramesAsTuplesPipe
6
+
7
+
8
+ __all__ = ["CaptureDataFrame", "DFIterDataPipe", "DataFramesAsTuplesPipe"]
9
+
10
+ # Please keep this list sorted
11
+ assert __all__ == sorted(__all__)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Optional
3
+
4
+
5
+ _pandas: Any = None
6
+ _WITH_PANDAS: Optional[bool] = None
7
+
8
+
9
+ def _try_import_pandas() -> bool:
10
+ try:
11
+ import pandas # type: ignore[import]
12
+
13
+ global _pandas
14
+ _pandas = pandas
15
+ return True
16
+ except ImportError:
17
+ return False
18
+
19
+
20
+ # pandas used only for prototyping, will be shortly replaced with TorchArrow
21
+ def _with_pandas() -> bool:
22
+ global _WITH_PANDAS
23
+ if _WITH_PANDAS is None:
24
+ _WITH_PANDAS = _try_import_pandas()
25
+ return _WITH_PANDAS
26
+
27
+
28
+ class PandasWrapper:
29
+ @classmethod
30
+ def create_dataframe(cls, data, columns):
31
+ if not _with_pandas():
32
+ raise RuntimeError("DataFrames prototype requires pandas to function")
33
+ return _pandas.DataFrame(data, columns=columns) # type: ignore[union-attr]
34
+
35
+ @classmethod
36
+ def is_dataframe(cls, data):
37
+ if not _with_pandas():
38
+ return False
39
+ return isinstance(data, _pandas.core.frame.DataFrame) # type: ignore[union-attr]
40
+
41
+ @classmethod
42
+ def is_column(cls, data):
43
+ if not _with_pandas():
44
+ return False
45
+ return isinstance(data, _pandas.core.series.Series) # type: ignore[union-attr]
46
+
47
+ @classmethod
48
+ def iterate(cls, data):
49
+ if not _with_pandas():
50
+ raise RuntimeError("DataFrames prototype requires pandas to function")
51
+ yield from data.itertuples(index=False)
52
+
53
+ @classmethod
54
+ def concat(cls, buffer):
55
+ if not _with_pandas():
56
+ raise RuntimeError("DataFrames prototype requires pandas to function")
57
+ return _pandas.concat(buffer) # type: ignore[union-attr]
58
+
59
+ @classmethod
60
+ def get_item(cls, data, idx):
61
+ if not _with_pandas():
62
+ raise RuntimeError("DataFrames prototype requires pandas to function")
63
+ return data[idx : idx + 1]
64
+
65
+ @classmethod
66
+ def get_len(cls, df):
67
+ if not _with_pandas():
68
+ raise RuntimeError("DataFrames prototype requires pandas to function")
69
+ return len(df.index)
70
+
71
+ @classmethod
72
+ def get_columns(cls, df):
73
+ if not _with_pandas():
74
+ raise RuntimeError("DataFrames prototype requires pandas to function")
75
+ return list(df.columns.values.tolist())
76
+
77
+
78
+ # When you build own implementation just override it with dataframe_wrapper.set_df_wrapper(new_wrapper_class)
79
+ default_wrapper = PandasWrapper
80
+
81
+
82
+ def get_df_wrapper():
83
+ return default_wrapper
84
+
85
+
86
+ def set_df_wrapper(wrapper):
87
+ global default_wrapper
88
+ default_wrapper = wrapper
89
+
90
+
91
+ def create_dataframe(data, columns=None):
92
+ wrapper = get_df_wrapper()
93
+ return wrapper.create_dataframe(data, columns)
94
+
95
+
96
+ def is_dataframe(data):
97
+ wrapper = get_df_wrapper()
98
+ return wrapper.is_dataframe(data)
99
+
100
+
101
+ def get_columns(data):
102
+ wrapper = get_df_wrapper()
103
+ return wrapper.get_columns(data)
104
+
105
+
106
+ def is_column(data):
107
+ wrapper = get_df_wrapper()
108
+ return wrapper.is_column(data)
109
+
110
+
111
+ def concat(buffer):
112
+ wrapper = get_df_wrapper()
113
+ return wrapper.concat(buffer)
114
+
115
+
116
+ def iterate(data):
117
+ wrapper = get_df_wrapper()
118
+ return wrapper.iterate(data)
119
+
120
+
121
+ def get_item(data, idx):
122
+ wrapper = get_df_wrapper()
123
+ return wrapper.get_item(data, idx)
124
+
125
+
126
+ def get_len(df):
127
+ wrapper = get_df_wrapper()
128
+ return wrapper.get_len(df)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Optional
3
+
4
+ from torch.utils.data.datapipes._decorator import functional_datapipe
5
+ from torch.utils.data.datapipes.dataframe.structures import DataChunkDF
6
+ from torch.utils.data.datapipes.datapipe import DFIterDataPipe, IterDataPipe
7
+
8
+
9
+ # TODO(VitalyFedyunin): Add error when two different traces get combined
10
+
11
+ __all__ = [
12
+ "Capture",
13
+ "CaptureA",
14
+ "CaptureAdd",
15
+ "CaptureCall",
16
+ "CaptureControl",
17
+ "CaptureDataFrame",
18
+ "CaptureDataFrameWithDataPipeOps",
19
+ "CaptureF",
20
+ "CaptureGetAttr",
21
+ "CaptureGetItem",
22
+ "CaptureInitial",
23
+ "CaptureLikeMock",
24
+ "CaptureMul",
25
+ "CaptureSetItem",
26
+ "CaptureSub",
27
+ "CaptureVariable",
28
+ "CaptureVariableAssign",
29
+ "DataFrameTracer",
30
+ "DataFrameTracedOps",
31
+ "disable_capture",
32
+ "get_val",
33
+ ]
34
+
35
+
36
+ def disable_capture():
37
+ CaptureControl.disabled = True
38
+
39
+
40
+ class CaptureControl:
41
+ disabled = False
42
+
43
+
44
+ class DataFrameTracedOps(DFIterDataPipe):
45
+ def __init__(self, source_datapipe, output_var):
46
+ self.source_datapipe = source_datapipe
47
+ self.output_var = output_var
48
+
49
+ def __iter__(self):
50
+ for item in self.source_datapipe:
51
+ yield self.output_var.apply_ops(item)
52
+
53
+
54
+ # TODO(VitalyFedyunin): Extract this list from the DFIterDataPipe registred functions
55
+ DATAPIPES_OPS = [
56
+ "_dataframes_as_tuples",
57
+ "groupby",
58
+ "_dataframes_filter",
59
+ "map",
60
+ "to_datapipe",
61
+ "shuffle",
62
+ "concat",
63
+ "batch",
64
+ "_dataframes_per_row",
65
+ "_dataframes_concat",
66
+ "_dataframes_shuffle",
67
+ ]
68
+
69
+ UNIMPLEMENTED_ATTR = ["__deepcopy__", "__setstate__", "is_shardable", "apply_sharding"]
70
+
71
+
72
+ class Capture:
73
+ # TODO: All operations are shared across entire InitialCapture, need to figure out what if we join two captures
74
+
75
+ def __init__(self, schema_df=None):
76
+ self.ctx = {"operations": [], "variables": [], "schema_df": schema_df}
77
+
78
+ def __str__(self):
79
+ return self._ops_str()
80
+
81
+ def _ops_str(self):
82
+ res = ""
83
+ for op in self.ctx["operations"]:
84
+ if len(res) > 0:
85
+ res += "\n"
86
+ res += str(op)
87
+ return res
88
+
89
+ def __getstate__(self):
90
+ # TODO(VitalyFedyunin): Currently can't pickle (why?)
91
+ self.ctx["schema_df"] = None
92
+ for var in self.ctx["variables"]:
93
+ var.calculated_value = None
94
+ state = {}
95
+ for item in self.__dict__:
96
+ state[item] = getattr(self, item)
97
+ return state
98
+
99
+ def __setstate__(self, state):
100
+ for k, v in state.items():
101
+ setattr(self, k, v)
102
+
103
+ def __getattr__(self, attrname):
104
+ if attrname == "kwarg" or attrname == "kwargs":
105
+ raise RuntimeError("no kwargs!")
106
+ if attrname in ["__deepcopy__"]:
107
+ raise AttributeError
108
+ result = CaptureGetAttr(self, attrname, ctx=self.ctx)
109
+ return result
110
+
111
+ def __getitem__(self, key):
112
+ return CaptureGetItem(self, key, ctx=self.ctx)
113
+
114
+ def __setitem__(self, key, value):
115
+ self.ctx["operations"].append(CaptureSetItem(self, key, value, ctx=self.ctx))
116
+
117
+ def __add__(self, add_val):
118
+ res = CaptureAdd(self, add_val, ctx=self.ctx)
119
+ var = CaptureVariable(res, ctx=self.ctx)
120
+ self.ctx["operations"].append(
121
+ CaptureVariableAssign(variable=var, value=res, ctx=self.ctx)
122
+ )
123
+ return var
124
+
125
+ def __sub__(self, add_val):
126
+ res = CaptureSub(self, add_val, ctx=self.ctx)
127
+ var = CaptureVariable(res, ctx=self.ctx)
128
+ self.ctx["operations"].append(
129
+ CaptureVariableAssign(variable=var, value=res, ctx=self.ctx)
130
+ )
131
+ return var
132
+
133
+ def __mul__(self, add_val):
134
+ res = CaptureMul(self, add_val, ctx=self.ctx)
135
+ var = CaptureVariable(res, ctx=self.ctx)
136
+ t = CaptureVariableAssign(variable=var, value=res, ctx=self.ctx)
137
+ self.ctx["operations"].append(t)
138
+ return var
139
+
140
+ def _is_context_empty(self):
141
+ return len(self.ctx["operations"]) == 0 and len(self.ctx["variables"]) == 0
142
+
143
+ def apply_ops_2(self, dataframe):
144
+ # TODO(VitalyFedyunin): Make this calculation thread safe (as currently it updates pointer)
145
+ self.ctx["variables"][0].calculated_value = dataframe
146
+ for op in self.ctx["operations"]:
147
+ op.execute()
148
+
149
+ @property
150
+ def columns(self):
151
+ self.apply_ops_2(self.ctx["schema_df"])
152
+ value = self.execute()
153
+ return value.columns
154
+
155
+ # TODO(VitalyFedyunin): Add tests
156
+ # TODO(VitalyFedyunin): Need to join context if one of them are empty because we used capture
157
+
158
+ def __call__(self, *args, **kwargs):
159
+ # TODO: Check if args or kwargs have more than one different context
160
+ if self._is_context_empty():
161
+ # TODO: Allow CaptureA to take context from mock
162
+ for arg in args:
163
+ if isinstance(arg, Capture) and not arg._is_context_empty():
164
+ self.ctx = arg.ctx
165
+ break
166
+ if self._is_context_empty():
167
+ for k, v in kwargs.items():
168
+ if isinstance(k, Capture) and not k._is_context_empty():
169
+ self.ctx = k.ctx
170
+ break
171
+ if isinstance(v, Capture) and not v._is_context_empty():
172
+ self.ctx = v.ctx
173
+ break
174
+
175
+ res = CaptureCall(self, ctx=self.ctx, args=args, kwargs=kwargs)
176
+ var = CaptureVariable(None, ctx=self.ctx)
177
+ t = CaptureVariableAssign(ctx=self.ctx, variable=var, value=res)
178
+ self.ctx["operations"].append(t)
179
+ return var
180
+
181
+
182
+ class CaptureF(Capture):
183
+ def __init__(self, ctx=None, **kwargs):
184
+ if ctx is None:
185
+ self.ctx = {"operations": [], "variables": []}
186
+ else:
187
+ self.ctx = ctx
188
+ self.kwargs = kwargs
189
+
190
+
191
+ class CaptureA(CaptureF):
192
+ def __str__(self):
193
+ return f"{self.kwargs['name']}"
194
+
195
+ def execute(self):
196
+ value = self.kwargs["real_attribute"]
197
+ return value
198
+
199
+
200
+ class CaptureLikeMock:
201
+ def __init__(self, name):
202
+ import unittest.mock as mock
203
+
204
+ # TODO(VitalyFedyunin): Do not use provate function here, copy own implementation instead.
205
+ get_target, attribute = mock._get_target(name) # type: ignore[attr-defined]
206
+ self.get_target = get_target
207
+ self.attribute = attribute
208
+ self.name = name
209
+
210
+ def __enter__(self):
211
+ self.save = getattr(self.get_target(), self.attribute)
212
+ capt = CaptureA(name=self.name, real_attribute=self.save)
213
+ setattr(self.get_target(), self.attribute, capt)
214
+
215
+ def __exit__(self, *exc_info):
216
+ setattr(self.get_target(), self.attribute, self.save)
217
+
218
+
219
+ class CaptureCall(Capture):
220
+ def __init__(self, callable, ctx=None, **kwargs):
221
+ if ctx is None:
222
+ self.ctx = {"operations": [], "variables": []}
223
+ else:
224
+ self.ctx = ctx
225
+ self.kwargs = kwargs
226
+ self.callable = callable
227
+
228
+ def __str__(self):
229
+ return "{callable}({args},{kwargs})".format(
230
+ callable=self.callable, **self.kwargs
231
+ )
232
+
233
+ def execute(self):
234
+ # TODO: VitalyFedyunin execute kwargs and maybe nested structures
235
+ executed_args = []
236
+ for arg in self.kwargs["args"]:
237
+ if isinstance(arg, Capture):
238
+ executed_args.append(arg.execute())
239
+ else:
240
+ executed_args.append(arg)
241
+ left = get_val(self.callable)
242
+ return left(*executed_args, **self.kwargs["kwargs"])
243
+
244
+
245
+ class CaptureVariableAssign(CaptureF):
246
+ def __str__(self):
247
+ variable = self.kwargs["variable"]
248
+ value = self.kwargs["value"]
249
+ return f"{variable} = {value}"
250
+
251
+ def execute(self):
252
+ self.kwargs["variable"].calculated_value = self.kwargs["value"].execute()
253
+
254
+
255
+ class CaptureVariable(Capture):
256
+ # TODO(VitalyFedyunin): This should be atomic and thread safe
257
+ names_idx = 0
258
+
259
+ def __init__(self, value, ctx):
260
+ if CaptureControl.disabled:
261
+ raise RuntimeError("Attempting to create capture variable with capture off")
262
+ self.ctx = ctx
263
+ self.value = value
264
+ self.name = f"var_{CaptureVariable.names_idx}"
265
+ CaptureVariable.names_idx += 1
266
+ self.ctx["variables"].append(self)
267
+
268
+ def __str__(self):
269
+ return self.name
270
+
271
+ def execute(self):
272
+ return self.calculated_value
273
+
274
+ def apply_ops(self, dataframe):
275
+ # TODO(VitalyFedyunin): Make this calculation thread safe (as currently it updates pointer)
276
+ self.ctx["variables"][0].calculated_value = dataframe
277
+ for op in self.ctx["operations"]:
278
+ op.execute()
279
+ return self.calculated_value
280
+
281
+
282
+ class CaptureGetItem(Capture):
283
+ def __init__(self, left, key, ctx):
284
+ self.ctx = ctx
285
+ self.left = left
286
+ self.key = key
287
+
288
+ def __str__(self):
289
+ return f"{self.left}[{get_val(self.key)}]"
290
+
291
+ def execute(self):
292
+ left = self.left.execute()
293
+ return left[self.key]
294
+
295
+
296
+ class CaptureSetItem(Capture):
297
+ def __init__(self, left, key, value, ctx):
298
+ self.ctx = ctx
299
+ self.left = left
300
+ self.key = key
301
+ self.value = value
302
+
303
+ def __str__(self):
304
+ return f"{self.left}[{get_val(self.key)}] = {self.value}"
305
+
306
+ def execute(self):
307
+ left = self.left.execute()
308
+ value = self.value.execute()
309
+ left[self.key] = value
310
+
311
+
312
+ class CaptureAdd(Capture):
313
+ def __init__(self, left, right, ctx):
314
+ self.ctx = ctx
315
+ self.left = left
316
+ self.right = right
317
+
318
+ def __str__(self):
319
+ return f"{self.left} + {self.right}"
320
+
321
+ def execute(self):
322
+ return get_val(self.left) + get_val(self.right)
323
+
324
+
325
+ class CaptureMul(Capture):
326
+ def __init__(self, left, right, ctx):
327
+ self.ctx = ctx
328
+ self.left = left
329
+ self.right = right
330
+
331
+ def __str__(self):
332
+ return f"{self.left} * {self.right}"
333
+
334
+ def execute(self):
335
+ return get_val(self.left) * get_val(self.right)
336
+
337
+
338
+ class CaptureSub(Capture):
339
+ def __init__(self, left, right, ctx):
340
+ self.ctx = ctx
341
+ self.left = left
342
+ self.right = right
343
+
344
+ def __str__(self):
345
+ return f"{self.left} - {self.right}"
346
+
347
+ def execute(self):
348
+ return get_val(self.left) - get_val(self.right)
349
+
350
+
351
+ class CaptureGetAttr(Capture):
352
+ def __init__(self, src, name, ctx):
353
+ self.ctx = ctx
354
+ self.src = src
355
+ self.name = name
356
+
357
+ def __str__(self):
358
+ return f"{self.src}.{self.name}"
359
+
360
+ def execute(self):
361
+ val = get_val(self.src)
362
+ return getattr(val, self.name)
363
+
364
+
365
+ def get_val(capture):
366
+ if isinstance(capture, Capture):
367
+ return capture.execute()
368
+ elif isinstance(capture, str):
369
+ return f'"{capture}"'
370
+ else:
371
+ return capture
372
+
373
+
374
+ class CaptureInitial(CaptureVariable):
375
+ def __init__(self, schema_df=None):
376
+ new_ctx: dict[str, list[Any]] = {
377
+ "operations": [],
378
+ "variables": [],
379
+ "schema_df": schema_df,
380
+ }
381
+ super().__init__(None, new_ctx)
382
+ self.name = f"input_{self.name}"
383
+
384
+
385
+ class CaptureDataFrame(CaptureInitial):
386
+ pass
387
+
388
+
389
+ class CaptureDataFrameWithDataPipeOps(CaptureDataFrame):
390
+ def as_datapipe(self):
391
+ return DataFrameTracedOps(self.ctx["variables"][0].source_datapipe, self)
392
+
393
+ def raw_iterator(self):
394
+ return self.as_datapipe().__iter__()
395
+
396
+ def __iter__(self):
397
+ return iter(self._dataframes_as_tuples())
398
+
399
+ def batch(self, batch_size=10, drop_last: bool = False, wrapper_class=DataChunkDF):
400
+ dp = self._dataframes_per_row()._dataframes_concat(batch_size)
401
+ dp = dp.as_datapipe().batch(1, drop_last=drop_last, wrapper_class=wrapper_class)
402
+ dp._dp_contains_dataframe = True
403
+ return dp
404
+
405
+ def groupby(
406
+ self,
407
+ group_key_fn,
408
+ *,
409
+ buffer_size=10000,
410
+ group_size=None,
411
+ guaranteed_group_size=None,
412
+ drop_remaining=False,
413
+ ):
414
+ dp = self._dataframes_per_row()
415
+ dp = dp.as_datapipe().groupby(
416
+ group_key_fn,
417
+ buffer_size=buffer_size,
418
+ group_size=group_size,
419
+ guaranteed_group_size=guaranteed_group_size,
420
+ drop_remaining=drop_remaining,
421
+ )
422
+ return dp
423
+
424
+ def shuffle(self, *args, **kwargs):
425
+ return self._dataframes_shuffle(*args, **kwargs)
426
+
427
+ def filter(self, *args, **kwargs):
428
+ return self._dataframes_filter(*args, **kwargs)
429
+
430
+ def collate(self, *args, **kwargs):
431
+ raise RuntimeError("Can't collate unbatched DataFrames stream")
432
+
433
+ def __getattr__(self, attrname): # ?
434
+ if attrname in UNIMPLEMENTED_ATTR:
435
+ raise AttributeError("Attempting to get ", attrname)
436
+ if attrname in DATAPIPES_OPS:
437
+ return (self.as_datapipe()).__getattr__(attrname)
438
+ return super().__getattr__(attrname)
439
+
440
+
441
+ @functional_datapipe("trace_as_dataframe")
442
+ class DataFrameTracer(CaptureDataFrameWithDataPipeOps, IterDataPipe): # type: ignore[misc]
443
+ source_datapipe: Optional[Any] = None
444
+
445
+ # TODO(VitalyFedyunin): Must implement all special functions of datapipes
446
+
447
+ def set_shuffle_settings(self, *args, **kwargs):
448
+ pass
449
+
450
+ def is_shardable(self):
451
+ return False
452
+
453
+ def __init__(self, source_datapipe, schema_df=None):
454
+ self.source_datapipe = source_datapipe
455
+ if schema_df is None:
456
+ schema_df = next(iter(self.source_datapipe))
457
+ super().__init__(schema_df=schema_df)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import random
3
+ from typing import Any
4
+
5
+ from torch.utils.data.datapipes._decorator import functional_datapipe
6
+ from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
7
+ from torch.utils.data.datapipes.datapipe import DFIterDataPipe, IterDataPipe
8
+
9
+
10
+ __all__ = [
11
+ "ConcatDataFramesPipe",
12
+ "DataFramesAsTuplesPipe",
13
+ "ExampleAggregateAsDataFrames",
14
+ "FilterDataFramesPipe",
15
+ "PerRowDataFramesPipe",
16
+ "ShuffleDataFramesPipe",
17
+ ]
18
+
19
+
20
+ @functional_datapipe("_dataframes_as_tuples")
21
+ class DataFramesAsTuplesPipe(IterDataPipe):
22
+ def __init__(self, source_datapipe):
23
+ self.source_datapipe = source_datapipe
24
+
25
+ def __iter__(self):
26
+ for df in self.source_datapipe:
27
+ # for record in df.to_records(index=False):
28
+ yield from df_wrapper.iterate(df)
29
+
30
+
31
+ @functional_datapipe("_dataframes_per_row", enable_df_api_tracing=True)
32
+ class PerRowDataFramesPipe(DFIterDataPipe):
33
+ def __init__(self, source_datapipe):
34
+ self.source_datapipe = source_datapipe
35
+
36
+ def __iter__(self):
37
+ for df in self.source_datapipe:
38
+ # TODO(VitalyFedyunin): Replacing with TorchArrow only API, as we are dropping pandas as followup
39
+ for i in range(len(df)):
40
+ yield df[i : i + 1]
41
+
42
+
43
+ @functional_datapipe("_dataframes_concat", enable_df_api_tracing=True)
44
+ class ConcatDataFramesPipe(DFIterDataPipe):
45
+ def __init__(self, source_datapipe, batch=3):
46
+ self.source_datapipe = source_datapipe
47
+ self.n_batch = batch
48
+
49
+ def __iter__(self):
50
+ buffer = []
51
+ for df in self.source_datapipe:
52
+ buffer.append(df)
53
+ if len(buffer) == self.n_batch:
54
+ yield df_wrapper.concat(buffer)
55
+ buffer = []
56
+ if len(buffer):
57
+ yield df_wrapper.concat(buffer)
58
+
59
+
60
+ @functional_datapipe("_dataframes_shuffle", enable_df_api_tracing=True)
61
+ class ShuffleDataFramesPipe(DFIterDataPipe):
62
+ def __init__(self, source_datapipe):
63
+ self.source_datapipe = source_datapipe
64
+
65
+ def __iter__(self):
66
+ size = None
67
+ all_buffer: list[Any] = []
68
+ for df in self.source_datapipe:
69
+ if size is None:
70
+ size = df_wrapper.get_len(df)
71
+ all_buffer.extend(
72
+ df_wrapper.get_item(df, i) for i in range(df_wrapper.get_len(df))
73
+ )
74
+ random.shuffle(all_buffer)
75
+ buffer = []
76
+ for df in all_buffer:
77
+ buffer.append(df)
78
+ if len(buffer) == size:
79
+ yield df_wrapper.concat(buffer)
80
+ buffer = []
81
+ if len(buffer):
82
+ yield df_wrapper.concat(buffer)
83
+
84
+
85
+ @functional_datapipe("_dataframes_filter", enable_df_api_tracing=True)
86
+ class FilterDataFramesPipe(DFIterDataPipe):
87
+ def __init__(self, source_datapipe, filter_fn):
88
+ self.source_datapipe = source_datapipe
89
+ self.filter_fn = filter_fn
90
+
91
+ def __iter__(self):
92
+ size = None
93
+ all_buffer = []
94
+ filter_res = []
95
+ for df in self.source_datapipe:
96
+ if size is None:
97
+ size = len(df.index)
98
+ for i in range(len(df.index)):
99
+ all_buffer.append(df[i : i + 1])
100
+ filter_res.append(self.filter_fn(df.iloc[i]))
101
+
102
+ buffer = []
103
+ for df, res in zip(all_buffer, filter_res):
104
+ if res:
105
+ buffer.append(df)
106
+ if len(buffer) == size:
107
+ yield df_wrapper.concat(buffer)
108
+ buffer = []
109
+ if len(buffer):
110
+ yield df_wrapper.concat(buffer)
111
+
112
+
113
+ @functional_datapipe("_to_dataframes_pipe", enable_df_api_tracing=True)
114
+ class ExampleAggregateAsDataFrames(DFIterDataPipe):
115
+ def __init__(self, source_datapipe, dataframe_size=10, columns=None):
116
+ self.source_datapipe = source_datapipe
117
+ self.columns = columns
118
+ self.dataframe_size = dataframe_size
119
+
120
+ def _as_list(self, item):
121
+ try:
122
+ return list(item)
123
+ except (
124
+ Exception
125
+ ): # TODO(VitalyFedyunin): Replace with better iterable exception
126
+ return [item]
127
+
128
+ def __iter__(self):
129
+ aggregate = []
130
+ for item in self.source_datapipe:
131
+ aggregate.append(self._as_list(item))
132
+ if len(aggregate) == self.dataframe_size:
133
+ yield df_wrapper.create_dataframe(aggregate, columns=self.columns)
134
+ aggregate = []
135
+ if len(aggregate) > 0:
136
+ yield df_wrapper.create_dataframe(aggregate, columns=self.columns)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/dataframe/structures.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterator
2
+ from typing import Any
3
+
4
+ from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
5
+ from torch.utils.data.datapipes.datapipe import DataChunk
6
+
7
+
8
+ __all__ = ["DataChunkDF"]
9
+
10
+
11
+ class DataChunkDF(DataChunk):
12
+ """DataChunkDF iterating over individual items inside of DataFrame containers, to access DataFrames user `raw_iterator`."""
13
+
14
+ def __iter__(self) -> Iterator[Any]:
15
+ for df in self.items:
16
+ yield from df_wrapper.iterate(df)
17
+
18
+ def __len__(self) -> int:
19
+ total_len = 0
20
+ for df in self.items:
21
+ total_len += df_wrapper.get_len(df)
22
+ return total_len
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/datapipe.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import pickle
3
+ from collections.abc import Iterable, Iterator
4
+ from typing import Callable, Optional, TypeVar
5
+
6
+ from torch.utils._import_utils import import_dill
7
+ from torch.utils.data.datapipes._hook_iterator import _SnapshotState
8
+ from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta
9
+ from torch.utils.data.datapipes.utils.common import (
10
+ _deprecation_warning,
11
+ _iter_deprecated_functional_names,
12
+ _map_deprecated_functional_names,
13
+ )
14
+ from torch.utils.data.dataset import Dataset, IterableDataset
15
+
16
+
17
+ dill = import_dill()
18
+ HAS_DILL = dill is not None
19
+
20
+ __all__ = [
21
+ "DataChunk",
22
+ "DFIterDataPipe",
23
+ "IterDataPipe",
24
+ "MapDataPipe",
25
+ ]
26
+
27
+
28
+ _T = TypeVar("_T")
29
+ _T_co = TypeVar("_T_co", covariant=True)
30
+
31
+ UNTRACABLE_DATAFRAME_PIPES = [
32
+ "batch", # As it returns DataChunks
33
+ "groupby", # As it returns DataChunks
34
+ "_dataframes_as_tuples", # As it unpacks DF
35
+ "trace_as_dataframe", # As it used to mark DF for tracing
36
+ ]
37
+
38
+
39
+ class DataChunk(list[_T]):
40
+ def __init__(self, items: Iterable[_T]) -> None:
41
+ items = list(items)
42
+ super().__init__(items)
43
+ self.items = items
44
+
45
+ def as_str(self, indent: str = "") -> str:
46
+ return indent + "[" + ", ".join(str(i) for i in iter(self)) + "]"
47
+
48
+ def __iter__(self) -> Iterator[_T]:
49
+ yield from super().__iter__()
50
+
51
+ def raw_iterator(self) -> Iterator[_T]:
52
+ yield from self.items
53
+
54
+
55
+ class IterDataPipe(IterableDataset[_T_co], metaclass=_IterDataPipeMeta):
56
+ r"""
57
+ Iterable-style DataPipe.
58
+
59
+ All DataPipes that represent an iterable of data samples should subclass this.
60
+ This style of DataPipes is particularly useful when data come from a stream, or
61
+ when the number of samples is too large to fit them all in memory. ``IterDataPipe`` is lazily initialized and its
62
+ elements are computed only when ``next()`` is called on the iterator of an ``IterDataPipe``.
63
+
64
+ All subclasses should overwrite :meth:`__iter__`, which would return an
65
+ iterator of samples in this DataPipe. Calling ``__iter__`` of an ``IterDataPipe`` automatically invokes its
66
+ method ``reset()``, which by default performs no operation. When writing a custom ``IterDataPipe``, users should
67
+ override ``reset()`` if necessary. The common usages include resetting buffers, pointers,
68
+ and various state variables within the custom ``IterDataPipe``.
69
+
70
+ Note:
71
+ Only `one` iterator can be valid for each ``IterDataPipe`` at a time,
72
+ and the creation a second iterator will invalidate the first one. This constraint is necessary because
73
+ some ``IterDataPipe`` have internal buffers, whose states can become invalid if there are multiple iterators.
74
+ The code example below presents details on how this constraint looks in practice.
75
+ If you have any feedback related to this constraint, please see `GitHub IterDataPipe Single Iterator Issue`_.
76
+
77
+ These DataPipes can be invoked in two ways, using the class constructor or applying their
78
+ functional form onto an existing ``IterDataPipe`` (recommended, available to most but not all DataPipes).
79
+ You can chain multiple `IterDataPipe` together to form a pipeline that will perform multiple
80
+ operations in succession.
81
+
82
+ .. _GitHub IterDataPipe Single Iterator Issue:
83
+ https://github.com/pytorch/data/issues/45
84
+
85
+ Note:
86
+ When a subclass is used with :class:`~torch.utils.data.DataLoader`, each
87
+ item in the DataPipe will be yielded from the :class:`~torch.utils.data.DataLoader`
88
+ iterator. When :attr:`num_workers > 0`, each worker process will have a
89
+ different copy of the DataPipe object, so it is often desired to configure
90
+ each copy independently to avoid having duplicate data returned from the
91
+ workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker
92
+ process, returns information about the worker. It can be used in either the
93
+ dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's
94
+ :attr:`worker_init_fn` option to modify each copy's behavior.
95
+
96
+ Examples:
97
+ General Usage:
98
+ >>> # xdoctest: +SKIP
99
+ >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
100
+ >>> dp = IterableWrapper(range(10))
101
+ >>> map_dp_1 = Mapper(dp, lambda x: x + 1) # Using class constructor
102
+ >>> map_dp_2 = dp.map(lambda x: x + 1) # Using functional form (recommended)
103
+ >>> list(map_dp_1)
104
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
105
+ >>> list(map_dp_2)
106
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
107
+ >>> filter_dp = map_dp_1.filter(lambda x: x % 2 == 0)
108
+ >>> list(filter_dp)
109
+ [2, 4, 6, 8, 10]
110
+ Single Iterator Constraint Example:
111
+ >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
112
+ >>> source_dp = IterableWrapper(range(10))
113
+ >>> it1 = iter(source_dp)
114
+ >>> list(it1)
115
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
116
+ >>> it1 = iter(source_dp)
117
+ >>> it2 = iter(source_dp) # The creation of a new iterator invalidates `it1`
118
+ >>> next(it2)
119
+ 0
120
+ >>> next(it1) # Further usage of `it1` will raise a `RunTimeError`
121
+ """
122
+
123
+ functions: dict[str, Callable] = {}
124
+ reduce_ex_hook: Optional[Callable] = None
125
+ getstate_hook: Optional[Callable] = None
126
+ str_hook: Optional[Callable] = None
127
+ repr_hook: Optional[Callable] = None
128
+ _valid_iterator_id: Optional[int] = None
129
+ _number_of_samples_yielded: int = 0
130
+ _snapshot_state: _SnapshotState = _SnapshotState.NotStarted
131
+ _fast_forward_iterator: Optional[Iterator] = None
132
+
133
+ def __iter__(self) -> Iterator[_T_co]:
134
+ return self
135
+
136
+ def __getattr__(self, attribute_name):
137
+ if attribute_name in IterDataPipe.functions:
138
+ if attribute_name in _iter_deprecated_functional_names:
139
+ kwargs = _iter_deprecated_functional_names[attribute_name]
140
+ _deprecation_warning(**kwargs)
141
+ f = IterDataPipe.functions[attribute_name]
142
+ function = functools.partial(f, self)
143
+ functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
144
+ return function
145
+ else:
146
+ raise AttributeError(
147
+ f"'{self.__class__.__name__}' object has no attribute '{attribute_name}"
148
+ )
149
+
150
+ @classmethod
151
+ def register_function(cls, function_name, function):
152
+ cls.functions[function_name] = function
153
+
154
+ @classmethod
155
+ def register_datapipe_as_function(
156
+ cls, function_name, cls_to_register, enable_df_api_tracing=False
157
+ ):
158
+ if function_name in cls.functions:
159
+ raise Exception( # noqa: TRY002
160
+ f"Unable to add DataPipe function name {function_name} as it is already taken"
161
+ )
162
+
163
+ def class_function(cls, enable_df_api_tracing, source_dp, *args, **kwargs):
164
+ result_pipe = cls(source_dp, *args, **kwargs)
165
+ if isinstance(result_pipe, IterDataPipe):
166
+ if enable_df_api_tracing or isinstance(source_dp, DFIterDataPipe):
167
+ if function_name not in UNTRACABLE_DATAFRAME_PIPES:
168
+ result_pipe = result_pipe.trace_as_dataframe()
169
+
170
+ return result_pipe
171
+
172
+ function = functools.partial(
173
+ class_function, cls_to_register, enable_df_api_tracing
174
+ )
175
+ functools.update_wrapper(
176
+ wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
177
+ )
178
+ cls.functions[function_name] = function
179
+
180
+ def __getstate__(self):
181
+ """
182
+ Serialize `lambda` functions when `dill` is available.
183
+
184
+ If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
185
+ `__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
186
+ """
187
+ state = self.__dict__
188
+ if IterDataPipe.getstate_hook is not None:
189
+ return IterDataPipe.getstate_hook(state)
190
+ return state
191
+
192
+ def __reduce_ex__(self, *args, **kwargs):
193
+ if IterDataPipe.reduce_ex_hook is not None:
194
+ try:
195
+ return IterDataPipe.reduce_ex_hook(self)
196
+ except NotImplementedError:
197
+ pass
198
+ return super().__reduce_ex__(*args, **kwargs)
199
+
200
+ @classmethod
201
+ def set_getstate_hook(cls, hook_fn):
202
+ if IterDataPipe.getstate_hook is not None and hook_fn is not None:
203
+ raise RuntimeError("Attempt to override existing getstate_hook")
204
+ IterDataPipe.getstate_hook = hook_fn
205
+
206
+ @classmethod
207
+ def set_reduce_ex_hook(cls, hook_fn):
208
+ if IterDataPipe.reduce_ex_hook is not None and hook_fn is not None:
209
+ raise RuntimeError("Attempt to override existing reduce_ex_hook")
210
+ IterDataPipe.reduce_ex_hook = hook_fn
211
+
212
+ def __repr__(self):
213
+ if self.repr_hook is not None:
214
+ return self.repr_hook(self)
215
+ # Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
216
+ return str(self.__class__.__qualname__)
217
+
218
+ def __str__(self):
219
+ if self.str_hook is not None:
220
+ return self.str_hook(self)
221
+ # Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
222
+ return str(self.__class__.__qualname__)
223
+
224
+ def __dir__(self):
225
+ # for auto-completion in a REPL (e.g. Jupyter notebook)
226
+ return list(super().__dir__()) + list(self.functions.keys())
227
+
228
+ def reset(self) -> None:
229
+ r"""
230
+ Reset the `IterDataPipe` to the initial state.
231
+
232
+ By default, no-op. For subclasses of `IterDataPipe`, depending on their functionalities,
233
+ they may want to override this method with implementations that
234
+ may clear the buffers and reset pointers of the DataPipe.
235
+ The `reset` method is always called when `__iter__` is called as part of `hook_iterator`.
236
+ """
237
+
238
+
239
+ class DFIterDataPipe(IterDataPipe):
240
+ def _is_dfpipe(self):
241
+ return True
242
+
243
+
244
+ class MapDataPipe(Dataset[_T_co], metaclass=_DataPipeMeta):
245
+ r"""
246
+ Map-style DataPipe.
247
+
248
+ All datasets that represent a map from keys to data samples should subclass this.
249
+ Subclasses should overwrite :meth:`__getitem__`, supporting fetching a
250
+ data sample for a given, unique key. Subclasses can also optionally overwrite
251
+ :meth:`__len__`, which is expected to return the size of the dataset by many
252
+ :class:`~torch.utils.data.Sampler` implementations and the default options
253
+ of :class:`~torch.utils.data.DataLoader`.
254
+
255
+ These DataPipes can be invoked in two ways, using the class constructor or applying their
256
+ functional form onto an existing `MapDataPipe` (recommend, available to most but not all DataPipes).
257
+
258
+ Note:
259
+ :class:`~torch.utils.data.DataLoader` by default constructs an index
260
+ sampler that yields integral indices. To make it work with a map-style
261
+ DataPipe with non-integral indices/keys, a custom sampler must be provided.
262
+
263
+ Example:
264
+ >>> # xdoctest: +SKIP
265
+ >>> from torchdata.datapipes.map import SequenceWrapper, Mapper
266
+ >>> dp = SequenceWrapper(range(10))
267
+ >>> map_dp_1 = dp.map(lambda x: x + 1) # Using functional form (recommended)
268
+ >>> list(map_dp_1)
269
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
270
+ >>> map_dp_2 = Mapper(dp, lambda x: x + 1) # Using class constructor
271
+ >>> list(map_dp_2)
272
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
273
+ >>> batch_dp = map_dp_1.batch(batch_size=2)
274
+ >>> list(batch_dp)
275
+ [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
276
+ """
277
+
278
+ functions: dict[str, Callable] = {}
279
+ reduce_ex_hook: Optional[Callable] = None
280
+ getstate_hook: Optional[Callable] = None
281
+ str_hook: Optional[Callable] = None
282
+ repr_hook: Optional[Callable] = None
283
+
284
+ def __getattr__(self, attribute_name):
285
+ if attribute_name in MapDataPipe.functions:
286
+ if attribute_name in _map_deprecated_functional_names:
287
+ kwargs = _map_deprecated_functional_names[attribute_name]
288
+ _deprecation_warning(**kwargs)
289
+ f = MapDataPipe.functions[attribute_name]
290
+ function = functools.partial(f, self)
291
+ functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
292
+ return function
293
+ else:
294
+ raise AttributeError(
295
+ f"'{self.__class__.__name__}' object has no attribute '{attribute_name}"
296
+ )
297
+
298
+ @classmethod
299
+ def register_function(cls, function_name, function):
300
+ cls.functions[function_name] = function
301
+
302
+ @classmethod
303
+ def register_datapipe_as_function(cls, function_name, cls_to_register):
304
+ if function_name in cls.functions:
305
+ raise Exception( # noqa: TRY002
306
+ f"Unable to add DataPipe function name {function_name} as it is already taken"
307
+ )
308
+
309
+ def class_function(cls, source_dp, *args, **kwargs):
310
+ result_pipe = cls(source_dp, *args, **kwargs)
311
+ return result_pipe
312
+
313
+ function = functools.partial(class_function, cls_to_register)
314
+ functools.update_wrapper(
315
+ wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
316
+ )
317
+ cls.functions[function_name] = function
318
+
319
+ def __getstate__(self):
320
+ """
321
+ Serialize `lambda` functions when `dill` is available.
322
+
323
+ If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
324
+ `__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
325
+ """
326
+ state = self.__dict__
327
+ if MapDataPipe.getstate_hook is not None:
328
+ return MapDataPipe.getstate_hook(state)
329
+ return state
330
+
331
+ def __reduce_ex__(self, *args, **kwargs):
332
+ if MapDataPipe.reduce_ex_hook is not None:
333
+ try:
334
+ return MapDataPipe.reduce_ex_hook(self)
335
+ except NotImplementedError:
336
+ pass
337
+ return super().__reduce_ex__(*args, **kwargs)
338
+
339
+ @classmethod
340
+ def set_getstate_hook(cls, hook_fn):
341
+ if MapDataPipe.getstate_hook is not None and hook_fn is not None:
342
+ raise RuntimeError("Attempt to override existing getstate_hook")
343
+ MapDataPipe.getstate_hook = hook_fn
344
+
345
+ @classmethod
346
+ def set_reduce_ex_hook(cls, hook_fn):
347
+ if MapDataPipe.reduce_ex_hook is not None and hook_fn is not None:
348
+ raise RuntimeError("Attempt to override existing reduce_ex_hook")
349
+ MapDataPipe.reduce_ex_hook = hook_fn
350
+
351
+ def __repr__(self):
352
+ if self.repr_hook is not None:
353
+ return self.repr_hook(self)
354
+ # Instead of showing <torch. ... .MapperMapDataPipe object at 0x.....>, return the class name
355
+ return str(self.__class__.__qualname__)
356
+
357
+ def __str__(self):
358
+ if self.str_hook is not None:
359
+ return self.str_hook(self)
360
+ # Instead of showing <torch. ... .MapperMapDataPipe object at 0x.....>, return the class name
361
+ return str(self.__class__.__qualname__)
362
+
363
+ def __dir__(self):
364
+ # for auto-completion in a REPL (e.g. Jupyter notebook)
365
+ return list(super().__dir__()) + list(self.functions.keys())
366
+
367
+
368
+ class _DataPipeSerializationWrapper:
369
+ def __init__(self, datapipe):
370
+ self._datapipe = datapipe
371
+
372
+ def __getstate__(self):
373
+ use_dill = False
374
+ try:
375
+ value = pickle.dumps(self._datapipe)
376
+ except Exception:
377
+ if HAS_DILL:
378
+ value = dill.dumps(self._datapipe)
379
+ use_dill = True
380
+ else:
381
+ raise
382
+ return (value, use_dill)
383
+
384
+ def __setstate__(self, state):
385
+ value, use_dill = state
386
+ if use_dill:
387
+ self._datapipe = dill.loads(value)
388
+ else:
389
+ self._datapipe = pickle.loads(value)
390
+
391
+ def __len__(self):
392
+ try:
393
+ return len(self._datapipe)
394
+ except Exception as e:
395
+ raise TypeError(
396
+ f"{type(self).__name__} instance doesn't have valid length"
397
+ ) from e
398
+
399
+
400
+ class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe):
401
+ def __init__(self, datapipe: IterDataPipe[_T_co]):
402
+ super().__init__(datapipe)
403
+ self._datapipe_iter: Optional[Iterator[_T_co]] = None
404
+
405
+ def __iter__(self) -> "_IterDataPipeSerializationWrapper":
406
+ self._datapipe_iter = iter(self._datapipe)
407
+ return self
408
+
409
+ def __next__(self) -> _T_co: # type: ignore[type-var]
410
+ assert self._datapipe_iter is not None
411
+ return next(self._datapipe_iter)
412
+
413
+
414
+ class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe):
415
+ def __getitem__(self, idx):
416
+ return self._datapipe[idx]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/datapipe.pyi ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @generated by torch/utils/data/datapipes/gen_pyi.py from datapipe.pyi.in
2
+ # mypy: allow-untyped-defs
3
+ # This base template ("datapipe.pyi.in") is generated from mypy stubgen with minimal editing for code injection
4
+ # The output file will be "datapipe.pyi". This is executed as part of torch/CMakeLists.txt
5
+ # Note that, for mypy, .pyi file takes precedent over .py file, such that we must define the interface for other
6
+ # classes/objects here, even though we are not injecting extra code into them at the moment.
7
+
8
+ from collections.abc import Iterable, Iterator
9
+ from typing import Any, Callable, Literal, Optional, TypeVar, Union
10
+
11
+ from torch.utils.data import Dataset, default_collate, IterableDataset
12
+ from torch.utils.data.datapipes._hook_iterator import _SnapshotState
13
+ from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta
14
+
15
+ _T = TypeVar("_T")
16
+ _T_co = TypeVar("_T_co", covariant=True)
17
+ UNTRACABLE_DATAFRAME_PIPES: Any
18
+
19
+ class DataChunk(list[_T]):
20
+ items: list[_T]
21
+ def __init__(self, items: Iterable[_T]) -> None: ...
22
+ def as_str(self, indent: str = "") -> str: ...
23
+ def __iter__(self) -> Iterator[_T]: ...
24
+ def raw_iterator(self) -> Iterator[_T]: ...
25
+
26
+ class MapDataPipe(Dataset[_T_co], metaclass=_DataPipeMeta):
27
+ functions: dict[str, Callable] = ...
28
+ reduce_ex_hook: Callable | None = ...
29
+ getstate_hook: Callable | None = ...
30
+ str_hook: Callable | None = ...
31
+ repr_hook: Callable | None = ...
32
+ def __getattr__(self, attribute_name: Any): ...
33
+ @classmethod
34
+ def register_function(cls, function_name: Any, function: Any) -> None: ...
35
+ @classmethod
36
+ def register_datapipe_as_function(
37
+ cls,
38
+ function_name: Any,
39
+ cls_to_register: Any,
40
+ ): ...
41
+ def __getstate__(self): ...
42
+ def __reduce_ex__(self, *args: Any, **kwargs: Any): ...
43
+ @classmethod
44
+ def set_getstate_hook(cls, hook_fn: Any) -> None: ...
45
+ @classmethod
46
+ def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ...
47
+ # Functional form of 'BatcherMapDataPipe'
48
+ def batch(
49
+ self,
50
+ batch_size: int,
51
+ drop_last: bool = False,
52
+ wrapper_class: type[DataChunk] = DataChunk,
53
+ ) -> MapDataPipe:
54
+ r"""
55
+ Create mini-batches of data (functional name: ``batch``).
56
+
57
+ An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``,
58
+ or ``length % batch_size`` for the last batch if ``drop_last`` is set to ``False``.
59
+
60
+ Args:
61
+ datapipe: Iterable DataPipe being batched
62
+ batch_size: The size of each batch
63
+ drop_last: Option to drop the last batch if it's not full
64
+
65
+ Example:
66
+ >>> # xdoctest: +SKIP
67
+ >>> from torchdata.datapipes.map import SequenceWrapper
68
+ >>> dp = SequenceWrapper(range(10))
69
+ >>> batch_dp = dp.batch(batch_size=2)
70
+ >>> list(batch_dp)
71
+ [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
72
+ """
73
+ # Functional form of 'ConcaterMapDataPipe'
74
+ def concat(self, *datapipes: MapDataPipe) -> MapDataPipe:
75
+ r"""
76
+ Concatenate multiple Map DataPipes (functional name: ``concat``).
77
+
78
+ The new index of is the cumulative sum of source DataPipes.
79
+ For example, if there are 2 source DataPipes both with length 5,
80
+ index 0 to 4 of the resulting `ConcatMapDataPipe` would refer to
81
+ elements of the first DataPipe, and 5 to 9 would refer to elements
82
+ of the second DataPipe.
83
+
84
+ Args:
85
+ datapipes: Map DataPipes being concatenated
86
+
87
+ Example:
88
+ >>> # xdoctest: +SKIP
89
+ >>> from torchdata.datapipes.map import SequenceWrapper
90
+ >>> dp1 = SequenceWrapper(range(3))
91
+ >>> dp2 = SequenceWrapper(range(3))
92
+ >>> concat_dp = dp1.concat(dp2)
93
+ >>> list(concat_dp)
94
+ [0, 1, 2, 0, 1, 2]
95
+ """
96
+ # Functional form of 'MapperMapDataPipe'
97
+ def map(self, fn: Callable = ...) -> MapDataPipe:
98
+ r"""
99
+ Apply the input function over each item from the source DataPipe (functional name: ``map``).
100
+
101
+ The function can be any regular Python function or partial object. Lambda
102
+ function is not recommended as it is not supported by pickle.
103
+
104
+ Args:
105
+ datapipe: Source MapDataPipe
106
+ fn: Function being applied to each item
107
+
108
+ Example:
109
+ >>> # xdoctest: +SKIP
110
+ >>> from torchdata.datapipes.map import SequenceWrapper, Mapper
111
+ >>> def add_one(x):
112
+ ... return x + 1
113
+ >>> dp = SequenceWrapper(range(10))
114
+ >>> map_dp_1 = dp.map(add_one)
115
+ >>> list(map_dp_1)
116
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
117
+ >>> map_dp_2 = Mapper(dp, lambda x: x + 1)
118
+ >>> list(map_dp_2)
119
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
120
+ """
121
+ # Functional form of 'ShufflerIterDataPipe'
122
+ def shuffle(self, *, indices: Optional[list] = None) -> IterDataPipe:
123
+ r"""
124
+ Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``).
125
+
126
+ When it is used with :class:`~torch.utils.data.DataLoader`, the methods to
127
+ set up random seed are different based on :attr:`num_workers`.
128
+
129
+ For single-process mode (:attr:`num_workers == 0`), the random seed is set before
130
+ the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
131
+ mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed
132
+ for each worker process.
133
+
134
+ Args:
135
+ datapipe: MapDataPipe being shuffled
136
+ indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing
137
+
138
+ Example:
139
+ >>> # xdoctest: +SKIP
140
+ >>> from torchdata.datapipes.map import SequenceWrapper
141
+ >>> dp = SequenceWrapper(range(10))
142
+ >>> shuffle_dp = dp.shuffle().set_seed(0)
143
+ >>> list(shuffle_dp)
144
+ [7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
145
+ >>> list(shuffle_dp)
146
+ [6, 1, 9, 5, 2, 4, 7, 3, 8, 0]
147
+ >>> # Reset seed for Shuffler
148
+ >>> shuffle_dp = shuffle_dp.set_seed(0)
149
+ >>> list(shuffle_dp)
150
+ [7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
151
+
152
+ Note:
153
+ Even thought this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an
154
+ ``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to
155
+ the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order
156
+ of data during data-processing.
157
+ """
158
+ # Functional form of 'ZipperMapDataPipe'
159
+ def zip(self, *datapipes: MapDataPipe[_T_co]) -> MapDataPipe:
160
+ r"""
161
+ Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
162
+
163
+ This MataPipe is out of bound as soon as the shortest input DataPipe is exhausted.
164
+
165
+ Args:
166
+ *datapipes: Map DataPipes being aggregated
167
+
168
+ Example:
169
+ >>> # xdoctest: +SKIP
170
+ >>> from torchdata.datapipes.map import SequenceWrapper
171
+ >>> dp1 = SequenceWrapper(range(3))
172
+ >>> dp2 = SequenceWrapper(range(10, 13))
173
+ >>> zip_dp = dp1.zip(dp2)
174
+ >>> list(zip_dp)
175
+ [(0, 10), (1, 11), (2, 12)]
176
+ """
177
+
178
+ class IterDataPipe(IterableDataset[_T_co], metaclass=_IterDataPipeMeta):
179
+ functions: dict[str, Callable] = ...
180
+ reduce_ex_hook: Optional[Callable] = ...
181
+ getstate_hook: Optional[Callable] = ...
182
+ str_hook: Optional[Callable] = ...
183
+ repr_hook: Optional[Callable] = ...
184
+ _number_of_samples_yielded: int = ...
185
+ _snapshot_state: _SnapshotState = _SnapshotState.Iterating # noqa: PYI015
186
+ _fast_forward_iterator: Optional[Iterator] = ...
187
+ def __getattr__(self, attribute_name: Any): ...
188
+ @classmethod
189
+ def register_function(cls, function_name: Any, function: Any) -> None: ...
190
+ @classmethod
191
+ def register_datapipe_as_function(
192
+ cls,
193
+ function_name: Any,
194
+ cls_to_register: Any,
195
+ enable_df_api_tracing: bool = ...,
196
+ ): ...
197
+ def __getstate__(self): ...
198
+ def __reduce_ex__(self, *args: Any, **kwargs: Any): ...
199
+ @classmethod
200
+ def set_getstate_hook(cls, hook_fn: Any) -> None: ...
201
+ @classmethod
202
+ def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ...
203
+ # Functional form of 'BatcherIterDataPipe'
204
+ def batch(
205
+ self,
206
+ batch_size: int,
207
+ drop_last: bool = False,
208
+ wrapper_class: type[DataChunk] = DataChunk,
209
+ ) -> IterDataPipe:
210
+ r"""
211
+ Creates mini-batches of data (functional name: ``batch``).
212
+
213
+ An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the
214
+ last batch if ``drop_last`` is set to ``False``.
215
+
216
+ Args:
217
+ datapipe: Iterable DataPipe being batched
218
+ batch_size: The size of each batch
219
+ drop_last: Option to drop the last batch if it's not full
220
+ wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding,
221
+ defaults to ``DataChunk``
222
+
223
+ Example:
224
+ >>> # xdoctest: +SKIP
225
+ >>> from torchdata.datapipes.iter import IterableWrapper
226
+ >>> dp = IterableWrapper(range(10))
227
+ >>> dp = dp.batch(batch_size=3, drop_last=True)
228
+ >>> list(dp)
229
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
230
+ """
231
+ # Functional form of 'CollatorIterDataPipe'
232
+ def collate(
233
+ self,
234
+ conversion: Union[Callable[..., Any], dict[Union[str, Any], Union[Callable, Any]], None] = default_collate,
235
+ collate_fn: Optional[Callable] = None,
236
+ ) -> IterDataPipe: # fmt: skip
237
+ r"""
238
+ Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``).
239
+
240
+ By default, it uses :func:`torch.utils.data.default_collate`.
241
+
242
+ .. note::
243
+ While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the
244
+ default behavior and `functools.partial` to specify any additional arguments.
245
+
246
+ Args:
247
+ datapipe: Iterable DataPipe being collated
248
+ collate_fn: Customized collate function to collect and combine data or a batch of data.
249
+ Default function collates to Tensor(s) based on data type.
250
+
251
+ Example:
252
+ >>> # xdoctest: +SKIP
253
+ >>> # Convert integer data to float Tensor
254
+ >>> class MyIterDataPipe(torch.utils.data.IterDataPipe):
255
+ ... def __init__(self, start, end):
256
+ ... super(MyIterDataPipe).__init__()
257
+ ... assert end > start, "this example code only works with end >= start"
258
+ ... self.start = start
259
+ ... self.end = end
260
+ ...
261
+ ... def __iter__(self):
262
+ ... return iter(range(self.start, self.end))
263
+ ...
264
+ ... def __len__(self):
265
+ ... return self.end - self.start
266
+ ...
267
+ >>> ds = MyIterDataPipe(start=3, end=7)
268
+ >>> print(list(ds))
269
+ [3, 4, 5, 6]
270
+ >>> def collate_fn(batch):
271
+ ... return torch.tensor(batch, dtype=torch.float)
272
+ ...
273
+ >>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn)
274
+ >>> print(list(collated_ds))
275
+ [tensor(3.), tensor(4.), tensor(5.), tensor(6.)]
276
+ """
277
+ # Functional form of 'ConcaterIterDataPipe'
278
+ def concat(self, *datapipes: IterDataPipe) -> IterDataPipe:
279
+ r"""
280
+ Concatenates multiple Iterable DataPipes (functional name: ``concat``).
281
+
282
+ The resulting DataPipe will yield all the elements from the first input DataPipe, before yielding from the subsequent ones.
283
+
284
+ Args:
285
+ datapipes: Iterable DataPipes being concatenated
286
+
287
+ Example:
288
+ >>> # xdoctest: +REQUIRES(module:torchdata)
289
+ >>> import random
290
+ >>> from torchdata.datapipes.iter import IterableWrapper
291
+ >>> dp1 = IterableWrapper(range(3))
292
+ >>> dp2 = IterableWrapper(range(5))
293
+ >>> list(dp1.concat(dp2))
294
+ [0, 1, 2, 0, 1, 2, 3, 4]
295
+ """
296
+ # Functional form of 'DemultiplexerIterDataPipe'
297
+ def demux(
298
+ self,
299
+ num_instances: int,
300
+ classifier_fn: Callable[[_T_co], Optional[int]],
301
+ drop_none: bool = False,
302
+ buffer_size: int = 1000,
303
+ ) -> list[IterDataPipe]:
304
+ r"""
305
+ Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``).
306
+
307
+ A list of the child DataPipes is returned from this operation.
308
+
309
+ Args:
310
+ datapipe: Iterable DataPipe being filtered
311
+ num_instances: number of instances of the DataPipe to create
312
+ classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None``
313
+ drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None``
314
+ buffer_size: this defines the maximum number of inputs that the buffer can hold across all child
315
+ DataPipes while waiting for their values to be yielded.
316
+ Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
317
+
318
+ Examples:
319
+ >>> # xdoctest: +REQUIRES(module:torchdata)
320
+ >>> from torchdata.datapipes.iter import IterableWrapper
321
+ >>> def odd_or_even(n):
322
+ ... return n % 2
323
+ >>> source_dp = IterableWrapper(range(5))
324
+ >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even)
325
+ >>> list(dp1)
326
+ [0, 2, 4]
327
+ >>> list(dp2)
328
+ [1, 3]
329
+ >>> # It can also filter out any element that gets `None` from the `classifier_fn`
330
+ >>> def odd_or_even_no_zero(n):
331
+ ... return n % 2 if n != 0 else None
332
+ >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True)
333
+ >>> list(dp1)
334
+ [2, 4]
335
+ >>> list(dp2)
336
+ [1, 3]
337
+ """
338
+ # Functional form of 'FilterIterDataPipe'
339
+ def filter(self, filter_fn: Callable, input_col=None) -> IterDataPipe:
340
+ r"""
341
+ Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``).
342
+
343
+ Args:
344
+ datapipe: Iterable DataPipe being filtered
345
+ filter_fn: Customized function mapping an element to a boolean.
346
+ input_col: Index or indices of data which ``filter_fn`` is applied, such as:
347
+
348
+ - ``None`` as default to apply ``filter_fn`` to the data directly.
349
+ - Integer(s) is used for list/tuple.
350
+ - Key(s) is used for dict.
351
+
352
+ Example:
353
+ >>> # xdoctest: +SKIP
354
+ >>> from torchdata.datapipes.iter import IterableWrapper
355
+ >>> def is_even(n):
356
+ ... return n % 2 == 0
357
+ >>> dp = IterableWrapper(range(5))
358
+ >>> filter_dp = dp.filter(filter_fn=is_even)
359
+ >>> list(filter_dp)
360
+ [0, 2, 4]
361
+ """
362
+ # Functional form of 'ForkerIterDataPipe'
363
+ def fork(
364
+ self,
365
+ num_instances: int,
366
+ buffer_size: int = 1000,
367
+ copy: Optional[Literal["shallow", "deep"]] = None,
368
+ ) -> list[IterDataPipe]:
369
+ r"""
370
+ Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``).
371
+
372
+ Args:
373
+ datapipe: Iterable DataPipe being copied
374
+ num_instances: number of instances of the datapipe to create
375
+ buffer_size: this restricts how far ahead the leading child DataPipe
376
+ can read relative to the slowest child DataPipe.
377
+ Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
378
+ copy: copy strategy to use for items yielded by each branch. Supported
379
+ options are ``None`` for no copying, ``"shallow"`` for shallow object
380
+ copies, and ``"deep"`` for deep object copies. Defaults to ``None``.
381
+
382
+ Note:
383
+ All branches of the forked pipeline return the identical object unless
384
+ the copy parameter is supplied. If the object is mutable or contains
385
+ mutable objects, changing them in one branch will affect all others.
386
+
387
+ Example:
388
+ >>> # xdoctest: +REQUIRES(module:torchdata)
389
+ >>> from torchdata.datapipes.iter import IterableWrapper
390
+ >>> source_dp = IterableWrapper(range(5))
391
+ >>> dp1, dp2 = source_dp.fork(num_instances=2)
392
+ >>> list(dp1)
393
+ [0, 1, 2, 3, 4]
394
+ >>> list(dp2)
395
+ [0, 1, 2, 3, 4]
396
+ """
397
+ # Functional form of 'GrouperIterDataPipe'
398
+ def groupby(
399
+ self,
400
+ group_key_fn: Callable[[_T_co], Any],
401
+ *,
402
+ keep_key: bool = False,
403
+ buffer_size: int = 10000,
404
+ group_size: Optional[int] = None,
405
+ guaranteed_group_size: Optional[int] = None,
406
+ drop_remaining: bool = False,
407
+ ) -> IterDataPipe:
408
+ r"""
409
+ Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``.
410
+
411
+ (functional name: ``groupby``).
412
+
413
+ The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group
414
+ will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full,
415
+ the DataPipe will yield the largest batch with the same key, provided that its size is larger
416
+ than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``.
417
+
418
+ After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity
419
+ will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``.
420
+
421
+ Args:
422
+ datapipe: Iterable datapipe to be grouped
423
+ group_key_fn: Function used to generate group key from the data of the source datapipe
424
+ keep_key: Option to yield the matching key along with the items in a tuple,
425
+ resulting in `(key, [items])` otherwise returning [items]
426
+ buffer_size: The size of buffer for ungrouped data
427
+ group_size: The max size of each group, a batch is yielded as soon as it reaches this size
428
+ guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full
429
+ drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer
430
+ when the buffer is full
431
+
432
+ Example:
433
+ >>> import os
434
+ >>> # xdoctest: +SKIP
435
+ >>> from torchdata.datapipes.iter import IterableWrapper
436
+ >>> def group_fn(file):
437
+ ... return os.path.basename(file).split(".")[0]
438
+ >>> source_dp = IterableWrapper(["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"])
439
+ >>> dp0 = source_dp.groupby(group_key_fn=group_fn)
440
+ >>> list(dp0)
441
+ [['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']]
442
+ >>> # A group is yielded as soon as its size equals to `group_size`
443
+ >>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2)
444
+ >>> list(dp1)
445
+ [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
446
+ >>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size`
447
+ >>> dp2 = source_dp.groupby(group_key_fn=group_fn, buffer_size=3, group_size=3, guaranteed_group_size=2)
448
+ >>> list(dp2)
449
+ [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
450
+ """
451
+ # Functional form of 'FileListerIterDataPipe'
452
+ def list_files(
453
+ self,
454
+ masks: Union[str, list[str]] = "",
455
+ *,
456
+ recursive: bool = False,
457
+ abspath: bool = False,
458
+ non_deterministic: bool = False,
459
+ length: int = -1,
460
+ ) -> IterDataPipe:
461
+ r"""
462
+ Given path(s) to the root directory, yields file pathname(s) (path + filename) of files within the root directory.
463
+
464
+ Multiple root directories can be provided (functional name: ``list_files``).
465
+
466
+ Args:
467
+ root: Root directory or a sequence of root directories
468
+ masks: Unix style filter string or string list for filtering file name(s)
469
+ recursive: Whether to return pathname from nested directories or not
470
+ abspath: Whether to return relative pathname or absolute pathname
471
+ non_deterministic: Whether to return pathname in sorted order or not.
472
+ If ``False``, the results yielded from each root directory will be sorted
473
+ length: Nominal length of the datapipe
474
+
475
+ Example:
476
+ >>> # xdoctest: +SKIP
477
+ >>> from torchdata.datapipes.iter import FileLister
478
+ >>> dp = FileLister(root=".", recursive=True)
479
+ >>> list(dp)
480
+ ['example.py', './data/data.tar']
481
+ """
482
+ # Functional form of 'MapperIterDataPipe'
483
+ def map(
484
+ self,
485
+ fn: Callable,
486
+ input_col=None,
487
+ output_col=None,
488
+ ) -> IterDataPipe:
489
+ r"""
490
+ Applies a function over each item from the source DataPipe (functional name: ``map``).
491
+
492
+ The function can be any regular Python function or partial object. Lambda
493
+ function is not recommended as it is not supported by pickle.
494
+
495
+ Args:
496
+ datapipe: Source Iterable DataPipe
497
+ fn: Function being applied over each item
498
+ input_col: Index or indices of data which ``fn`` is applied, such as:
499
+
500
+ - ``None`` as default to apply ``fn`` to the data directly.
501
+ - Integer(s) is used for list/tuple.
502
+ - Key(s) is used for dict.
503
+
504
+ output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified
505
+ only when ``input_col`` is not ``None``
506
+
507
+ - ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with
508
+ multiple indices, the left-most one is used, and other indices will be removed.
509
+ - Integer is used for list/tuple. ``-1`` represents to append result at the end.
510
+ - Key is used for dict. New key is acceptable.
511
+
512
+ Example:
513
+ >>> # xdoctest: +SKIP
514
+ >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
515
+ >>> def add_one(x):
516
+ ... return x + 1
517
+ >>> dp = IterableWrapper(range(10))
518
+ >>> map_dp_1 = dp.map(add_one) # Invocation via functional form is preferred
519
+ >>> list(map_dp_1)
520
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
521
+ >>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle`
522
+ >>> # Use `functools.partial` or explicitly define the function instead
523
+ >>> map_dp_2 = Mapper(dp, lambda x: x + 1)
524
+ >>> list(map_dp_2)
525
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
526
+ """
527
+ # Functional form of 'MultiplexerIterDataPipe'
528
+ def mux(self, *datapipes) -> IterDataPipe:
529
+ r"""
530
+ Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``).
531
+
532
+ As in, one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration,
533
+ and so on. It ends when the shortest input DataPipe is exhausted.
534
+
535
+ Args:
536
+ datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted
537
+
538
+ Example:
539
+ >>> # xdoctest: +REQUIRES(module:torchdata)
540
+ >>> from torchdata.datapipes.iter import IterableWrapper
541
+ >>> dp1, dp2, dp3 = IterableWrapper(range(3)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
542
+ >>> list(dp1.mux(dp2, dp3))
543
+ [0, 10, 20, 1, 11, 21, 2, 12, 22]
544
+ """
545
+ # Functional form of 'FileOpenerIterDataPipe'
546
+ def open_files(
547
+ self,
548
+ mode: str = "r",
549
+ encoding: Optional[str] = None,
550
+ length: int = -1,
551
+ ) -> IterDataPipe:
552
+ r"""
553
+ Given pathnames, opens files and yield pathname and file stream in a tuple (functional name: ``open_files``).
554
+
555
+ Args:
556
+ datapipe: Iterable datapipe that provides pathnames
557
+ mode: An optional string that specifies the mode in which
558
+ the file is opened by ``open()``. It defaults to ``r``, other options are
559
+ ``b`` for reading in binary mode and ``t`` for text mode.
560
+ encoding: An optional string that specifies the encoding of the
561
+ underlying file. It defaults to ``None`` to match the default encoding of ``open``.
562
+ length: Nominal length of the datapipe
563
+
564
+ Note:
565
+ The opened file handles will be closed by Python's GC periodically. Users can choose
566
+ to close them explicitly.
567
+
568
+ Example:
569
+ >>> # xdoctest: +SKIP
570
+ >>> from torchdata.datapipes.iter import FileLister, FileOpener, StreamReader
571
+ >>> dp = FileLister(root=".").filter(lambda fname: fname.endswith('.txt'))
572
+ >>> dp = FileOpener(dp)
573
+ >>> dp = StreamReader(dp)
574
+ >>> list(dp)
575
+ [('./abc.txt', 'abc')]
576
+ """
577
+ # Functional form of 'StreamReaderIterDataPipe'
578
+ def read_from_stream(self, chunk: Optional[int] = None) -> IterDataPipe:
579
+ r"""
580
+ Given IO streams and their label names, yield bytes with label name as tuple.
581
+
582
+ (functional name: ``read_from_stream``).
583
+
584
+ Args:
585
+ datapipe: Iterable DataPipe provides label/URL and byte stream
586
+ chunk: Number of bytes to be read from stream per iteration.
587
+ If ``None``, all bytes will be read until the EOF.
588
+
589
+ Example:
590
+ >>> # xdoctest: +SKIP
591
+ >>> from torchdata.datapipes.iter import IterableWrapper, StreamReader
592
+ >>> from io import StringIO
593
+ >>> dp = IterableWrapper([("alphabet", StringIO("abcde"))])
594
+ >>> list(StreamReader(dp, chunk=1))
595
+ [('alphabet', 'a'), ('alphabet', 'b'), ('alphabet', 'c'), ('alphabet', 'd'), ('alphabet', 'e')]
596
+ """
597
+ # Functional form of 'RoutedDecoderIterDataPipe'
598
+ def routed_decode(
599
+ self,
600
+ *handlers: Callable,
601
+ key_fn: Callable = ...,
602
+ ) -> IterDataPipe:
603
+ r"""
604
+ Decodes binary streams from input DataPipe, yields pathname and decoded data in a tuple.
605
+
606
+ (functional name: ``routed_decode``)
607
+
608
+ Args:
609
+ datapipe: Iterable datapipe that provides pathname and binary stream in tuples
610
+ handlers: Optional user defined decoder handlers. If ``None``, basic and image decoder
611
+ handlers will be set as default. If multiple handles are provided, the priority
612
+ order follows the order of handlers (the first handler has the top priority)
613
+ key_fn: Function for decoder to extract key from pathname to dispatch handlers.
614
+ Default is set to extract file extension from pathname
615
+
616
+ Note:
617
+ When ``key_fn`` is specified returning anything other than extension, the default
618
+ handler will not work and users need to specify custom handler. Custom handler
619
+ could use regex to determine the eligibility to handle data.
620
+ """
621
+ # Functional form of 'ShardingFilterIterDataPipe'
622
+ def sharding_filter(self, sharding_group_filter=None) -> IterDataPipe:
623
+ r"""
624
+ Wrapper that allows DataPipe to be sharded (functional name: ``sharding_filter``).
625
+
626
+ After ``apply_sharding`` is called, each instance of the DataPipe (on different workers) will have every `n`-th element of the
627
+ original DataPipe, where `n` equals to the number of instances.
628
+
629
+ Args:
630
+ source_datapipe: Iterable DataPipe that will be sharded
631
+ """
632
+ # Functional form of 'ShufflerIterDataPipe'
633
+ def shuffle(
634
+ self,
635
+ *,
636
+ buffer_size: int = 10000,
637
+ unbatch_level: int = 0,
638
+ ) -> IterDataPipe:
639
+ r"""
640
+ Shuffle the input DataPipe with a buffer (functional name: ``shuffle``).
641
+
642
+ The buffer with ``buffer_size`` is filled with elements from the datapipe first. Then,
643
+ each item will be yielded from the buffer by reservoir sampling via iterator.
644
+
645
+ ``buffer_size`` is required to be larger than ``0``. For ``buffer_size == 1``, the
646
+ datapipe is not shuffled. In order to fully shuffle all elements from datapipe,
647
+ ``buffer_size`` is required to be greater than or equal to the size of datapipe.
648
+
649
+ When it is used with :class:`torch.utils.data.DataLoader`, the methods to
650
+ set up random seed are different based on :attr:`num_workers`.
651
+
652
+ For single-process mode (:attr:`num_workers == 0`), the random seed is set before
653
+ the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
654
+ mode (:attr:`num_worker > 0`), `worker_init_fn` is used to set up a random seed
655
+ for each worker process.
656
+
657
+ Args:
658
+ datapipe: The IterDataPipe being shuffled
659
+ buffer_size: The buffer size for shuffling (default to ``10000``)
660
+ unbatch_level: Specifies if it is necessary to unbatch source data before
661
+ applying the shuffle
662
+
663
+ Example:
664
+ >>> # xdoctest: +SKIP
665
+ >>> from torchdata.datapipes.iter import IterableWrapper
666
+ >>> dp = IterableWrapper(range(10))
667
+ >>> shuffle_dp = dp.shuffle()
668
+ >>> list(shuffle_dp)
669
+ [0, 4, 1, 6, 3, 2, 9, 5, 7, 8]
670
+ """
671
+ # Functional form of 'UnBatcherIterDataPipe'
672
+ def unbatch(self, unbatch_level: int = 1) -> IterDataPipe:
673
+ r"""
674
+ Undos batching of data (functional name: ``unbatch``).
675
+
676
+ In other words, it flattens the data up to the specified level within a batched DataPipe.
677
+
678
+ Args:
679
+ datapipe: Iterable DataPipe being un-batched
680
+ unbatch_level: Defaults to ``1`` (only flattening the top level). If set to ``2``,
681
+ it will flatten the top two levels, and ``-1`` will flatten the entire DataPipe.
682
+
683
+ Example:
684
+ >>> # xdoctest: +SKIP
685
+ >>> from torchdata.datapipes.iter import IterableWrapper
686
+ >>> source_dp = IterableWrapper([[[0, 1], [2]], [[3, 4], [5]], [[6]]])
687
+ >>> dp1 = source_dp.unbatch()
688
+ >>> list(dp1)
689
+ [[0, 1], [2], [3, 4], [5], [6]]
690
+ >>> dp2 = source_dp.unbatch(unbatch_level=2)
691
+ >>> list(dp2)
692
+ [0, 1, 2, 3, 4, 5, 6]
693
+ """
694
+ # Functional form of 'ZipperIterDataPipe'
695
+ def zip(self, *datapipes: IterDataPipe) -> IterDataPipe:
696
+ r"""
697
+ Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
698
+
699
+ The output is stopped as soon as the shortest input DataPipe is exhausted.
700
+
701
+ Args:
702
+ *datapipes: Iterable DataPipes being aggregated
703
+
704
+ Example:
705
+ >>> # xdoctest: +REQUIRES(module:torchdata)
706
+ >>> from torchdata.datapipes.iter import IterableWrapper
707
+ >>> dp1, dp2, dp3 = IterableWrapper(range(5)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
708
+ >>> list(dp1.zip(dp2, dp3))
709
+ [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)]
710
+ """
711
+
712
+ class DFIterDataPipe(IterDataPipe):
713
+ def _is_dfpipe(self): ...
714
+ def __iter__(self): ...
715
+
716
+ class _DataPipeSerializationWrapper:
717
+ def __init__(self, datapipe): ...
718
+ def __getstate__(self): ...
719
+ def __setstate__(self, state): ...
720
+ def __len__(self): ...
721
+
722
+ class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe):
723
+ def __iter__(self): ...
724
+
725
+ class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe):
726
+ def __getitem__(self, idx): ...
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/gen_pyi.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import os
3
+ from collections import defaultdict
4
+ from pathlib import Path
5
+ from typing import Any, Union
6
+ from typing_extensions import deprecated
7
+
8
+
9
+ try:
10
+ from torchgen.api.python import format_function_signature
11
+ from torchgen.utils import FileManager as FileManager
12
+ except ImportError:
13
+ import sys
14
+
15
+ REPO_ROOT = Path(__file__).absolute().parents[4]
16
+ sys.path.insert(0, str(REPO_ROOT))
17
+
18
+ from torchgen.api.python import format_function_signature
19
+ from torchgen.utils import FileManager
20
+
21
+ if len(sys.path) > 0 and sys.path[0] == str(REPO_ROOT):
22
+ del sys.path[0]
23
+
24
+
25
+ __all__: list[str] = [] # not intended to expose any symbols
26
+
27
+
28
+ def __dir__() -> list[str]:
29
+ return [] # appease public API test
30
+
31
+
32
+ @deprecated(
33
+ "`torch.utils.data.datapipes.gen_pyi.materialize_lines` is deprecated and will be removed in the future.",
34
+ category=FutureWarning,
35
+ )
36
+ def materialize_lines(lines: list[str], indentation: int) -> str:
37
+ output = ""
38
+ new_line_with_indent = "\n" + " " * indentation
39
+ for i, line in enumerate(lines):
40
+ if i != 0:
41
+ output += new_line_with_indent
42
+ output += line.replace("\n", new_line_with_indent)
43
+ return output
44
+
45
+
46
+ @deprecated(
47
+ "`torch.utils.data.datapipes.gen_pyi.gen_from_template` is deprecated and will be removed in the future.",
48
+ category=FutureWarning,
49
+ )
50
+ def gen_from_template(
51
+ dir: str,
52
+ template_name: str,
53
+ output_name: str,
54
+ replacements: list[tuple[str, Any, int]],
55
+ ):
56
+ template_path = os.path.join(dir, template_name)
57
+ output_path = os.path.join(dir, output_name)
58
+
59
+ with open(template_path, encoding="utf-8") as f:
60
+ content = f.read()
61
+ for placeholder, lines, indentation in replacements:
62
+ with open(output_path, "w", encoding="utf-8") as f:
63
+ content = content.replace(
64
+ placeholder, materialize_lines(lines, indentation)
65
+ )
66
+ f.write(content)
67
+
68
+
69
+ def find_file_paths(dir_paths: list[str], files_to_exclude: set[str]) -> set[str]:
70
+ """
71
+ When given a path to a directory, returns the paths to the relevant files within it.
72
+
73
+ This function does NOT recursive traverse to subdirectories.
74
+ """
75
+ paths: set[str] = set()
76
+ for dir_path in dir_paths:
77
+ all_files = os.listdir(dir_path)
78
+ python_files = {fname for fname in all_files if ".py" == fname[-3:]}
79
+ filter_files = {
80
+ fname for fname in python_files if fname not in files_to_exclude
81
+ }
82
+ paths.update({os.path.join(dir_path, fname) for fname in filter_files})
83
+ return paths
84
+
85
+
86
+ def extract_method_name(line: str) -> str:
87
+ """Extract method name from decorator in the form of "@functional_datapipe({method_name})"."""
88
+ if '("' in line:
89
+ start_token, end_token = '("', '")'
90
+ elif "('" in line:
91
+ start_token, end_token = "('", "')"
92
+ else:
93
+ raise RuntimeError(
94
+ f"Unable to find appropriate method name within line:\n{line}"
95
+ )
96
+ start, end = line.find(start_token) + len(start_token), line.find(end_token)
97
+ return line[start:end]
98
+
99
+
100
+ def extract_class_name(line: str) -> str:
101
+ """Extract class name from class definition in the form of "class {CLASS_NAME}({Type}):"."""
102
+ start_token = "class "
103
+ end_token = "("
104
+ start, end = line.find(start_token) + len(start_token), line.find(end_token)
105
+ return line[start:end]
106
+
107
+
108
+ def parse_datapipe_file(
109
+ file_path: str,
110
+ ) -> tuple[dict[str, list[str]], dict[str, str], set[str], dict[str, list[str]]]:
111
+ """Given a path to file, parses the file and returns a dictionary of method names to function signatures."""
112
+ method_to_signature, method_to_class_name, special_output_type = {}, {}, set()
113
+ doc_string_dict = defaultdict(list)
114
+ with open(file_path, encoding="utf-8") as f:
115
+ open_paren_count = 0
116
+ method_name, class_name, signature = "", "", ""
117
+ skip = False
118
+ for line in f:
119
+ if line.count('"""') % 2 == 1:
120
+ skip = not skip
121
+ if skip or '"""' in line: # Saving docstrings
122
+ doc_string_dict[method_name].append(line)
123
+ continue
124
+ if "@functional_datapipe" in line:
125
+ method_name = extract_method_name(line)
126
+ doc_string_dict[method_name] = []
127
+ continue
128
+ if method_name and "class " in line:
129
+ class_name = extract_class_name(line)
130
+ continue
131
+ if method_name and ("def __init__(" in line or "def __new__(" in line):
132
+ if "def __new__(" in line:
133
+ special_output_type.add(method_name)
134
+ open_paren_count += 1
135
+ start = line.find("(") + len("(")
136
+ line = line[start:]
137
+ if open_paren_count > 0:
138
+ open_paren_count += line.count("(")
139
+ open_paren_count -= line.count(")")
140
+ if open_paren_count == 0:
141
+ end = line.rfind(")")
142
+ signature += line[:end]
143
+ method_to_signature[method_name] = process_signature(signature)
144
+ method_to_class_name[method_name] = class_name
145
+ method_name, class_name, signature = "", "", ""
146
+ elif open_paren_count < 0:
147
+ raise RuntimeError(
148
+ "open parenthesis count < 0. This shouldn't be possible."
149
+ )
150
+ else:
151
+ signature += line.strip()
152
+ return (
153
+ method_to_signature,
154
+ method_to_class_name,
155
+ special_output_type,
156
+ doc_string_dict,
157
+ )
158
+
159
+
160
+ def parse_datapipe_files(
161
+ file_paths: set[str],
162
+ ) -> tuple[dict[str, list[str]], dict[str, str], set[str], dict[str, list[str]]]:
163
+ methods_and_signatures = {}
164
+ methods_and_class_names = {}
165
+ methods_with_special_output_types = set()
166
+ methods_and_doc_strings = {}
167
+ for path in file_paths:
168
+ (
169
+ method_to_signature,
170
+ method_to_class_name,
171
+ methods_needing_special_output_types,
172
+ doc_string_dict,
173
+ ) = parse_datapipe_file(path)
174
+ methods_and_signatures.update(method_to_signature)
175
+ methods_and_class_names.update(method_to_class_name)
176
+ methods_with_special_output_types.update(methods_needing_special_output_types)
177
+ methods_and_doc_strings.update(doc_string_dict)
178
+ return (
179
+ methods_and_signatures,
180
+ methods_and_class_names,
181
+ methods_with_special_output_types,
182
+ methods_and_doc_strings,
183
+ )
184
+
185
+
186
+ def split_outside_bracket(line: str, delimiter: str = ",") -> list[str]:
187
+ """Given a line of text, split it on comma unless the comma is within a bracket '[]'."""
188
+ bracket_count = 0
189
+ curr_token = ""
190
+ res = []
191
+ for char in line:
192
+ if char == "[":
193
+ bracket_count += 1
194
+ elif char == "]":
195
+ bracket_count -= 1
196
+ elif char == delimiter and bracket_count == 0:
197
+ res.append(curr_token)
198
+ curr_token = ""
199
+ continue
200
+ curr_token += char
201
+ res.append(curr_token)
202
+ return res
203
+
204
+
205
+ def process_signature(line: str) -> list[str]:
206
+ """
207
+ Clean up a given raw function signature.
208
+
209
+ This includes removing the self-referential datapipe argument, default
210
+ arguments of input functions, newlines, and spaces.
211
+ """
212
+ tokens: list[str] = split_outside_bracket(line)
213
+ for i, token in enumerate(tokens):
214
+ tokens[i] = token.strip(" ")
215
+ if token == "cls":
216
+ tokens[i] = "self"
217
+ elif i > 0 and ("self" == tokens[i - 1]) and (tokens[i][0] != "*"):
218
+ # Remove the datapipe after 'self' or 'cls' unless it has '*'
219
+ tokens[i] = ""
220
+ elif "Callable =" in token: # Remove default argument if it is a function
221
+ head = token.rpartition("=")[0]
222
+ tokens[i] = head.strip(" ") + " = ..."
223
+ tokens = [t for t in tokens if t != ""]
224
+ return tokens
225
+
226
+
227
+ def get_method_definitions(
228
+ file_path: Union[str, list[str]],
229
+ files_to_exclude: set[str],
230
+ deprecated_files: set[str],
231
+ default_output_type: str,
232
+ method_to_special_output_type: dict[str, str],
233
+ root: str = "",
234
+ ) -> list[str]:
235
+ """
236
+ #.pyi generation for functional DataPipes Process.
237
+
238
+ # 1. Find files that we want to process (exclude the ones who don't)
239
+ # 2. Parse method name and signature
240
+ # 3. Remove first argument after self (unless it is "*datapipes"), default args, and spaces
241
+ """
242
+ if root == "":
243
+ root = str(Path(__file__).parent.resolve())
244
+ file_path = [file_path] if isinstance(file_path, str) else file_path
245
+ file_path = [os.path.join(root, path) for path in file_path]
246
+ file_paths = find_file_paths(
247
+ file_path, files_to_exclude=files_to_exclude.union(deprecated_files)
248
+ )
249
+ (
250
+ methods_and_signatures,
251
+ methods_and_class_names,
252
+ methods_w_special_output_types,
253
+ methods_and_doc_strings,
254
+ ) = parse_datapipe_files(file_paths)
255
+
256
+ for fn_name in method_to_special_output_type:
257
+ if fn_name not in methods_w_special_output_types:
258
+ methods_w_special_output_types.add(fn_name)
259
+
260
+ method_definitions = []
261
+ for method_name, arguments in methods_and_signatures.items():
262
+ class_name = methods_and_class_names[method_name]
263
+ if method_name in methods_w_special_output_types:
264
+ output_type = method_to_special_output_type[method_name]
265
+ else:
266
+ output_type = default_output_type
267
+ doc_string = "".join(methods_and_doc_strings[method_name])
268
+ if doc_string == "":
269
+ doc_string = " ..."
270
+ else:
271
+ doc_string = "\n" + doc_string
272
+ definition = format_function_signature(method_name, arguments, output_type)
273
+ method_definitions.append(
274
+ f"# Functional form of '{class_name}'\n"
275
+ + definition.removesuffix("...").rstrip() # remove "..."
276
+ + doc_string,
277
+ )
278
+ method_definitions.sort(
279
+ key=lambda s: s.split("\n")[1]
280
+ ) # sorting based on method_name
281
+
282
+ return method_definitions
283
+
284
+
285
+ # Defined outside of main() so they can be imported by TorchData
286
+ iterDP_file_path: str = "iter"
287
+ iterDP_files_to_exclude: set[str] = {"__init__.py", "utils.py"}
288
+ iterDP_deprecated_files: set[str] = set()
289
+ iterDP_method_to_special_output_type: dict[str, str] = {
290
+ "demux": "list[IterDataPipe]",
291
+ "fork": "list[IterDataPipe]",
292
+ }
293
+
294
+ mapDP_file_path: str = "map"
295
+ mapDP_files_to_exclude: set[str] = {"__init__.py", "utils.py"}
296
+ mapDP_deprecated_files: set[str] = set()
297
+ mapDP_method_to_special_output_type: dict[str, str] = {"shuffle": "IterDataPipe"}
298
+
299
+
300
+ def main() -> None:
301
+ """
302
+ # Inject file into template datapipe.pyi.in.
303
+
304
+ TODO: The current implementation of this script only generates interfaces for built-in methods. To generate
305
+ interface for user-defined DataPipes, consider changing `IterDataPipe.register_datapipe_as_function`.
306
+ """
307
+ iter_method_definitions = get_method_definitions(
308
+ iterDP_file_path,
309
+ iterDP_files_to_exclude,
310
+ iterDP_deprecated_files,
311
+ "IterDataPipe",
312
+ iterDP_method_to_special_output_type,
313
+ )
314
+
315
+ map_method_definitions = get_method_definitions(
316
+ mapDP_file_path,
317
+ mapDP_files_to_exclude,
318
+ mapDP_deprecated_files,
319
+ "MapDataPipe",
320
+ mapDP_method_to_special_output_type,
321
+ )
322
+
323
+ path = Path(__file__).absolute().parent
324
+ fm = FileManager(install_dir=path, template_dir=path, dry_run=False)
325
+ fm.write_with_template(
326
+ "datapipe.pyi",
327
+ "datapipe.pyi.in",
328
+ lambda: {
329
+ "IterDataPipeMethods": iter_method_definitions,
330
+ "MapDataPipeMethods": map_method_definitions,
331
+ },
332
+ )
333
+
334
+
335
+ if __name__ == "__main__":
336
+ main()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data.datapipes.iter.callable import (
2
+ CollatorIterDataPipe as Collator,
3
+ MapperIterDataPipe as Mapper,
4
+ )
5
+ from torch.utils.data.datapipes.iter.combinatorics import (
6
+ SamplerIterDataPipe as Sampler,
7
+ ShufflerIterDataPipe as Shuffler,
8
+ )
9
+ from torch.utils.data.datapipes.iter.combining import (
10
+ ConcaterIterDataPipe as Concater,
11
+ DemultiplexerIterDataPipe as Demultiplexer,
12
+ ForkerIterDataPipe as Forker,
13
+ MultiplexerIterDataPipe as Multiplexer,
14
+ ZipperIterDataPipe as Zipper,
15
+ )
16
+ from torch.utils.data.datapipes.iter.filelister import (
17
+ FileListerIterDataPipe as FileLister,
18
+ )
19
+ from torch.utils.data.datapipes.iter.fileopener import (
20
+ FileOpenerIterDataPipe as FileOpener,
21
+ )
22
+ from torch.utils.data.datapipes.iter.grouping import (
23
+ BatcherIterDataPipe as Batcher,
24
+ GrouperIterDataPipe as Grouper,
25
+ UnBatcherIterDataPipe as UnBatcher,
26
+ )
27
+ from torch.utils.data.datapipes.iter.routeddecoder import (
28
+ RoutedDecoderIterDataPipe as RoutedDecoder,
29
+ )
30
+ from torch.utils.data.datapipes.iter.selecting import FilterIterDataPipe as Filter
31
+ from torch.utils.data.datapipes.iter.sharding import (
32
+ ShardingFilterIterDataPipe as ShardingFilter,
33
+ )
34
+ from torch.utils.data.datapipes.iter.streamreader import (
35
+ StreamReaderIterDataPipe as StreamReader,
36
+ )
37
+ from torch.utils.data.datapipes.iter.utils import (
38
+ IterableWrapperIterDataPipe as IterableWrapper,
39
+ )
40
+
41
+
42
+ __all__ = [
43
+ "Batcher",
44
+ "Collator",
45
+ "Concater",
46
+ "Demultiplexer",
47
+ "FileLister",
48
+ "FileOpener",
49
+ "Filter",
50
+ "Forker",
51
+ "Grouper",
52
+ "IterableWrapper",
53
+ "Mapper",
54
+ "Multiplexer",
55
+ "RoutedDecoder",
56
+ "Sampler",
57
+ "ShardingFilter",
58
+ "Shuffler",
59
+ "StreamReader",
60
+ "UnBatcher",
61
+ "Zipper",
62
+ ]
63
+
64
+ # Please keep this list sorted
65
+ assert __all__ == sorted(__all__)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/callable.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from collections import namedtuple
4
+ from collections.abc import Iterator, Sized
5
+ from typing import Any, Callable, Optional, TypeVar, Union
6
+
7
+ from torch.utils.data._utils.collate import default_collate
8
+ from torch.utils.data.datapipes._decorator import functional_datapipe
9
+ from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
10
+ from torch.utils.data.datapipes.datapipe import IterDataPipe
11
+ from torch.utils.data.datapipes.utils.common import (
12
+ _check_unpickable_fn,
13
+ validate_input_col,
14
+ )
15
+
16
+
17
+ __all__ = [
18
+ "CollatorIterDataPipe",
19
+ "MapperIterDataPipe",
20
+ ]
21
+
22
+
23
+ _T_co = TypeVar("_T_co", covariant=True)
24
+
25
+
26
+ @functional_datapipe("map")
27
+ class MapperIterDataPipe(IterDataPipe[_T_co]):
28
+ r"""
29
+ Applies a function over each item from the source DataPipe (functional name: ``map``).
30
+
31
+ The function can be any regular Python function or partial object. Lambda
32
+ function is not recommended as it is not supported by pickle.
33
+
34
+ Args:
35
+ datapipe: Source Iterable DataPipe
36
+ fn: Function being applied over each item
37
+ input_col: Index or indices of data which ``fn`` is applied, such as:
38
+
39
+ - ``None`` as default to apply ``fn`` to the data directly.
40
+ - Integer(s) is used for list/tuple.
41
+ - Key(s) is used for dict.
42
+
43
+ output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified
44
+ only when ``input_col`` is not ``None``
45
+
46
+ - ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with
47
+ multiple indices, the left-most one is used, and other indices will be removed.
48
+ - Integer is used for list/tuple. ``-1`` represents to append result at the end.
49
+ - Key is used for dict. New key is acceptable.
50
+
51
+ Example:
52
+ >>> # xdoctest: +SKIP
53
+ >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
54
+ >>> def add_one(x):
55
+ ... return x + 1
56
+ >>> dp = IterableWrapper(range(10))
57
+ >>> map_dp_1 = dp.map(add_one) # Invocation via functional form is preferred
58
+ >>> list(map_dp_1)
59
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
60
+ >>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle`
61
+ >>> # Use `functools.partial` or explicitly define the function instead
62
+ >>> map_dp_2 = Mapper(dp, lambda x: x + 1)
63
+ >>> list(map_dp_2)
64
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
65
+ """
66
+
67
+ datapipe: IterDataPipe
68
+ fn: Callable
69
+
70
+ def __init__(
71
+ self,
72
+ datapipe: IterDataPipe,
73
+ fn: Callable,
74
+ input_col=None,
75
+ output_col=None,
76
+ ) -> None:
77
+ super().__init__()
78
+ self.datapipe = datapipe
79
+
80
+ _check_unpickable_fn(fn)
81
+ self.fn = fn # type: ignore[assignment]
82
+
83
+ self.input_col = input_col
84
+ if input_col is None and output_col is not None:
85
+ raise ValueError("`output_col` must be None when `input_col` is None.")
86
+ if isinstance(output_col, (list, tuple)):
87
+ if len(output_col) > 1:
88
+ raise ValueError("`output_col` must be a single-element list or tuple")
89
+ output_col = output_col[0]
90
+ self.output_col = output_col
91
+ validate_input_col(fn, input_col)
92
+
93
+ def _apply_fn(self, data):
94
+ if self.input_col is None and self.output_col is None:
95
+ return self.fn(data)
96
+
97
+ if self.input_col is None:
98
+ res = self.fn(data)
99
+ elif isinstance(self.input_col, (list, tuple)):
100
+ args = tuple(data[col] for col in self.input_col)
101
+ res = self.fn(*args)
102
+ else:
103
+ res = self.fn(data[self.input_col])
104
+
105
+ # Copy tuple to list and run in-place modification because tuple is immutable.
106
+ if isinstance(data, tuple):
107
+ t_flag = True
108
+ data = list(data)
109
+ else:
110
+ t_flag = False
111
+
112
+ if self.output_col is None:
113
+ if isinstance(self.input_col, (list, tuple)):
114
+ data[self.input_col[0]] = res
115
+ for idx in sorted(self.input_col[1:], reverse=True):
116
+ del data[idx]
117
+ else:
118
+ data[self.input_col] = res
119
+ else:
120
+ if self.output_col == -1:
121
+ data.append(res)
122
+ else:
123
+ data[self.output_col] = res
124
+
125
+ # Convert list back to tuple
126
+ return tuple(data) if t_flag else data
127
+
128
+ def __iter__(self) -> Iterator[_T_co]:
129
+ for data in self.datapipe:
130
+ yield self._apply_fn(data)
131
+
132
+ def __len__(self) -> int:
133
+ if isinstance(self.datapipe, Sized):
134
+ return len(self.datapipe)
135
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
136
+
137
+
138
+ def _collate_helper(conversion, item):
139
+ # TODO(VitalyFedyunin): Verify that item is any sort of batch
140
+ if len(item.items) > 1:
141
+ # TODO(VitalyFedyunin): Compact all batch dataframes into one
142
+ raise RuntimeError("Only supports one DataFrame per batch")
143
+ df = item[0]
144
+ columns_name = df_wrapper.get_columns(df)
145
+ tuple_names: list = []
146
+ tuple_values: list = []
147
+
148
+ for name in conversion.keys():
149
+ if name not in columns_name:
150
+ raise RuntimeError("Conversion keys missmatch")
151
+
152
+ for name in columns_name:
153
+ if name in conversion:
154
+ if not callable(conversion[name]):
155
+ raise RuntimeError(
156
+ "Collate (DF)DataPipe requires callable as dict values"
157
+ )
158
+ collation_fn = conversion[name]
159
+ else:
160
+ # TODO(VitalyFedyunin): Add default collation into df_wrapper
161
+ try:
162
+ import torcharrow.pytorch as tap # type: ignore[import]
163
+
164
+ collation_fn = tap.rec.Default()
165
+ except Exception as e:
166
+ raise RuntimeError(
167
+ "unable to import default collation function from the TorchArrow"
168
+ ) from e
169
+
170
+ tuple_names.append(str(name))
171
+ value = collation_fn(df[name])
172
+ tuple_values.append(value)
173
+
174
+ # TODO(VitalyFedyunin): We can dynamically extract types from the tuple_values here
175
+ # TODO(VitalyFedyunin): Instead of ignoring mypy error, make sure tuple_names is not empty
176
+ tpl_cls = namedtuple("CollateResult", tuple_names) # type: ignore[misc]
177
+ tuple = tpl_cls(*tuple_values)
178
+ return tuple
179
+
180
+
181
+ @functional_datapipe("collate")
182
+ class CollatorIterDataPipe(MapperIterDataPipe):
183
+ r"""
184
+ Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``).
185
+
186
+ By default, it uses :func:`torch.utils.data.default_collate`.
187
+
188
+ .. note::
189
+ While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the
190
+ default behavior and `functools.partial` to specify any additional arguments.
191
+
192
+ Args:
193
+ datapipe: Iterable DataPipe being collated
194
+ collate_fn: Customized collate function to collect and combine data or a batch of data.
195
+ Default function collates to Tensor(s) based on data type.
196
+
197
+ Example:
198
+ >>> # xdoctest: +SKIP
199
+ >>> # Convert integer data to float Tensor
200
+ >>> class MyIterDataPipe(torch.utils.data.IterDataPipe):
201
+ ... def __init__(self, start, end):
202
+ ... super(MyIterDataPipe).__init__()
203
+ ... assert end > start, "this example code only works with end >= start"
204
+ ... self.start = start
205
+ ... self.end = end
206
+ ...
207
+ ... def __iter__(self):
208
+ ... return iter(range(self.start, self.end))
209
+ ...
210
+ ... def __len__(self):
211
+ ... return self.end - self.start
212
+ ...
213
+ >>> ds = MyIterDataPipe(start=3, end=7)
214
+ >>> print(list(ds))
215
+ [3, 4, 5, 6]
216
+ >>> def collate_fn(batch):
217
+ ... return torch.tensor(batch, dtype=torch.float)
218
+ ...
219
+ >>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn)
220
+ >>> print(list(collated_ds))
221
+ [tensor(3.), tensor(4.), tensor(5.), tensor(6.)]
222
+ """
223
+
224
+ def __init__(
225
+ self,
226
+ datapipe: IterDataPipe,
227
+ conversion: Union[
228
+ Callable[..., Any], dict[Union[str, Any], Union[Callable, Any]], None
229
+ ] = default_collate,
230
+ collate_fn: Optional[Callable] = None,
231
+ ) -> None:
232
+ # TODO(VitalyFedyunin): Replace `Callable[..., Any]` with `Callable[[IColumn], Any]`
233
+ # TODO(VitalyFedyunin): Replace with `Dict[Union[str, IColumn], Union[Callable, Enum]]`
234
+ if collate_fn is not None:
235
+ super().__init__(datapipe, fn=collate_fn)
236
+ else:
237
+ if callable(conversion):
238
+ super().__init__(datapipe, fn=conversion)
239
+ else:
240
+ # TODO(VitalyFedyunin): Validate passed dictionary
241
+ collate_fn = functools.partial(_collate_helper, conversion)
242
+ super().__init__(datapipe, fn=collate_fn)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/combinatorics.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import random
3
+ from collections.abc import Iterator, Sized
4
+ from typing import Optional, TypeVar
5
+
6
+ import torch
7
+ from torch.utils.data.datapipes._decorator import functional_datapipe
8
+ from torch.utils.data.datapipes.datapipe import IterDataPipe
9
+ from torch.utils.data.sampler import Sampler, SequentialSampler
10
+
11
+
12
+ __all__ = [
13
+ "SamplerIterDataPipe",
14
+ "ShufflerIterDataPipe",
15
+ ]
16
+
17
+
18
+ _T_co = TypeVar("_T_co", covariant=True)
19
+
20
+
21
+ class SamplerIterDataPipe(IterDataPipe[_T_co]):
22
+ r"""
23
+ Generate sample elements using the provided ``Sampler`` (defaults to :class:`SequentialSampler`).
24
+
25
+ Args:
26
+ datapipe: IterDataPipe to sample from
27
+ sampler: Sampler class to generate sample elements from input DataPipe.
28
+ Default is :class:`SequentialSampler` for IterDataPipe
29
+ """
30
+
31
+ datapipe: IterDataPipe
32
+ sampler: Sampler
33
+
34
+ def __init__(
35
+ self,
36
+ datapipe: IterDataPipe,
37
+ sampler: type[Sampler] = SequentialSampler,
38
+ sampler_args: Optional[tuple] = None,
39
+ sampler_kwargs: Optional[dict] = None,
40
+ ) -> None:
41
+ assert isinstance(
42
+ datapipe, Sized
43
+ ), "Sampler class requires input datapipe implemented `__len__`"
44
+ super().__init__()
45
+ self.datapipe = datapipe
46
+ self.sampler_args = () if sampler_args is None else sampler_args
47
+ self.sampler_kwargs = {} if sampler_kwargs is None else sampler_kwargs
48
+ # https://github.com/python/mypy/pull/9629 will solve
49
+ self.sampler = sampler(*self.sampler_args, data_source=self.datapipe, **self.sampler_kwargs) # type: ignore[misc]
50
+
51
+ def __iter__(self) -> Iterator[_T_co]:
52
+ return iter(self.sampler)
53
+
54
+ def __len__(self) -> int:
55
+ # Dataset has been tested as `Sized`
56
+ if isinstance(self.sampler, Sized):
57
+ return len(self.sampler)
58
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
59
+
60
+
61
+ @functional_datapipe("shuffle")
62
+ class ShufflerIterDataPipe(IterDataPipe[_T_co]):
63
+ r"""
64
+ Shuffle the input DataPipe with a buffer (functional name: ``shuffle``).
65
+
66
+ The buffer with ``buffer_size`` is filled with elements from the datapipe first. Then,
67
+ each item will be yielded from the buffer by reservoir sampling via iterator.
68
+
69
+ ``buffer_size`` is required to be larger than ``0``. For ``buffer_size == 1``, the
70
+ datapipe is not shuffled. In order to fully shuffle all elements from datapipe,
71
+ ``buffer_size`` is required to be greater than or equal to the size of datapipe.
72
+
73
+ When it is used with :class:`torch.utils.data.DataLoader`, the methods to
74
+ set up random seed are different based on :attr:`num_workers`.
75
+
76
+ For single-process mode (:attr:`num_workers == 0`), the random seed is set before
77
+ the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
78
+ mode (:attr:`num_worker > 0`), `worker_init_fn` is used to set up a random seed
79
+ for each worker process.
80
+
81
+ Args:
82
+ datapipe: The IterDataPipe being shuffled
83
+ buffer_size: The buffer size for shuffling (default to ``10000``)
84
+ unbatch_level: Specifies if it is necessary to unbatch source data before
85
+ applying the shuffle
86
+
87
+ Example:
88
+ >>> # xdoctest: +SKIP
89
+ >>> from torchdata.datapipes.iter import IterableWrapper
90
+ >>> dp = IterableWrapper(range(10))
91
+ >>> shuffle_dp = dp.shuffle()
92
+ >>> list(shuffle_dp)
93
+ [0, 4, 1, 6, 3, 2, 9, 5, 7, 8]
94
+ """
95
+
96
+ datapipe: IterDataPipe[_T_co]
97
+ buffer_size: int
98
+ _buffer: list[_T_co]
99
+ _enabled: bool
100
+ _seed: Optional[int]
101
+ _rng: random.Random
102
+
103
+ def __init__(
104
+ self,
105
+ datapipe: IterDataPipe[_T_co],
106
+ *,
107
+ buffer_size: int = 10000,
108
+ unbatch_level: int = 0,
109
+ ) -> None:
110
+ super().__init__()
111
+ # TODO: Performance optimization
112
+ # buffer can be a fixed size and remove expensive `append()` and `len()` operations
113
+ self._buffer: list[_T_co] = []
114
+ assert buffer_size > 0, "buffer_size should be larger than 0"
115
+ if unbatch_level == 0:
116
+ self.datapipe = datapipe
117
+ else:
118
+ self.datapipe = datapipe.unbatch(unbatch_level=unbatch_level)
119
+ self.buffer_size = buffer_size
120
+ self._enabled = True
121
+ self._seed = None
122
+ self._rng = random.Random()
123
+
124
+ def set_shuffle(self, shuffle=True):
125
+ self._enabled = shuffle
126
+ return self
127
+
128
+ def set_seed(self, seed: int):
129
+ self._seed = seed
130
+ return self
131
+
132
+ def __iter__(self) -> Iterator[_T_co]:
133
+ if not self._enabled:
134
+ yield from self.datapipe
135
+ else:
136
+ for x in self.datapipe:
137
+ if len(self._buffer) == self.buffer_size:
138
+ idx = self._rng.randint(0, len(self._buffer) - 1)
139
+ val, self._buffer[idx] = self._buffer[idx], x
140
+ yield val
141
+ else:
142
+ self._buffer.append(x)
143
+ while self._buffer:
144
+ idx = self._rng.randint(0, len(self._buffer) - 1)
145
+ yield self._buffer.pop(idx)
146
+
147
+ def __len__(self) -> int:
148
+ if isinstance(self.datapipe, Sized):
149
+ return len(self.datapipe)
150
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
151
+
152
+ def reset(self) -> None:
153
+ self._buffer = []
154
+ if self._enabled:
155
+ if self._seed is None:
156
+ self._seed = int(torch.empty((), dtype=torch.int64).random_().item())
157
+ self._rng.seed(self._seed)
158
+ self._seed = None
159
+
160
+ def __getstate__(self):
161
+ state = (
162
+ self.datapipe,
163
+ self.buffer_size,
164
+ self._enabled,
165
+ self._seed,
166
+ self._buffer,
167
+ self._rng.getstate(),
168
+ self._valid_iterator_id,
169
+ self._number_of_samples_yielded,
170
+ )
171
+ if IterDataPipe.getstate_hook is not None:
172
+ return IterDataPipe.getstate_hook(state)
173
+ return state
174
+
175
+ def __setstate__(self, state):
176
+ (
177
+ self.datapipe,
178
+ self.buffer_size,
179
+ self._enabled,
180
+ self._seed,
181
+ self._buffer,
182
+ rng_state,
183
+ self._valid_iterator_id,
184
+ self._number_of_samples_yielded,
185
+ ) = state
186
+ self._rng = random.Random()
187
+ self._rng.setstate(rng_state)
188
+
189
+ def __del__(self):
190
+ self._buffer.clear()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/combining.py ADDED
@@ -0,0 +1,696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy as copymodule
3
+ import warnings
4
+ from abc import ABC, abstractmethod
5
+ from collections import deque
6
+ from collections.abc import Iterator, Sized
7
+ from typing import Any, Callable, Literal, Optional, TypeVar
8
+
9
+ from torch.utils.data.datapipes._decorator import functional_datapipe
10
+ from torch.utils.data.datapipes._hook_iterator import _SnapshotState
11
+ from torch.utils.data.datapipes.datapipe import IterDataPipe
12
+ from torch.utils.data.datapipes.utils.common import _check_unpickable_fn, StreamWrapper
13
+
14
+
15
+ __all__ = [
16
+ "ConcaterIterDataPipe",
17
+ "DemultiplexerIterDataPipe",
18
+ "ForkerIterDataPipe",
19
+ "MultiplexerIterDataPipe",
20
+ "ZipperIterDataPipe",
21
+ ]
22
+
23
+
24
+ _T_co = TypeVar("_T_co", covariant=True)
25
+
26
+
27
+ @functional_datapipe("concat")
28
+ class ConcaterIterDataPipe(IterDataPipe):
29
+ r"""
30
+ Concatenates multiple Iterable DataPipes (functional name: ``concat``).
31
+
32
+ The resulting DataPipe will yield all the elements from the first input DataPipe, before yielding from the subsequent ones.
33
+
34
+ Args:
35
+ datapipes: Iterable DataPipes being concatenated
36
+
37
+ Example:
38
+ >>> # xdoctest: +REQUIRES(module:torchdata)
39
+ >>> import random
40
+ >>> from torchdata.datapipes.iter import IterableWrapper
41
+ >>> dp1 = IterableWrapper(range(3))
42
+ >>> dp2 = IterableWrapper(range(5))
43
+ >>> list(dp1.concat(dp2))
44
+ [0, 1, 2, 0, 1, 2, 3, 4]
45
+ """
46
+
47
+ datapipes: tuple[IterDataPipe]
48
+
49
+ def __init__(self, *datapipes: IterDataPipe):
50
+ if len(datapipes) == 0:
51
+ raise ValueError("Expected at least one DataPipe, but got nothing")
52
+ if not all(isinstance(dp, IterDataPipe) for dp in datapipes):
53
+ raise TypeError("Expected all inputs to be `IterDataPipe`")
54
+ self.datapipes = datapipes # type: ignore[assignment]
55
+
56
+ def __iter__(self) -> Iterator:
57
+ for dp in self.datapipes:
58
+ yield from dp
59
+
60
+ def __len__(self) -> int:
61
+ if all(isinstance(dp, Sized) for dp in self.datapipes):
62
+ return sum(len(dp) for dp in self.datapipes)
63
+ else:
64
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
65
+
66
+
67
+ @functional_datapipe("fork")
68
+ class ForkerIterDataPipe(IterDataPipe):
69
+ r"""
70
+ Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``).
71
+
72
+ Args:
73
+ datapipe: Iterable DataPipe being copied
74
+ num_instances: number of instances of the datapipe to create
75
+ buffer_size: this restricts how far ahead the leading child DataPipe
76
+ can read relative to the slowest child DataPipe.
77
+ Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
78
+ copy: copy strategy to use for items yielded by each branch. Supported
79
+ options are ``None`` for no copying, ``"shallow"`` for shallow object
80
+ copies, and ``"deep"`` for deep object copies. Defaults to ``None``.
81
+
82
+ Note:
83
+ All branches of the forked pipeline return the identical object unless
84
+ the copy parameter is supplied. If the object is mutable or contains
85
+ mutable objects, changing them in one branch will affect all others.
86
+
87
+ Example:
88
+ >>> # xdoctest: +REQUIRES(module:torchdata)
89
+ >>> from torchdata.datapipes.iter import IterableWrapper
90
+ >>> source_dp = IterableWrapper(range(5))
91
+ >>> dp1, dp2 = source_dp.fork(num_instances=2)
92
+ >>> list(dp1)
93
+ [0, 1, 2, 3, 4]
94
+ >>> list(dp2)
95
+ [0, 1, 2, 3, 4]
96
+ """
97
+
98
+ def __new__(
99
+ cls,
100
+ datapipe: IterDataPipe,
101
+ num_instances: int,
102
+ buffer_size: int = 1000,
103
+ copy: Optional[Literal["shallow", "deep"]] = None,
104
+ ):
105
+ if num_instances < 1:
106
+ raise ValueError(
107
+ f"Expected `num_instances` larger than 0, but {num_instances} is found"
108
+ )
109
+ if num_instances == 1:
110
+ return datapipe
111
+ container = _ForkerIterDataPipe(datapipe, num_instances, buffer_size, copy) # type: ignore[abstract]
112
+ return [_ChildDataPipe(container, i) for i in range(num_instances)]
113
+
114
+
115
+ class _ContainerTemplate(ABC):
116
+ r"""Abstract class for container ``DataPipes``. The followings are three required methods."""
117
+
118
+ @abstractmethod
119
+ def get_next_element_by_instance(self, instance_id: int):
120
+ ...
121
+
122
+ @abstractmethod
123
+ def is_every_instance_exhausted(self) -> bool:
124
+ ...
125
+
126
+ @abstractmethod
127
+ def reset(self) -> None:
128
+ ...
129
+
130
+ @abstractmethod
131
+ def get_length_by_instance(self, instance_id: int):
132
+ r"""Raise TypeError if it's not supposed to be implemented to support `list(datapipe)`."""
133
+
134
+
135
+ def _no_op(x):
136
+ return x
137
+
138
+
139
+ class _ForkerIterDataPipe(IterDataPipe, _ContainerTemplate):
140
+ r"""
141
+ Container to hold instance-specific information on behalf of ForkerIterDataPipe.
142
+
143
+ It tracks the state of its child DataPipes, maintains the buffer, and yields the next value
144
+ as requested by the child DataPipes.
145
+ """
146
+
147
+ def __init__(
148
+ self,
149
+ datapipe: IterDataPipe,
150
+ num_instances: int,
151
+ buffer_size: int = 1000,
152
+ copy: Optional[Literal["shallow", "deep"]] = None,
153
+ ):
154
+ self.main_datapipe = datapipe
155
+ self._datapipe_iterator: Optional[Iterator[Any]] = None
156
+ self.num_instances = num_instances
157
+ self.buffer: deque = deque()
158
+ self.buffer_size = buffer_size
159
+ if self.buffer_size < 0:
160
+ warnings.warn(
161
+ "Unlimited buffer size is set for `fork`, "
162
+ "please be aware of OOM at random places",
163
+ UserWarning,
164
+ )
165
+ if copy is None:
166
+ self.copy_fn = _no_op
167
+ elif copy == "shallow":
168
+ self.copy_fn = copymodule.copy
169
+ elif copy == "deep":
170
+ self.copy_fn = copymodule.deepcopy
171
+ else:
172
+ raise ValueError(
173
+ f"Unknown copy method `{copy}` requested, choose one of None, `shallow` or `deep`."
174
+ )
175
+
176
+ self.child_pointers: list[int] = [
177
+ 0
178
+ ] * num_instances # Indicate the indices of the next element to get
179
+ self.slowest_ptr = 0 # The index to read by the slowest child
180
+ self.leading_ptr = 0 # The index to read by the fastest child
181
+ self.end_ptr: Optional[int] = None # The index to stop child
182
+ self._child_stop: list[bool] = [True for _ in range(num_instances)]
183
+
184
+ def __len__(self):
185
+ return len(self.main_datapipe)
186
+
187
+ def get_next_element_by_instance(self, instance_id: int):
188
+ if self._datapipe_iterator is None and self._child_stop[instance_id]:
189
+ self._datapipe_iterator = iter(self.main_datapipe)
190
+ self._snapshot_state = _SnapshotState.Iterating
191
+ for i in range(self.num_instances):
192
+ self._child_stop[i] = False
193
+ try:
194
+ while not self._child_stop[instance_id]:
195
+ self.child_pointers[instance_id] += 1
196
+ if (
197
+ self.end_ptr is not None
198
+ and self.child_pointers[instance_id] == self.end_ptr
199
+ ):
200
+ self._child_stop[instance_id] = True
201
+ break
202
+ # Use buffer
203
+ if self.buffer and self.child_pointers[instance_id] <= self.leading_ptr:
204
+ idx = self.child_pointers[instance_id] - self.slowest_ptr - 1
205
+ return_val = self.buffer[idx]
206
+ else: # Retrieve one element from main datapipe
207
+ self.leading_ptr = self.child_pointers[instance_id]
208
+ try:
209
+ return_val = next(self._datapipe_iterator) # type: ignore[arg-type]
210
+ self.buffer.append(return_val)
211
+ except StopIteration:
212
+ self._child_stop[instance_id] = True
213
+ self._datapipe_iterator = None
214
+ self.end_ptr = self.leading_ptr
215
+ continue
216
+ if self.child_pointers[instance_id] == self.slowest_ptr + 1:
217
+ new_min = min(
218
+ self.child_pointers
219
+ ) # Can optimize by avoiding the call to min()
220
+ if self.slowest_ptr < new_min:
221
+ self.slowest_ptr = new_min
222
+ self.buffer.popleft()
223
+ if (
224
+ self.buffer_size >= 0
225
+ and self.leading_ptr > self.buffer_size + self.slowest_ptr
226
+ ):
227
+ raise BufferError(
228
+ "ForkerIterDataPipe buffer overflow,"
229
+ + f"buffer size {self.buffer_size} is insufficient."
230
+ )
231
+
232
+ yield self.copy_fn(return_val) # type: ignore[possibly-undefined]
233
+ finally:
234
+ self._child_stop[instance_id] = True
235
+ # Cleanup _datapipe_iterator for the case that fork exits earlier
236
+ if all(self._child_stop):
237
+ self._datapipe_iterator = None
238
+ self._cleanup()
239
+
240
+ def is_every_instance_exhausted(self) -> bool:
241
+ return self.end_ptr is not None and all(self._child_stop)
242
+
243
+ def get_length_by_instance(self, instance_id: int) -> int:
244
+ return len(self.main_datapipe)
245
+
246
+ def reset(self) -> None:
247
+ self._datapipe_iterator = None
248
+ self.buffer = deque()
249
+ self.child_pointers = [0] * self.num_instances
250
+ self.slowest_ptr = 0
251
+ self.leading_ptr = 0
252
+ self.end_ptr = None
253
+ self._child_stop = [True for _ in range(self.num_instances)]
254
+
255
+ def __getstate__(self):
256
+ state = (
257
+ self.main_datapipe,
258
+ self.num_instances,
259
+ self.buffer_size,
260
+ self.copy_fn,
261
+ self._valid_iterator_id,
262
+ self._number_of_samples_yielded,
263
+ )
264
+ if IterDataPipe.getstate_hook is not None:
265
+ return IterDataPipe.getstate_hook(state)
266
+ return state
267
+
268
+ def __setstate__(self, state):
269
+ (
270
+ self.main_datapipe,
271
+ self.num_instances,
272
+ self.buffer_size,
273
+ self.copy_fn,
274
+ self._valid_iterator_id,
275
+ self._number_of_samples_yielded,
276
+ ) = state
277
+ self._datapipe_iterator = None
278
+ self.buffer = deque()
279
+ self.child_pointers = [0] * self.num_instances
280
+ self.slowest_ptr = 0
281
+ self.leading_ptr = 0
282
+ self.end_ptr = None
283
+ self._child_stop = [True for _ in range(self.num_instances)]
284
+
285
+ def _cleanup(self):
286
+ while self.buffer:
287
+ d = self.buffer.popleft()
288
+ StreamWrapper.close_streams(d)
289
+
290
+ def __del__(self):
291
+ self._cleanup()
292
+
293
+
294
+ class _ChildDataPipe(IterDataPipe):
295
+ r"""
296
+ Iterable Datapipe that is a child of a main DataPipe.
297
+
298
+ The instance of this class will pass its instance_id to get the next value from its main DataPipe.
299
+
300
+ Note:
301
+ ChildDataPipe, like all other IterDataPipe, follows the single iterator per IterDataPipe constraint.
302
+ Since ChildDataPipes share a common buffer, when an iterator is created for one of the ChildDataPipes,
303
+ the previous iterators for all ChildDataPipes must be invalidated, with the exception when a ChildDataPipe
304
+ hasn't had an iterator created from it since the last invalidation. See the example below.
305
+
306
+ Example:
307
+ >>> # xdoctest: +REQUIRES(module:torchdata)
308
+ >>> # Singler Iterator per IteraDataPipe Invalidation
309
+ >>> from torchdata.datapipes.iter import IterableWrapper
310
+ >>> source_dp = IterableWrapper(range(10))
311
+ >>> cdp1, cdp2 = source_dp.fork(num_instances=2)
312
+ >>> it1, it2 = iter(cdp1), iter(cdp2)
313
+ >>> it3 = iter(cdp1)
314
+ >>> # The line above invalidates `it1` and `it2`, and resets `ForkerIterDataPipe`.
315
+ >>> it4 = iter(cdp2)
316
+ >>> # The line above doesn't invalidate `it3`, because an iterator for `cdp2` hasn't been created since
317
+ >>> # the last invalidation.
318
+
319
+ Args:
320
+ main_datapipe: Main DataPipe with a method 'get_next_element_by_instance(instance_id)'
321
+ instance_id: integer identifier of this instance
322
+ """
323
+
324
+ _is_child_datapipe: bool = True
325
+
326
+ def __init__(self, main_datapipe: IterDataPipe, instance_id: int):
327
+ assert isinstance(main_datapipe, _ContainerTemplate)
328
+
329
+ self.main_datapipe: IterDataPipe = main_datapipe
330
+ self.instance_id = instance_id
331
+
332
+ def __iter__(self):
333
+ # Note that the logic behind setting iterator ID and `reset` are handled within `hook_iterator`
334
+ # We want to separate the code for reset and yield, so that 'reset' executes before __next__ is called
335
+ return self.main_datapipe.get_next_element_by_instance(self.instance_id)
336
+
337
+ def __len__(self):
338
+ return self.main_datapipe.get_length_by_instance(self.instance_id)
339
+
340
+ # This method is called by `hook_iterator` in `_typing.py`.
341
+ def _set_main_datapipe_valid_iterator_id(self) -> int:
342
+ r"""
343
+ Update the valid iterator ID for both this DataPipe object and `main_datapipe`.
344
+
345
+ `main_datapipe.reset()` is called when the ID is incremented to a new generation.
346
+ """
347
+ # 1. First time any child iterator is created
348
+ if self.main_datapipe._valid_iterator_id is None:
349
+ self.main_datapipe._valid_iterator_id = 0 # type: ignore[attr-defined]
350
+ # 2. This instance was already in the same generation as `main_datapipe`,
351
+ # we need to increment the ID further by 1
352
+ elif self.main_datapipe._valid_iterator_id == self._valid_iterator_id: # type: ignore[has-type]
353
+ self.main_datapipe._valid_iterator_id += 1 # type: ignore[attr-defined]
354
+ # Whenever a new generation of iterator is created, the `main_datapipe` must reset
355
+ if not self.main_datapipe.is_every_instance_exhausted():
356
+ warnings.warn(
357
+ "Some child DataPipes are not exhausted when __iter__ is called. We are resetting "
358
+ "the buffer and each child DataPipe will read from the start again.",
359
+ UserWarning,
360
+ )
361
+ self.main_datapipe.reset()
362
+ # 3. Otherwise, the iterator is behind the others, so it will just need to catch up by setting
363
+ # the instance's iterator to match that of `main_datapipe`
364
+ self._valid_iterator_id = self.main_datapipe._valid_iterator_id
365
+ return self._valid_iterator_id
366
+
367
+ # This method is called by `hook_iterator` in `_typing.py`.
368
+ def _check_valid_iterator_id(self, iterator_id) -> bool:
369
+ r"""Check the valid iterator ID against that of DataPipe object and that of `main_datapipe`."""
370
+ return (
371
+ iterator_id == self._valid_iterator_id
372
+ and iterator_id == self.main_datapipe._valid_iterator_id
373
+ )
374
+
375
+
376
+ @functional_datapipe("demux")
377
+ class DemultiplexerIterDataPipe(IterDataPipe):
378
+ r"""
379
+ Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``).
380
+
381
+ A list of the child DataPipes is returned from this operation.
382
+
383
+ Args:
384
+ datapipe: Iterable DataPipe being filtered
385
+ num_instances: number of instances of the DataPipe to create
386
+ classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None``
387
+ drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None``
388
+ buffer_size: this defines the maximum number of inputs that the buffer can hold across all child
389
+ DataPipes while waiting for their values to be yielded.
390
+ Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
391
+
392
+ Examples:
393
+ >>> # xdoctest: +REQUIRES(module:torchdata)
394
+ >>> from torchdata.datapipes.iter import IterableWrapper
395
+ >>> def odd_or_even(n):
396
+ ... return n % 2
397
+ >>> source_dp = IterableWrapper(range(5))
398
+ >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even)
399
+ >>> list(dp1)
400
+ [0, 2, 4]
401
+ >>> list(dp2)
402
+ [1, 3]
403
+ >>> # It can also filter out any element that gets `None` from the `classifier_fn`
404
+ >>> def odd_or_even_no_zero(n):
405
+ ... return n % 2 if n != 0 else None
406
+ >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True)
407
+ >>> list(dp1)
408
+ [2, 4]
409
+ >>> list(dp2)
410
+ [1, 3]
411
+ """
412
+
413
+ def __new__(
414
+ cls,
415
+ datapipe: IterDataPipe,
416
+ num_instances: int,
417
+ classifier_fn: Callable[[_T_co], Optional[int]],
418
+ drop_none: bool = False,
419
+ buffer_size: int = 1000,
420
+ ):
421
+ if num_instances < 1:
422
+ raise ValueError(
423
+ f"Expected `num_instances` larger than 0, but {num_instances} is found"
424
+ )
425
+
426
+ _check_unpickable_fn(classifier_fn)
427
+
428
+ # When num_instances == 1, demux can be replaced by filter,
429
+ # but keep it as Demultiplexer for the sake of consistency
430
+ # like throwing Error when classification result is out of o range
431
+ container = _DemultiplexerIterDataPipe(datapipe, num_instances, classifier_fn, drop_none, buffer_size) # type: ignore[abstract]
432
+ return [_ChildDataPipe(container, i) for i in range(num_instances)]
433
+
434
+
435
+ class _DemultiplexerIterDataPipe(IterDataPipe, _ContainerTemplate):
436
+ r"""
437
+ Container to hold instance-specific information on behalf of DemultiplexerIterDataPipe.
438
+
439
+ It tracks the state of its child DataPipes, maintains the buffer, classifies and yields the next correct value
440
+ as requested by the child DataPipes.
441
+ """
442
+
443
+ def __init__(
444
+ self,
445
+ datapipe: IterDataPipe[_T_co],
446
+ num_instances: int,
447
+ classifier_fn: Callable[[_T_co], Optional[int]],
448
+ drop_none: bool,
449
+ buffer_size: int,
450
+ ):
451
+ self.main_datapipe = datapipe
452
+ self._datapipe_iterator: Optional[Iterator[Any]] = None
453
+ self.num_instances = num_instances
454
+ self.buffer_size = buffer_size
455
+ if self.buffer_size < 0:
456
+ warnings.warn(
457
+ "Unlimited buffer size is set for `demux`, "
458
+ "please be aware of OOM at random places",
459
+ UserWarning,
460
+ )
461
+ self.current_buffer_usage = 0
462
+ self.child_buffers: list[deque[_T_co]] = [deque() for _ in range(num_instances)]
463
+ self.classifier_fn = classifier_fn
464
+ self.drop_none = drop_none
465
+ self.main_datapipe_exhausted = False
466
+ self._child_stop: list[bool] = [True for _ in range(num_instances)]
467
+
468
+ def _find_next(self, instance_id: int) -> _T_co: # type: ignore[type-var]
469
+ while True:
470
+ if self.main_datapipe_exhausted or self._child_stop[instance_id]:
471
+ raise StopIteration
472
+ if self._datapipe_iterator is None:
473
+ raise ValueError(
474
+ "_datapipe_iterator has not been set, likely because this private method is called directly "
475
+ "without invoking get_next_element_by_instance() first."
476
+ )
477
+ value = next(self._datapipe_iterator)
478
+ classification = self.classifier_fn(value)
479
+ if classification is None and self.drop_none:
480
+ StreamWrapper.close_streams(value)
481
+ continue
482
+ if (
483
+ classification is None
484
+ or classification >= self.num_instances
485
+ or classification < 0
486
+ ):
487
+ raise ValueError(
488
+ f"Output of the classification fn should be between 0 and {self.num_instances - 1}. "
489
+ + f"{classification} is returned."
490
+ )
491
+ if classification == instance_id:
492
+ return value
493
+ self.child_buffers[classification].append(value)
494
+ self.current_buffer_usage += 1
495
+ if self.buffer_size >= 0 and self.current_buffer_usage > self.buffer_size:
496
+ raise BufferError(
497
+ f"DemultiplexerIterDataPipe buffer overflow, buffer size {self.buffer_size} is insufficient."
498
+ )
499
+
500
+ def get_next_element_by_instance(self, instance_id: int):
501
+ if self._datapipe_iterator is None and self._child_stop[instance_id]:
502
+ self._datapipe_iterator = iter(self.main_datapipe)
503
+ self._snapshot_state = (
504
+ _SnapshotState.Iterating
505
+ ) # This is necessary for the DataPipe to reset properly.
506
+ self.main_datapipe_exhausted = False
507
+ for i in range(self.num_instances):
508
+ self._child_stop[i] = False
509
+
510
+ try:
511
+ while not self._child_stop[instance_id]:
512
+ if self.child_buffers[instance_id]:
513
+ self.current_buffer_usage -= 1
514
+ yield self.child_buffers[instance_id].popleft()
515
+ else:
516
+ try:
517
+ yield self._find_next(instance_id)
518
+ except StopIteration:
519
+ self._child_stop[instance_id] = True
520
+ self.main_datapipe_exhausted = True
521
+ self._datapipe_iterator = None
522
+ finally:
523
+ self._child_stop[instance_id] = True
524
+ # Cleanup _datapipe_iterator for the case that demux exits earlier
525
+ if all(self._child_stop):
526
+ self._datapipe_iterator = None
527
+ if self.child_buffers[instance_id]:
528
+ self._cleanup(instance_id)
529
+
530
+ def is_every_instance_exhausted(self) -> bool:
531
+ return self.main_datapipe_exhausted and all(self._child_stop)
532
+
533
+ def get_length_by_instance(self, instance_id: int) -> int:
534
+ raise TypeError
535
+
536
+ def reset(self) -> None:
537
+ self._datapipe_iterator = None
538
+ self.current_buffer_usage = 0
539
+ self.child_buffers = [deque() for _ in range(self.num_instances)]
540
+ self._child_stop = [True for _ in range(self.num_instances)]
541
+ self.main_datapipe_exhausted = False
542
+
543
+ def __getstate__(self):
544
+ state = (
545
+ self.main_datapipe,
546
+ self.num_instances,
547
+ self.buffer_size,
548
+ self.classifier_fn,
549
+ self.drop_none,
550
+ self._valid_iterator_id,
551
+ self._number_of_samples_yielded,
552
+ )
553
+ if IterDataPipe.getstate_hook is not None:
554
+ return IterDataPipe.getstate_hook(state)
555
+ return state
556
+
557
+ def __setstate__(self, state):
558
+ (
559
+ self.main_datapipe,
560
+ self.num_instances,
561
+ self.buffer_size,
562
+ self.classifier_fn,
563
+ self.drop_none,
564
+ self._valid_iterator_id,
565
+ self._number_of_samples_yielded,
566
+ ) = state
567
+ self._datapipe_iterator = None
568
+ self.current_buffer_usage = 0
569
+ self.child_buffers = [deque() for _ in range(self.num_instances)]
570
+ self._child_stop = [True for _ in range(self.num_instances)]
571
+ self.main_datapipe_exhausted = False
572
+
573
+ def _cleanup(self, instance_id: Optional[int] = None):
574
+ ids = (
575
+ range(self.num_instances)
576
+ if instance_id is None
577
+ else [
578
+ instance_id,
579
+ ]
580
+ )
581
+ for i in ids:
582
+ q = self.child_buffers[i]
583
+ while q:
584
+ d = q.popleft()
585
+ StreamWrapper.close_streams(d)
586
+
587
+ def __del__(self):
588
+ self._cleanup()
589
+
590
+
591
+ @functional_datapipe("mux")
592
+ class MultiplexerIterDataPipe(IterDataPipe):
593
+ r"""
594
+ Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``).
595
+
596
+ As in, one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration,
597
+ and so on. It ends when the shortest input DataPipe is exhausted.
598
+
599
+ Args:
600
+ datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted
601
+
602
+ Example:
603
+ >>> # xdoctest: +REQUIRES(module:torchdata)
604
+ >>> from torchdata.datapipes.iter import IterableWrapper
605
+ >>> dp1, dp2, dp3 = IterableWrapper(range(3)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
606
+ >>> list(dp1.mux(dp2, dp3))
607
+ [0, 10, 20, 1, 11, 21, 2, 12, 22]
608
+ """
609
+
610
+ def __init__(self, *datapipes):
611
+ self.datapipes = datapipes
612
+ self.buffer: list = (
613
+ []
614
+ ) # Store values to be yielded only when every iterator provides one
615
+
616
+ def __iter__(self):
617
+ iterators = [iter(x) for x in self.datapipes]
618
+ while len(iterators):
619
+ for it in iterators:
620
+ try:
621
+ value = next(it)
622
+ self.buffer.append(value)
623
+ except StopIteration:
624
+ self.buffer.clear()
625
+ return
626
+ yield from self.buffer
627
+ self.buffer.clear()
628
+
629
+ def __len__(self):
630
+ if all(isinstance(dp, Sized) for dp in self.datapipes):
631
+ return min(len(dp) for dp in self.datapipes) * len(self.datapipes)
632
+ else:
633
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
634
+
635
+ def reset(self) -> None:
636
+ self.buffer = []
637
+
638
+ def __getstate__(self):
639
+ state = (
640
+ self.datapipes,
641
+ self._valid_iterator_id,
642
+ self._number_of_samples_yielded,
643
+ )
644
+ if IterDataPipe.getstate_hook is not None:
645
+ return IterDataPipe.getstate_hook(state)
646
+ return state
647
+
648
+ def __setstate__(self, state):
649
+ (
650
+ self.datapipes,
651
+ self._valid_iterator_id,
652
+ self._number_of_samples_yielded,
653
+ ) = state
654
+ self.buffer = []
655
+
656
+ def __del__(self):
657
+ self.buffer.clear()
658
+
659
+
660
+ @functional_datapipe("zip")
661
+ class ZipperIterDataPipe(IterDataPipe[tuple[_T_co]]):
662
+ r"""
663
+ Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
664
+
665
+ The output is stopped as soon as the shortest input DataPipe is exhausted.
666
+
667
+ Args:
668
+ *datapipes: Iterable DataPipes being aggregated
669
+
670
+ Example:
671
+ >>> # xdoctest: +REQUIRES(module:torchdata)
672
+ >>> from torchdata.datapipes.iter import IterableWrapper
673
+ >>> dp1, dp2, dp3 = IterableWrapper(range(5)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
674
+ >>> list(dp1.zip(dp2, dp3))
675
+ [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)]
676
+ """
677
+
678
+ datapipes: tuple[IterDataPipe]
679
+
680
+ def __init__(self, *datapipes: IterDataPipe):
681
+ if not all(isinstance(dp, IterDataPipe) for dp in datapipes):
682
+ raise TypeError(
683
+ "All inputs are required to be `IterDataPipe` for `ZipIterDataPipe`."
684
+ )
685
+ super().__init__()
686
+ self.datapipes = datapipes # type: ignore[assignment]
687
+
688
+ def __iter__(self) -> Iterator[tuple[_T_co]]:
689
+ iterators = [iter(datapipe) for datapipe in self.datapipes]
690
+ yield from zip(*iterators)
691
+
692
+ def __len__(self) -> int:
693
+ if all(isinstance(dp, Sized) for dp in self.datapipes):
694
+ return min(len(dp) for dp in self.datapipes)
695
+ else:
696
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/filelister.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterator, Sequence
2
+ from typing import Union
3
+
4
+ from torch.utils.data.datapipes._decorator import functional_datapipe
5
+ from torch.utils.data.datapipes.datapipe import IterDataPipe
6
+ from torch.utils.data.datapipes.iter.utils import IterableWrapperIterDataPipe
7
+ from torch.utils.data.datapipes.utils.common import get_file_pathnames_from_root
8
+
9
+
10
+ __all__ = ["FileListerIterDataPipe"]
11
+
12
+
13
+ @functional_datapipe("list_files")
14
+ class FileListerIterDataPipe(IterDataPipe[str]):
15
+ r"""
16
+ Given path(s) to the root directory, yields file pathname(s) (path + filename) of files within the root directory.
17
+
18
+ Multiple root directories can be provided (functional name: ``list_files``).
19
+
20
+ Args:
21
+ root: Root directory or a sequence of root directories
22
+ masks: Unix style filter string or string list for filtering file name(s)
23
+ recursive: Whether to return pathname from nested directories or not
24
+ abspath: Whether to return relative pathname or absolute pathname
25
+ non_deterministic: Whether to return pathname in sorted order or not.
26
+ If ``False``, the results yielded from each root directory will be sorted
27
+ length: Nominal length of the datapipe
28
+
29
+ Example:
30
+ >>> # xdoctest: +SKIP
31
+ >>> from torchdata.datapipes.iter import FileLister
32
+ >>> dp = FileLister(root=".", recursive=True)
33
+ >>> list(dp)
34
+ ['example.py', './data/data.tar']
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ root: Union[str, Sequence[str], IterDataPipe] = ".",
40
+ masks: Union[str, list[str]] = "",
41
+ *,
42
+ recursive: bool = False,
43
+ abspath: bool = False,
44
+ non_deterministic: bool = False,
45
+ length: int = -1,
46
+ ) -> None:
47
+ super().__init__()
48
+ if isinstance(root, str):
49
+ root = [root]
50
+ if not isinstance(root, IterDataPipe):
51
+ root = IterableWrapperIterDataPipe(root)
52
+ self.datapipe: IterDataPipe = root
53
+ self.masks: Union[str, list[str]] = masks
54
+ self.recursive: bool = recursive
55
+ self.abspath: bool = abspath
56
+ self.non_deterministic: bool = non_deterministic
57
+ self.length: int = length
58
+
59
+ def __iter__(self) -> Iterator[str]:
60
+ for path in self.datapipe:
61
+ yield from get_file_pathnames_from_root(
62
+ path, self.masks, self.recursive, self.abspath, self.non_deterministic
63
+ )
64
+
65
+ def __len__(self) -> int:
66
+ if self.length == -1:
67
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
68
+ return self.length
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/fileopener.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Iterable
3
+ from io import IOBase
4
+ from typing import Optional
5
+
6
+ from torch.utils.data.datapipes._decorator import functional_datapipe
7
+ from torch.utils.data.datapipes.datapipe import IterDataPipe
8
+ from torch.utils.data.datapipes.utils.common import get_file_binaries_from_pathnames
9
+
10
+
11
+ __all__ = [
12
+ "FileOpenerIterDataPipe",
13
+ ]
14
+
15
+
16
+ @functional_datapipe("open_files")
17
+ class FileOpenerIterDataPipe(IterDataPipe[tuple[str, IOBase]]):
18
+ r"""
19
+ Given pathnames, opens files and yield pathname and file stream in a tuple (functional name: ``open_files``).
20
+
21
+ Args:
22
+ datapipe: Iterable datapipe that provides pathnames
23
+ mode: An optional string that specifies the mode in which
24
+ the file is opened by ``open()``. It defaults to ``r``, other options are
25
+ ``b`` for reading in binary mode and ``t`` for text mode.
26
+ encoding: An optional string that specifies the encoding of the
27
+ underlying file. It defaults to ``None`` to match the default encoding of ``open``.
28
+ length: Nominal length of the datapipe
29
+
30
+ Note:
31
+ The opened file handles will be closed by Python's GC periodically. Users can choose
32
+ to close them explicitly.
33
+
34
+ Example:
35
+ >>> # xdoctest: +SKIP
36
+ >>> from torchdata.datapipes.iter import FileLister, FileOpener, StreamReader
37
+ >>> dp = FileLister(root=".").filter(lambda fname: fname.endswith('.txt'))
38
+ >>> dp = FileOpener(dp)
39
+ >>> dp = StreamReader(dp)
40
+ >>> list(dp)
41
+ [('./abc.txt', 'abc')]
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ datapipe: Iterable[str],
47
+ mode: str = "r",
48
+ encoding: Optional[str] = None,
49
+ length: int = -1,
50
+ ):
51
+ super().__init__()
52
+ self.datapipe: Iterable = datapipe
53
+ self.mode: str = mode
54
+ self.encoding: Optional[str] = encoding
55
+
56
+ if self.mode not in ("b", "t", "rb", "rt", "r"):
57
+ raise ValueError(f"Invalid mode {mode}")
58
+ # TODO: enforce typing for each instance based on mode, otherwise
59
+ # `argument_validation` with this DataPipe may be potentially broken
60
+
61
+ if "b" in mode and encoding is not None:
62
+ raise ValueError("binary mode doesn't take an encoding argument")
63
+
64
+ self.length: int = length
65
+
66
+ # Remove annotation due to 'IOBase' is a general type and true type
67
+ # is determined at runtime based on mode. Some `DataPipe` requiring
68
+ # a subtype would cause mypy error.
69
+ def __iter__(self):
70
+ yield from get_file_binaries_from_pathnames(
71
+ self.datapipe, self.mode, self.encoding
72
+ )
73
+
74
+ def __len__(self):
75
+ if self.length == -1:
76
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
77
+ return self.length
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/utils/data/datapipes/iter/grouping.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+ from collections import defaultdict
4
+ from collections.abc import Iterator, Sized
5
+ from typing import Any, Callable, Optional, TypeVar
6
+
7
+ import torch.utils.data.datapipes.iter.sharding
8
+ from torch.utils.data.datapipes._decorator import functional_datapipe
9
+ from torch.utils.data.datapipes.datapipe import DataChunk, IterDataPipe
10
+ from torch.utils.data.datapipes.utils.common import _check_unpickable_fn
11
+
12
+
13
+ __all__ = [
14
+ "BatcherIterDataPipe",
15
+ "GrouperIterDataPipe",
16
+ "UnBatcherIterDataPipe",
17
+ ]
18
+
19
+
20
+ _T_co = TypeVar("_T_co", covariant=True)
21
+
22
+
23
+ def __getattr__(name: str):
24
+ if name in ["SHARDING_PRIORITIES", "ShardingFilterIterDataPipe"]:
25
+ warnings.warn(
26
+ f"`{name}` from `torch.utils.data.datapipes.iter.grouping` is going to be removed in PyTorch 2.1"
27
+ f"Please use `{name}` from the `torch.utils.data.datapipes.iter.sharding`",
28
+ category=FutureWarning,
29
+ stacklevel=2,
30
+ )
31
+
32
+ return getattr(torch.utils.data.datapipes.iter.sharding, name)
33
+
34
+ raise AttributeError(f"module {__name__} has no attribute {name}")
35
+
36
+
37
+ @functional_datapipe("batch")
38
+ class BatcherIterDataPipe(IterDataPipe[DataChunk]):
39
+ r"""
40
+ Creates mini-batches of data (functional name: ``batch``).
41
+
42
+ An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the
43
+ last batch if ``drop_last`` is set to ``False``.
44
+
45
+ Args:
46
+ datapipe: Iterable DataPipe being batched
47
+ batch_size: The size of each batch
48
+ drop_last: Option to drop the last batch if it's not full
49
+ wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding,
50
+ defaults to ``DataChunk``
51
+
52
+ Example:
53
+ >>> # xdoctest: +SKIP
54
+ >>> from torchdata.datapipes.iter import IterableWrapper
55
+ >>> dp = IterableWrapper(range(10))
56
+ >>> dp = dp.batch(batch_size=3, drop_last=True)
57
+ >>> list(dp)
58
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
59
+ """
60
+
61
+ datapipe: IterDataPipe
62
+ batch_size: int
63
+ drop_last: bool
64
+
65
+ def __init__(
66
+ self,
67
+ datapipe: IterDataPipe,
68
+ batch_size: int,
69
+ drop_last: bool = False,
70
+ wrapper_class: type[DataChunk] = DataChunk,
71
+ ) -> None:
72
+ assert batch_size > 0, "Batch size is required to be larger than 0!"
73
+ super().__init__()
74
+ self.datapipe = datapipe
75
+ self.batch_size = batch_size
76
+ self.drop_last = drop_last
77
+ self.wrapper_class = wrapper_class
78
+
79
+ def __iter__(self) -> Iterator[DataChunk]:
80
+ batch: list = []
81
+ for x in self.datapipe:
82
+ batch.append(x)
83
+ if len(batch) == self.batch_size:
84
+ yield self.wrapper_class(batch)
85
+ batch = []
86
+ if len(batch) > 0:
87
+ if not self.drop_last:
88
+ yield self.wrapper_class(batch)
89
+
90
+ def __len__(self) -> int:
91
+ if isinstance(self.datapipe, Sized):
92
+ if self.drop_last:
93
+ return len(self.datapipe) // self.batch_size
94
+ else:
95
+ return (len(self.datapipe) + self.batch_size - 1) // self.batch_size
96
+ else:
97
+ raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
98
+
99
+
100
+ @functional_datapipe("unbatch")
101
+ class UnBatcherIterDataPipe(IterDataPipe):
102
+ r"""
103
+ Undos batching of data (functional name: ``unbatch``).
104
+
105
+ In other words, it flattens the data up to the specified level within a batched DataPipe.
106
+
107
+ Args:
108
+ datapipe: Iterable DataPipe being un-batched
109
+ unbatch_level: Defaults to ``1`` (only flattening the top level). If set to ``2``,
110
+ it will flatten the top two levels, and ``-1`` will flatten the entire DataPipe.
111
+
112
+ Example:
113
+ >>> # xdoctest: +SKIP
114
+ >>> from torchdata.datapipes.iter import IterableWrapper
115
+ >>> source_dp = IterableWrapper([[[0, 1], [2]], [[3, 4], [5]], [[6]]])
116
+ >>> dp1 = source_dp.unbatch()
117
+ >>> list(dp1)
118
+ [[0, 1], [2], [3, 4], [5], [6]]
119
+ >>> dp2 = source_dp.unbatch(unbatch_level=2)
120
+ >>> list(dp2)
121
+ [0, 1, 2, 3, 4, 5, 6]
122
+ """
123
+
124
+ def __init__(self, datapipe: IterDataPipe, unbatch_level: int = 1):
125
+ self.datapipe = datapipe
126
+ self.unbatch_level = unbatch_level
127
+
128
+ def __iter__(self):
129
+ for element in self.datapipe:
130
+ yield from self._dive(element, unbatch_level=self.unbatch_level)
131
+
132
+ def _dive(self, element, unbatch_level):
133
+ if unbatch_level < -1:
134
+ raise ValueError("unbatch_level must be -1 or >= 0")
135
+ if unbatch_level == -1:
136
+ if isinstance(element, (list, DataChunk)):
137
+ for item in element:
138
+ yield from self._dive(item, unbatch_level=-1)
139
+ else:
140
+ yield element
141
+ elif unbatch_level == 0:
142
+ yield element
143
+ else:
144
+ if isinstance(element, (list, DataChunk)):
145
+ for item in element:
146
+ yield from self._dive(item, unbatch_level=unbatch_level - 1)
147
+ else:
148
+ raise IndexError(
149
+ f"unbatch_level {self.unbatch_level} exceeds the depth of the DataPipe"
150
+ )
151
+
152
+
153
+ @functional_datapipe("groupby")
154
+ class GrouperIterDataPipe(IterDataPipe[DataChunk]):
155
+ r"""
156
+ Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``.
157
+
158
+ (functional name: ``groupby``).
159
+
160
+ The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group
161
+ will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full,
162
+ the DataPipe will yield the largest batch with the same key, provided that its size is larger
163
+ than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``.
164
+
165
+ After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity
166
+ will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``.
167
+
168
+ Args:
169
+ datapipe: Iterable datapipe to be grouped
170
+ group_key_fn: Function used to generate group key from the data of the source datapipe
171
+ keep_key: Option to yield the matching key along with the items in a tuple,
172
+ resulting in `(key, [items])` otherwise returning [items]
173
+ buffer_size: The size of buffer for ungrouped data
174
+ group_size: The max size of each group, a batch is yielded as soon as it reaches this size
175
+ guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full
176
+ drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer
177
+ when the buffer is full
178
+
179
+ Example:
180
+ >>> import os
181
+ >>> # xdoctest: +SKIP
182
+ >>> from torchdata.datapipes.iter import IterableWrapper
183
+ >>> def group_fn(file):
184
+ ... return os.path.basename(file).split(".")[0]
185
+ >>> source_dp = IterableWrapper(["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"])
186
+ >>> dp0 = source_dp.groupby(group_key_fn=group_fn)
187
+ >>> list(dp0)
188
+ [['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']]
189
+ >>> # A group is yielded as soon as its size equals to `group_size`
190
+ >>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2)
191
+ >>> list(dp1)
192
+ [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
193
+ >>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size`
194
+ >>> dp2 = source_dp.groupby(group_key_fn=group_fn, buffer_size=3, group_size=3, guaranteed_group_size=2)
195
+ >>> list(dp2)
196
+ [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
197
+ """
198
+
199
+ def __init__(
200
+ self,
201
+ datapipe: IterDataPipe[_T_co],
202
+ group_key_fn: Callable[[_T_co], Any],
203
+ *,
204
+ keep_key: bool = False,
205
+ buffer_size: int = 10000,
206
+ group_size: Optional[int] = None,
207
+ guaranteed_group_size: Optional[int] = None,
208
+ drop_remaining: bool = False,
209
+ ):
210
+ _check_unpickable_fn(group_key_fn)
211
+ self.datapipe = datapipe
212
+ self.group_key_fn = group_key_fn
213
+
214
+ self.keep_key = keep_key
215
+ self.max_buffer_size = buffer_size
216
+ self.buffer_elements: defaultdict[Any, list] = defaultdict(list)
217
+ self.curr_buffer_size = 0
218
+ self.group_size = group_size
219
+ self.guaranteed_group_size = None
220
+ if group_size is not None and buffer_size is not None:
221
+ assert 0 < group_size <= buffer_size
222
+ self.guaranteed_group_size = group_size
223
+ if guaranteed_group_size is not None:
224
+ assert group_size is not None and 0 < guaranteed_group_size <= group_size
225
+ self.guaranteed_group_size = guaranteed_group_size
226
+ self.drop_remaining = drop_remaining
227
+ self.wrapper_class = DataChunk
228
+
229
+ def _remove_biggest_key(self):
230
+ biggest_key = None
231
+ biggest_size = 0
232
+ result_to_yield = None
233
+ for findkey in self.buffer_elements.keys():
234
+ if len(self.buffer_elements[findkey]) > biggest_size:
235
+ biggest_size = len(self.buffer_elements[findkey])
236
+ biggest_key = findkey
237
+
238
+ if (
239
+ self.guaranteed_group_size is not None
240
+ and biggest_size < self.guaranteed_group_size
241
+ and not self.drop_remaining
242
+ ):
243
+ raise RuntimeError(
244
+ "Failed to group items", str(self.buffer_elements[biggest_key])
245
+ )
246
+
247
+ if (
248
+ self.guaranteed_group_size is None
249
+ or biggest_size >= self.guaranteed_group_size
250
+ ):
251
+ result_to_yield = self.buffer_elements[biggest_key]
252
+
253
+ self.curr_buffer_size -= biggest_size
254
+ del self.buffer_elements[biggest_key]
255
+
256
+ return result_to_yield
257
+
258
+ def __iter__(self):
259
+ for x in self.datapipe:
260
+ key = self.group_key_fn(x)
261
+
262
+ self.buffer_elements[key].append(x)
263
+ self.curr_buffer_size += 1
264
+
265
+ if self.group_size is not None and self.group_size == len(
266
+ self.buffer_elements[key]
267
+ ):
268
+ result: DataChunk[Any] = self.wrapper_class(self.buffer_elements[key])
269
+ yield (key, result) if self.keep_key else result
270
+ self.curr_buffer_size -= len(self.buffer_elements[key])
271
+ del self.buffer_elements[key]
272
+
273
+ if self.curr_buffer_size == self.max_buffer_size:
274
+ result_to_yield = self._remove_biggest_key()
275
+ if result_to_yield is not None:
276
+ result = self.wrapper_class(result_to_yield)
277
+ yield (key, result) if self.keep_key else result
278
+
279
+ for key in tuple(self.buffer_elements.keys()):
280
+ result = self.wrapper_class(self.buffer_elements.pop(key))
281
+ self.curr_buffer_size -= len(result)
282
+ yield (key, result) if self.keep_key else result
283
+
284
+ def reset(self) -> None:
285
+ self.curr_buffer_size = 0
286
+ self.buffer_elements = defaultdict(list)
287
+
288
+ def __getstate__(self):
289
+ state = (
290
+ self.datapipe,
291
+ self.group_key_fn,
292
+ self.keep_key,
293
+ self.max_buffer_size,
294
+ self.group_size,
295
+ self.guaranteed_group_size,
296
+ self.drop_remaining,
297
+ self.wrapper_class,
298
+ self._valid_iterator_id,
299
+ self._number_of_samples_yielded,
300
+ )
301
+ if IterDataPipe.getstate_hook is not None:
302
+ return IterDataPipe.getstate_hook(state)
303
+ return state
304
+
305
+ def __setstate__(self, state):
306
+ (
307
+ self.datapipe,
308
+ self.group_key_fn,
309
+ self.keep_key,
310
+ self.max_buffer_size,
311
+ self.group_size,
312
+ self.guaranteed_group_size,
313
+ self.drop_remaining,
314
+ self.wrapper_class,
315
+ self._valid_iterator_id,
316
+ self._number_of_samples_yielded,
317
+ ) = state
318
+ self.curr_buffer_size = 0
319
+ self.buffer_elements = defaultdict(list)
320
+
321
+ def __del__(self):
322
+ self.buffer_elements.clear()