JinghuiLuAstronaut commited on
Commit
eb47b33
·
verified ·
1 Parent(s): c24f28e

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__config__.py +162 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__init__.cython-30.pxd +1050 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__init__.py +461 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__init__.pyi +0 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/_distributor_init.py +15 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/_globals.py +95 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/_pytesttester.py +207 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/ctypeslib.py +545 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/exceptions.py +231 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/matlib.py +378 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/__init__.py +324 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/awq.py +119 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/executorch.py +1137 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/hub_kernels.py +514 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/moe.py +582 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/npu_flash_attention.py +143 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/spqr.py +74 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/torchao.py +234 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_owt_llmclean_qwen36_35b_10k_C1to1024sqrt_step013000_gpu_temp1_decode128_quick_n8.log +34 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/noise_geometry_fixed_selfcond_ce_main_pow3.log +261 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__config__.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is generated by numpy's build process
2
+ # It contains system_info results at the time of building this package.
3
+ from enum import Enum
4
+ from numpy.core._multiarray_umath import (
5
+ __cpu_features__,
6
+ __cpu_baseline__,
7
+ __cpu_dispatch__,
8
+ )
9
+
10
+ __all__ = ["show"]
11
+ _built_with_meson = True
12
+
13
+
14
+ class DisplayModes(Enum):
15
+ stdout = "stdout"
16
+ dicts = "dicts"
17
+
18
+
19
+ def _cleanup(d):
20
+ """
21
+ Removes empty values in a `dict` recursively
22
+ This ensures we remove values that Meson could not provide to CONFIG
23
+ """
24
+ if isinstance(d, dict):
25
+ return {k: _cleanup(v) for k, v in d.items() if v and _cleanup(v)}
26
+ else:
27
+ return d
28
+
29
+
30
+ CONFIG = _cleanup(
31
+ {
32
+ "Compilers": {
33
+ "c": {
34
+ "name": "gcc",
35
+ "linker": r"ld.bfd",
36
+ "version": "10.2.1",
37
+ "commands": r"cc",
38
+ "args": r"-fno-strict-aliasing",
39
+ "linker args": r"-Wl,--strip-debug, -fno-strict-aliasing",
40
+ },
41
+ "cython": {
42
+ "name": "cython",
43
+ "linker": r"cython",
44
+ "version": "3.0.8",
45
+ "commands": r"cython",
46
+ "args": r"",
47
+ "linker args": r"",
48
+ },
49
+ "c++": {
50
+ "name": "gcc",
51
+ "linker": r"ld.bfd",
52
+ "version": "10.2.1",
53
+ "commands": r"c++",
54
+ "args": r"",
55
+ "linker args": r"-Wl,--strip-debug",
56
+ },
57
+ },
58
+ "Machine Information": {
59
+ "host": {
60
+ "cpu": "x86_64",
61
+ "family": "x86_64",
62
+ "endian": "little",
63
+ "system": "linux",
64
+ },
65
+ "build": {
66
+ "cpu": "x86_64",
67
+ "family": "x86_64",
68
+ "endian": "little",
69
+ "system": "linux",
70
+ },
71
+ "cross-compiled": bool("False".lower().replace("false", "")),
72
+ },
73
+ "Build Dependencies": {
74
+ "blas": {
75
+ "name": "openblas64",
76
+ "found": bool("True".lower().replace("false", "")),
77
+ "version": "0.3.23.dev",
78
+ "detection method": "pkgconfig",
79
+ "include directory": r"/usr/local/include",
80
+ "lib directory": r"/usr/local/lib",
81
+ "openblas configuration": r"USE_64BITINT=1 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS= NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= HASWELL MAX_THREADS=2",
82
+ "pc file directory": r"/usr/local/lib/pkgconfig",
83
+ },
84
+ "lapack": {
85
+ "name": "dep140551260102944",
86
+ "found": bool("True".lower().replace("false", "")),
87
+ "version": "1.26.4",
88
+ "detection method": "internal",
89
+ "include directory": r"unknown",
90
+ "lib directory": r"unknown",
91
+ "openblas configuration": r"unknown",
92
+ "pc file directory": r"unknown",
93
+ },
94
+ },
95
+ "Python Information": {
96
+ "path": r"/opt/python/cp312-cp312/bin/python",
97
+ "version": "3.12",
98
+ },
99
+ "SIMD Extensions": {
100
+ "baseline": __cpu_baseline__,
101
+ "found": [
102
+ feature for feature in __cpu_dispatch__ if __cpu_features__[feature]
103
+ ],
104
+ "not found": [
105
+ feature for feature in __cpu_dispatch__ if not __cpu_features__[feature]
106
+ ],
107
+ },
108
+ }
109
+ )
110
+
111
+
112
+ def _check_pyyaml():
113
+ import yaml
114
+
115
+ return yaml
116
+
117
+
118
+ def show(mode=DisplayModes.stdout.value):
119
+ """
120
+ Show libraries and system information on which NumPy was built
121
+ and is being used
122
+
123
+ Parameters
124
+ ----------
125
+ mode : {`'stdout'`, `'dicts'`}, optional.
126
+ Indicates how to display the config information.
127
+ `'stdout'` prints to console, `'dicts'` returns a dictionary
128
+ of the configuration.
129
+
130
+ Returns
131
+ -------
132
+ out : {`dict`, `None`}
133
+ If mode is `'dicts'`, a dict is returned, else None
134
+
135
+ See Also
136
+ --------
137
+ get_include : Returns the directory containing NumPy C
138
+ header files.
139
+
140
+ Notes
141
+ -----
142
+ 1. The `'stdout'` mode will give more readable
143
+ output if ``pyyaml`` is installed
144
+
145
+ """
146
+ if mode == DisplayModes.stdout.value:
147
+ try: # Non-standard library, check import
148
+ yaml = _check_pyyaml()
149
+
150
+ print(yaml.dump(CONFIG))
151
+ except ModuleNotFoundError:
152
+ import warnings
153
+ import json
154
+
155
+ warnings.warn("Install `pyyaml` for better output", stacklevel=1)
156
+ print(json.dumps(CONFIG, indent=2))
157
+ elif mode == DisplayModes.dicts.value:
158
+ return CONFIG
159
+ else:
160
+ raise AttributeError(
161
+ f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}"
162
+ )
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__init__.cython-30.pxd ADDED
@@ -0,0 +1,1050 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NumPy static imports for Cython >= 3.0
2
+ #
3
+ # If any of the PyArray_* functions are called, import_array must be
4
+ # called first. This is done automatically by Cython 3.0+ if a call
5
+ # is not detected inside of the module.
6
+ #
7
+ # Author: Dag Sverre Seljebotn
8
+ #
9
+
10
+ from cpython.ref cimport Py_INCREF
11
+ from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck
12
+ cimport libc.stdio as stdio
13
+
14
+
15
+ cdef extern from *:
16
+ # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython.
17
+ # See https://github.com/cython/cython/issues/3573
18
+ """
19
+ /* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */
20
+ """
21
+
22
+
23
+ cdef extern from "Python.h":
24
+ ctypedef int Py_intptr_t
25
+
26
+ cdef extern from "numpy/arrayobject.h":
27
+ ctypedef Py_intptr_t npy_intp
28
+ ctypedef size_t npy_uintp
29
+
30
+ cdef enum NPY_TYPES:
31
+ NPY_BOOL
32
+ NPY_BYTE
33
+ NPY_UBYTE
34
+ NPY_SHORT
35
+ NPY_USHORT
36
+ NPY_INT
37
+ NPY_UINT
38
+ NPY_LONG
39
+ NPY_ULONG
40
+ NPY_LONGLONG
41
+ NPY_ULONGLONG
42
+ NPY_FLOAT
43
+ NPY_DOUBLE
44
+ NPY_LONGDOUBLE
45
+ NPY_CFLOAT
46
+ NPY_CDOUBLE
47
+ NPY_CLONGDOUBLE
48
+ NPY_OBJECT
49
+ NPY_STRING
50
+ NPY_UNICODE
51
+ NPY_VOID
52
+ NPY_DATETIME
53
+ NPY_TIMEDELTA
54
+ NPY_NTYPES
55
+ NPY_NOTYPE
56
+
57
+ NPY_INT8
58
+ NPY_INT16
59
+ NPY_INT32
60
+ NPY_INT64
61
+ NPY_INT128
62
+ NPY_INT256
63
+ NPY_UINT8
64
+ NPY_UINT16
65
+ NPY_UINT32
66
+ NPY_UINT64
67
+ NPY_UINT128
68
+ NPY_UINT256
69
+ NPY_FLOAT16
70
+ NPY_FLOAT32
71
+ NPY_FLOAT64
72
+ NPY_FLOAT80
73
+ NPY_FLOAT96
74
+ NPY_FLOAT128
75
+ NPY_FLOAT256
76
+ NPY_COMPLEX32
77
+ NPY_COMPLEX64
78
+ NPY_COMPLEX128
79
+ NPY_COMPLEX160
80
+ NPY_COMPLEX192
81
+ NPY_COMPLEX256
82
+ NPY_COMPLEX512
83
+
84
+ NPY_INTP
85
+
86
+ ctypedef enum NPY_ORDER:
87
+ NPY_ANYORDER
88
+ NPY_CORDER
89
+ NPY_FORTRANORDER
90
+ NPY_KEEPORDER
91
+
92
+ ctypedef enum NPY_CASTING:
93
+ NPY_NO_CASTING
94
+ NPY_EQUIV_CASTING
95
+ NPY_SAFE_CASTING
96
+ NPY_SAME_KIND_CASTING
97
+ NPY_UNSAFE_CASTING
98
+
99
+ ctypedef enum NPY_CLIPMODE:
100
+ NPY_CLIP
101
+ NPY_WRAP
102
+ NPY_RAISE
103
+
104
+ ctypedef enum NPY_SCALARKIND:
105
+ NPY_NOSCALAR,
106
+ NPY_BOOL_SCALAR,
107
+ NPY_INTPOS_SCALAR,
108
+ NPY_INTNEG_SCALAR,
109
+ NPY_FLOAT_SCALAR,
110
+ NPY_COMPLEX_SCALAR,
111
+ NPY_OBJECT_SCALAR
112
+
113
+ ctypedef enum NPY_SORTKIND:
114
+ NPY_QUICKSORT
115
+ NPY_HEAPSORT
116
+ NPY_MERGESORT
117
+
118
+ ctypedef enum NPY_SEARCHSIDE:
119
+ NPY_SEARCHLEFT
120
+ NPY_SEARCHRIGHT
121
+
122
+ enum:
123
+ # DEPRECATED since NumPy 1.7 ! Do not use in new code!
124
+ NPY_C_CONTIGUOUS
125
+ NPY_F_CONTIGUOUS
126
+ NPY_CONTIGUOUS
127
+ NPY_FORTRAN
128
+ NPY_OWNDATA
129
+ NPY_FORCECAST
130
+ NPY_ENSURECOPY
131
+ NPY_ENSUREARRAY
132
+ NPY_ELEMENTSTRIDES
133
+ NPY_ALIGNED
134
+ NPY_NOTSWAPPED
135
+ NPY_WRITEABLE
136
+ NPY_ARR_HAS_DESCR
137
+
138
+ NPY_BEHAVED
139
+ NPY_BEHAVED_NS
140
+ NPY_CARRAY
141
+ NPY_CARRAY_RO
142
+ NPY_FARRAY
143
+ NPY_FARRAY_RO
144
+ NPY_DEFAULT
145
+
146
+ NPY_IN_ARRAY
147
+ NPY_OUT_ARRAY
148
+ NPY_INOUT_ARRAY
149
+ NPY_IN_FARRAY
150
+ NPY_OUT_FARRAY
151
+ NPY_INOUT_FARRAY
152
+
153
+ NPY_UPDATE_ALL
154
+
155
+ enum:
156
+ # Added in NumPy 1.7 to replace the deprecated enums above.
157
+ NPY_ARRAY_C_CONTIGUOUS
158
+ NPY_ARRAY_F_CONTIGUOUS
159
+ NPY_ARRAY_OWNDATA
160
+ NPY_ARRAY_FORCECAST
161
+ NPY_ARRAY_ENSURECOPY
162
+ NPY_ARRAY_ENSUREARRAY
163
+ NPY_ARRAY_ELEMENTSTRIDES
164
+ NPY_ARRAY_ALIGNED
165
+ NPY_ARRAY_NOTSWAPPED
166
+ NPY_ARRAY_WRITEABLE
167
+ NPY_ARRAY_WRITEBACKIFCOPY
168
+
169
+ NPY_ARRAY_BEHAVED
170
+ NPY_ARRAY_BEHAVED_NS
171
+ NPY_ARRAY_CARRAY
172
+ NPY_ARRAY_CARRAY_RO
173
+ NPY_ARRAY_FARRAY
174
+ NPY_ARRAY_FARRAY_RO
175
+ NPY_ARRAY_DEFAULT
176
+
177
+ NPY_ARRAY_IN_ARRAY
178
+ NPY_ARRAY_OUT_ARRAY
179
+ NPY_ARRAY_INOUT_ARRAY
180
+ NPY_ARRAY_IN_FARRAY
181
+ NPY_ARRAY_OUT_FARRAY
182
+ NPY_ARRAY_INOUT_FARRAY
183
+
184
+ NPY_ARRAY_UPDATE_ALL
185
+
186
+ cdef enum:
187
+ NPY_MAXDIMS
188
+
189
+ npy_intp NPY_MAX_ELSIZE
190
+
191
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
192
+
193
+ ctypedef struct PyArray_ArrayDescr:
194
+ # shape is a tuple, but Cython doesn't support "tuple shape"
195
+ # inside a non-PyObject declaration, so we have to declare it
196
+ # as just a PyObject*.
197
+ PyObject* shape
198
+
199
+ ctypedef struct PyArray_Descr:
200
+ pass
201
+
202
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
203
+ # Use PyDataType_* macros when possible, however there are no macros
204
+ # for accessing some of the fields, so some are defined.
205
+ cdef PyTypeObject* typeobj
206
+ cdef char kind
207
+ cdef char type
208
+ # Numpy sometimes mutates this without warning (e.g. it'll
209
+ # sometimes change "|" to "<" in shared dtype objects on
210
+ # little-endian machines). If this matters to you, use
211
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
212
+ # directly accessing this field.
213
+ cdef char byteorder
214
+ cdef char flags
215
+ cdef int type_num
216
+ cdef int itemsize "elsize"
217
+ cdef int alignment
218
+ cdef object fields
219
+ cdef tuple names
220
+ # Use PyDataType_HASSUBARRAY to test whether this field is
221
+ # valid (the pointer can be NULL). Most users should access
222
+ # this field via the inline helper method PyDataType_SHAPE.
223
+ cdef PyArray_ArrayDescr* subarray
224
+
225
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
226
+ # Use through macros
227
+ pass
228
+
229
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
230
+ # Use through macros
231
+ pass
232
+
233
+ ctypedef struct PyArrayObject:
234
+ # For use in situations where ndarray can't replace PyArrayObject*,
235
+ # like PyArrayObject**.
236
+ pass
237
+
238
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
239
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
240
+
241
+ # NOTE: no field declarations since direct access is deprecated since NumPy 1.7
242
+ # Instead, we use properties that map to the corresponding C-API functions.
243
+
244
+ @property
245
+ cdef inline PyObject* base(self) nogil:
246
+ """Returns a borrowed reference to the object owning the data/memory.
247
+ """
248
+ return PyArray_BASE(self)
249
+
250
+ @property
251
+ cdef inline dtype descr(self):
252
+ """Returns an owned reference to the dtype of the array.
253
+ """
254
+ return <dtype>PyArray_DESCR(self)
255
+
256
+ @property
257
+ cdef inline int ndim(self) nogil:
258
+ """Returns the number of dimensions in the array.
259
+ """
260
+ return PyArray_NDIM(self)
261
+
262
+ @property
263
+ cdef inline npy_intp *shape(self) nogil:
264
+ """Returns a pointer to the dimensions/shape of the array.
265
+ The number of elements matches the number of dimensions of the array (ndim).
266
+ Can return NULL for 0-dimensional arrays.
267
+ """
268
+ return PyArray_DIMS(self)
269
+
270
+ @property
271
+ cdef inline npy_intp *strides(self) nogil:
272
+ """Returns a pointer to the strides of the array.
273
+ The number of elements matches the number of dimensions of the array (ndim).
274
+ """
275
+ return PyArray_STRIDES(self)
276
+
277
+ @property
278
+ cdef inline npy_intp size(self) nogil:
279
+ """Returns the total size (in number of elements) of the array.
280
+ """
281
+ return PyArray_SIZE(self)
282
+
283
+ @property
284
+ cdef inline char* data(self) nogil:
285
+ """The pointer to the data buffer as a char*.
286
+ This is provided for legacy reasons to avoid direct struct field access.
287
+ For new code that needs this access, you probably want to cast the result
288
+ of `PyArray_DATA()` instead, which returns a 'void*'.
289
+ """
290
+ return PyArray_BYTES(self)
291
+
292
+ ctypedef unsigned char npy_bool
293
+
294
+ ctypedef signed char npy_byte
295
+ ctypedef signed short npy_short
296
+ ctypedef signed int npy_int
297
+ ctypedef signed long npy_long
298
+ ctypedef signed long long npy_longlong
299
+
300
+ ctypedef unsigned char npy_ubyte
301
+ ctypedef unsigned short npy_ushort
302
+ ctypedef unsigned int npy_uint
303
+ ctypedef unsigned long npy_ulong
304
+ ctypedef unsigned long long npy_ulonglong
305
+
306
+ ctypedef float npy_float
307
+ ctypedef double npy_double
308
+ ctypedef long double npy_longdouble
309
+
310
+ ctypedef signed char npy_int8
311
+ ctypedef signed short npy_int16
312
+ ctypedef signed int npy_int32
313
+ ctypedef signed long long npy_int64
314
+ ctypedef signed long long npy_int96
315
+ ctypedef signed long long npy_int128
316
+
317
+ ctypedef unsigned char npy_uint8
318
+ ctypedef unsigned short npy_uint16
319
+ ctypedef unsigned int npy_uint32
320
+ ctypedef unsigned long long npy_uint64
321
+ ctypedef unsigned long long npy_uint96
322
+ ctypedef unsigned long long npy_uint128
323
+
324
+ ctypedef float npy_float32
325
+ ctypedef double npy_float64
326
+ ctypedef long double npy_float80
327
+ ctypedef long double npy_float96
328
+ ctypedef long double npy_float128
329
+
330
+ ctypedef struct npy_cfloat:
331
+ float real
332
+ float imag
333
+
334
+ ctypedef struct npy_cdouble:
335
+ double real
336
+ double imag
337
+
338
+ ctypedef struct npy_clongdouble:
339
+ long double real
340
+ long double imag
341
+
342
+ ctypedef struct npy_complex64:
343
+ float real
344
+ float imag
345
+
346
+ ctypedef struct npy_complex128:
347
+ double real
348
+ double imag
349
+
350
+ ctypedef struct npy_complex160:
351
+ long double real
352
+ long double imag
353
+
354
+ ctypedef struct npy_complex192:
355
+ long double real
356
+ long double imag
357
+
358
+ ctypedef struct npy_complex256:
359
+ long double real
360
+ long double imag
361
+
362
+ ctypedef struct PyArray_Dims:
363
+ npy_intp *ptr
364
+ int len
365
+
366
+ int _import_array() except -1
367
+ # A second definition so _import_array isn't marked as used when we use it here.
368
+ # Do not use - subject to change any time.
369
+ int __pyx_import_array "_import_array"() except -1
370
+
371
+ #
372
+ # Macros from ndarrayobject.h
373
+ #
374
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
375
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
376
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
377
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
378
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
379
+ bint PyArray_ISALIGNED(ndarray m) nogil
380
+
381
+ int PyArray_NDIM(ndarray) nogil
382
+ bint PyArray_ISONESEGMENT(ndarray) nogil
383
+ bint PyArray_ISFORTRAN(ndarray) nogil
384
+ int PyArray_FORTRANIF(ndarray) nogil
385
+
386
+ void* PyArray_DATA(ndarray) nogil
387
+ char* PyArray_BYTES(ndarray) nogil
388
+
389
+ npy_intp* PyArray_DIMS(ndarray) nogil
390
+ npy_intp* PyArray_STRIDES(ndarray) nogil
391
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
392
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
393
+
394
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
395
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
396
+ PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr.
397
+ int PyArray_FLAGS(ndarray) nogil
398
+ void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
399
+ void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
400
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
401
+ int PyArray_TYPE(ndarray arr) nogil
402
+
403
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
404
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
405
+
406
+ bint PyTypeNum_ISBOOL(int) nogil
407
+ bint PyTypeNum_ISUNSIGNED(int) nogil
408
+ bint PyTypeNum_ISSIGNED(int) nogil
409
+ bint PyTypeNum_ISINTEGER(int) nogil
410
+ bint PyTypeNum_ISFLOAT(int) nogil
411
+ bint PyTypeNum_ISNUMBER(int) nogil
412
+ bint PyTypeNum_ISSTRING(int) nogil
413
+ bint PyTypeNum_ISCOMPLEX(int) nogil
414
+ bint PyTypeNum_ISPYTHON(int) nogil
415
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
416
+ bint PyTypeNum_ISUSERDEF(int) nogil
417
+ bint PyTypeNum_ISEXTENDED(int) nogil
418
+ bint PyTypeNum_ISOBJECT(int) nogil
419
+
420
+ bint PyDataType_ISBOOL(dtype) nogil
421
+ bint PyDataType_ISUNSIGNED(dtype) nogil
422
+ bint PyDataType_ISSIGNED(dtype) nogil
423
+ bint PyDataType_ISINTEGER(dtype) nogil
424
+ bint PyDataType_ISFLOAT(dtype) nogil
425
+ bint PyDataType_ISNUMBER(dtype) nogil
426
+ bint PyDataType_ISSTRING(dtype) nogil
427
+ bint PyDataType_ISCOMPLEX(dtype) nogil
428
+ bint PyDataType_ISPYTHON(dtype) nogil
429
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
430
+ bint PyDataType_ISUSERDEF(dtype) nogil
431
+ bint PyDataType_ISEXTENDED(dtype) nogil
432
+ bint PyDataType_ISOBJECT(dtype) nogil
433
+ bint PyDataType_HASFIELDS(dtype) nogil
434
+ bint PyDataType_HASSUBARRAY(dtype) nogil
435
+
436
+ bint PyArray_ISBOOL(ndarray) nogil
437
+ bint PyArray_ISUNSIGNED(ndarray) nogil
438
+ bint PyArray_ISSIGNED(ndarray) nogil
439
+ bint PyArray_ISINTEGER(ndarray) nogil
440
+ bint PyArray_ISFLOAT(ndarray) nogil
441
+ bint PyArray_ISNUMBER(ndarray) nogil
442
+ bint PyArray_ISSTRING(ndarray) nogil
443
+ bint PyArray_ISCOMPLEX(ndarray) nogil
444
+ bint PyArray_ISPYTHON(ndarray) nogil
445
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
446
+ bint PyArray_ISUSERDEF(ndarray) nogil
447
+ bint PyArray_ISEXTENDED(ndarray) nogil
448
+ bint PyArray_ISOBJECT(ndarray) nogil
449
+ bint PyArray_HASFIELDS(ndarray) nogil
450
+
451
+ bint PyArray_ISVARIABLE(ndarray) nogil
452
+
453
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
454
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
455
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
456
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
457
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
458
+
459
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
460
+
461
+ bint PyArray_ISCARRAY(ndarray) nogil
462
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
463
+ bint PyArray_ISFARRAY(ndarray) nogil
464
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
465
+ bint PyArray_ISBEHAVED(ndarray) nogil
466
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
467
+
468
+
469
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
470
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
471
+
472
+ bint PyArray_DescrCheck(object)
473
+
474
+ bint PyArray_Check(object)
475
+ bint PyArray_CheckExact(object)
476
+
477
+ # Cannot be supported due to out arg:
478
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
479
+ # bint PyArray_HasArrayInterface(op, out)
480
+
481
+
482
+ bint PyArray_IsZeroDim(object)
483
+ # Cannot be supported due to ## ## in macro:
484
+ # bint PyArray_IsScalar(object, verbatim work)
485
+ bint PyArray_CheckScalar(object)
486
+ bint PyArray_IsPythonNumber(object)
487
+ bint PyArray_IsPythonScalar(object)
488
+ bint PyArray_IsAnyScalar(object)
489
+ bint PyArray_CheckAnyScalar(object)
490
+
491
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
492
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
493
+ npy_intp PyArray_SIZE(ndarray) nogil
494
+ npy_intp PyArray_NBYTES(ndarray) nogil
495
+
496
+ object PyArray_FROM_O(object)
497
+ object PyArray_FROM_OF(object m, int flags)
498
+ object PyArray_FROM_OT(object m, int type)
499
+ object PyArray_FROM_OTF(object m, int type, int flags)
500
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
501
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
502
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
503
+ void PyArray_FILLWBYTE(object, int val)
504
+ npy_intp PyArray_REFCOUNT(object)
505
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
506
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
507
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
508
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
509
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
510
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
511
+ object PyArray_ToScalar(void* data, ndarray arr)
512
+
513
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
514
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
515
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
516
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
517
+
518
+ # Cannot be supported due to out arg
519
+ # void PyArray_DESCR_REPLACE(descr)
520
+
521
+
522
+ object PyArray_Copy(ndarray)
523
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
524
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
525
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
526
+
527
+ object PyArray_Cast(ndarray mp, int type_num)
528
+ object PyArray_Take(ndarray ap, object items, int axis)
529
+ object PyArray_Put(ndarray ap, object items, object values)
530
+
531
+ void PyArray_ITER_RESET(flatiter it) nogil
532
+ void PyArray_ITER_NEXT(flatiter it) nogil
533
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
534
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
535
+ void* PyArray_ITER_DATA(flatiter it) nogil
536
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
537
+
538
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
539
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
540
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
541
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
542
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
543
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
544
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
545
+
546
+ # Functions from __multiarray_api.h
547
+
548
+ # Functions taking dtype and returning object/ndarray are disabled
549
+ # for now as they steal dtype references. I'm conservative and disable
550
+ # more than is probably needed until it can be checked further.
551
+ int PyArray_SetNumericOps (object) except -1
552
+ object PyArray_GetNumericOps ()
553
+ int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF...
554
+ int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF...
555
+ void PyArray_SetStringFunction (object, int)
556
+ dtype PyArray_DescrFromType (int)
557
+ object PyArray_TypeObjectFromType (int)
558
+ char * PyArray_Zero (ndarray)
559
+ char * PyArray_One (ndarray)
560
+ #object PyArray_CastToType (ndarray, dtype, int)
561
+ int PyArray_CastTo (ndarray, ndarray) except -1
562
+ int PyArray_CastAnyTo (ndarray, ndarray) except -1
563
+ int PyArray_CanCastSafely (int, int) # writes errors
564
+ npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors
565
+ int PyArray_ObjectType (object, int) except 0
566
+ dtype PyArray_DescrFromObject (object, dtype)
567
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
568
+ dtype PyArray_DescrFromScalar (object)
569
+ dtype PyArray_DescrFromTypeObject (object)
570
+ npy_intp PyArray_Size (object)
571
+ #object PyArray_Scalar (void *, dtype, object)
572
+ #object PyArray_FromScalar (object, dtype)
573
+ void PyArray_ScalarAsCtype (object, void *)
574
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
575
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
576
+ object PyArray_ScalarFromObject (object)
577
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
578
+ object PyArray_FromDims (int, int *, int)
579
+ #object PyArray_FromDimsAndDataAndDescr (int, int *, dtype, char *)
580
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
581
+ object PyArray_EnsureArray (object)
582
+ object PyArray_EnsureAnyArray (object)
583
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
584
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
585
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
586
+ #object PyArray_FromIter (object, dtype, npy_intp)
587
+ object PyArray_Return (ndarray)
588
+ #object PyArray_GetField (ndarray, dtype, int)
589
+ #int PyArray_SetField (ndarray, dtype, int, object) except -1
590
+ object PyArray_Byteswap (ndarray, npy_bool)
591
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
592
+ int PyArray_MoveInto (ndarray, ndarray) except -1
593
+ int PyArray_CopyInto (ndarray, ndarray) except -1
594
+ int PyArray_CopyAnyInto (ndarray, ndarray) except -1
595
+ int PyArray_CopyObject (ndarray, object) except -1
596
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
597
+ object PyArray_ToList (ndarray)
598
+ object PyArray_ToString (ndarray, NPY_ORDER)
599
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1
600
+ int PyArray_Dump (object, object, int) except -1
601
+ object PyArray_Dumps (object, int)
602
+ int PyArray_ValidType (int) # Cannot error
603
+ void PyArray_UpdateFlags (ndarray, int)
604
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
605
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
606
+ #dtype PyArray_DescrNew (dtype)
607
+ dtype PyArray_DescrNewFromType (int)
608
+ double PyArray_GetPriority (object, double) # clears errors as of 1.25
609
+ object PyArray_IterNew (object)
610
+ object PyArray_MultiIterNew (int, ...)
611
+
612
+ int PyArray_PyIntAsInt (object) except? -1
613
+ npy_intp PyArray_PyIntAsIntp (object)
614
+ int PyArray_Broadcast (broadcast) except -1
615
+ void PyArray_FillObjectArray (ndarray, object) except *
616
+ int PyArray_FillWithScalar (ndarray, object) except -1
617
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
618
+ dtype PyArray_DescrNewByteorder (dtype, char)
619
+ object PyArray_IterAllButAxis (object, int *)
620
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
621
+ #object PyArray_FromArray (ndarray, dtype, int)
622
+ object PyArray_FromInterface (object)
623
+ object PyArray_FromStructInterface (object)
624
+ #object PyArray_FromArrayAttr (object, dtype, object)
625
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
626
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
627
+ object PyArray_NewFlagsObject (object)
628
+ npy_bool PyArray_CanCastScalar (type, type)
629
+ #int PyArray_CompareUCS4 (npy_ucs4 *, npy_ucs4 *, register size_t)
630
+ int PyArray_RemoveSmallest (broadcast) except -1
631
+ int PyArray_ElementStrides (object)
632
+ void PyArray_Item_INCREF (char *, dtype) except *
633
+ void PyArray_Item_XDECREF (char *, dtype) except *
634
+ object PyArray_FieldNames (object)
635
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
636
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
637
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
638
+ object PyArray_PutMask (ndarray, object, object)
639
+ object PyArray_Repeat (ndarray, object, int)
640
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
641
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
642
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
643
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
644
+ object PyArray_ArgMax (ndarray, int, ndarray)
645
+ object PyArray_ArgMin (ndarray, int, ndarray)
646
+ object PyArray_Reshape (ndarray, object)
647
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
648
+ object PyArray_Squeeze (ndarray)
649
+ #object PyArray_View (ndarray, dtype, type)
650
+ object PyArray_SwapAxes (ndarray, int, int)
651
+ object PyArray_Max (ndarray, int, ndarray)
652
+ object PyArray_Min (ndarray, int, ndarray)
653
+ object PyArray_Ptp (ndarray, int, ndarray)
654
+ object PyArray_Mean (ndarray, int, int, ndarray)
655
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
656
+ object PyArray_Diagonal (ndarray, int, int, int)
657
+ object PyArray_Clip (ndarray, object, object, ndarray)
658
+ object PyArray_Conjugate (ndarray, ndarray)
659
+ object PyArray_Nonzero (ndarray)
660
+ object PyArray_Std (ndarray, int, int, ndarray, int)
661
+ object PyArray_Sum (ndarray, int, int, ndarray)
662
+ object PyArray_CumSum (ndarray, int, int, ndarray)
663
+ object PyArray_Prod (ndarray, int, int, ndarray)
664
+ object PyArray_CumProd (ndarray, int, int, ndarray)
665
+ object PyArray_All (ndarray, int, ndarray)
666
+ object PyArray_Any (ndarray, int, ndarray)
667
+ object PyArray_Compress (ndarray, object, int, ndarray)
668
+ object PyArray_Flatten (ndarray, NPY_ORDER)
669
+ object PyArray_Ravel (ndarray, NPY_ORDER)
670
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
671
+ int PyArray_MultiplyIntList (int *, int)
672
+ void * PyArray_GetPtr (ndarray, npy_intp*)
673
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
674
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
675
+ #int PyArray_As1D (object*, char **, int *, int)
676
+ #int PyArray_As2D (object*, char ***, int *, int *, int)
677
+ int PyArray_Free (object, void *)
678
+ #int PyArray_Converter (object, object*)
679
+ int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
680
+ object PyArray_Concatenate (object, int)
681
+ object PyArray_InnerProduct (object, object)
682
+ object PyArray_MatrixProduct (object, object)
683
+ object PyArray_CopyAndTranspose (object)
684
+ object PyArray_Correlate (object, object, int)
685
+ int PyArray_TypestrConvert (int, int)
686
+ #int PyArray_DescrConverter (object, dtype*) except 0
687
+ #int PyArray_DescrConverter2 (object, dtype*) except 0
688
+ int PyArray_IntpConverter (object, PyArray_Dims *) except 0
689
+ #int PyArray_BufferConverter (object, chunk) except 0
690
+ int PyArray_AxisConverter (object, int *) except 0
691
+ int PyArray_BoolConverter (object, npy_bool *) except 0
692
+ int PyArray_ByteorderConverter (object, char *) except 0
693
+ int PyArray_OrderConverter (object, NPY_ORDER *) except 0
694
+ unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors
695
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
696
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
697
+ object PyArray_Where (object, object, object)
698
+ object PyArray_Arange (double, double, double, int)
699
+ #object PyArray_ArangeObj (object, object, object, dtype)
700
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
701
+ object PyArray_LexSort (object, int)
702
+ object PyArray_Round (ndarray, int, ndarray)
703
+ unsigned char PyArray_EquivTypenums (int, int)
704
+ int PyArray_RegisterDataType (dtype) except -1
705
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
706
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
707
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
708
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
709
+ int PyArray_TypeNumFromName (char *)
710
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0
711
+ #int PyArray_OutputConverter (object, ndarray*) except 0
712
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
713
+ void _PyArray_SigintHandler (int)
714
+ void* _PyArray_GetSigintBuf ()
715
+ #int PyArray_DescrAlignConverter (object, dtype*) except 0
716
+ #int PyArray_DescrAlignConverter2 (object, dtype*) except 0
717
+ int PyArray_SearchsideConverter (object, void *) except 0
718
+ object PyArray_CheckAxis (ndarray, int *, int)
719
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
720
+ int PyArray_CompareString (char *, char *, size_t)
721
+ int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead.
722
+
723
+
724
+ # Typedefs that matches the runtime dtype objects in
725
+ # the numpy module.
726
+
727
+ # The ones that are commented out needs an IFDEF function
728
+ # in Cython to enable them only on the right systems.
729
+
730
+ ctypedef npy_int8 int8_t
731
+ ctypedef npy_int16 int16_t
732
+ ctypedef npy_int32 int32_t
733
+ ctypedef npy_int64 int64_t
734
+ #ctypedef npy_int96 int96_t
735
+ #ctypedef npy_int128 int128_t
736
+
737
+ ctypedef npy_uint8 uint8_t
738
+ ctypedef npy_uint16 uint16_t
739
+ ctypedef npy_uint32 uint32_t
740
+ ctypedef npy_uint64 uint64_t
741
+ #ctypedef npy_uint96 uint96_t
742
+ #ctypedef npy_uint128 uint128_t
743
+
744
+ ctypedef npy_float32 float32_t
745
+ ctypedef npy_float64 float64_t
746
+ #ctypedef npy_float80 float80_t
747
+ #ctypedef npy_float128 float128_t
748
+
749
+ ctypedef float complex complex64_t
750
+ ctypedef double complex complex128_t
751
+
752
+ # The int types are mapped a bit surprising --
753
+ # numpy.int corresponds to 'l' and numpy.long to 'q'
754
+ ctypedef npy_long int_t
755
+ ctypedef npy_longlong longlong_t
756
+
757
+ ctypedef npy_ulong uint_t
758
+ ctypedef npy_ulonglong ulonglong_t
759
+
760
+ ctypedef npy_intp intp_t
761
+ ctypedef npy_uintp uintp_t
762
+
763
+ ctypedef npy_double float_t
764
+ ctypedef npy_double double_t
765
+ ctypedef npy_longdouble longdouble_t
766
+
767
+ ctypedef npy_cfloat cfloat_t
768
+ ctypedef npy_cdouble cdouble_t
769
+ ctypedef npy_clongdouble clongdouble_t
770
+
771
+ ctypedef npy_cdouble complex_t
772
+
773
+ cdef inline object PyArray_MultiIterNew1(a):
774
+ return PyArray_MultiIterNew(1, <void*>a)
775
+
776
+ cdef inline object PyArray_MultiIterNew2(a, b):
777
+ return PyArray_MultiIterNew(2, <void*>a, <void*>b)
778
+
779
+ cdef inline object PyArray_MultiIterNew3(a, b, c):
780
+ return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
781
+
782
+ cdef inline object PyArray_MultiIterNew4(a, b, c, d):
783
+ return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
784
+
785
+ cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
786
+ return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
787
+
788
+ cdef inline tuple PyDataType_SHAPE(dtype d):
789
+ if PyDataType_HASSUBARRAY(d):
790
+ return <tuple>d.subarray.shape
791
+ else:
792
+ return ()
793
+
794
+
795
+ cdef extern from "numpy/ndarrayobject.h":
796
+ PyTypeObject PyTimedeltaArrType_Type
797
+ PyTypeObject PyDatetimeArrType_Type
798
+ ctypedef int64_t npy_timedelta
799
+ ctypedef int64_t npy_datetime
800
+
801
+ cdef extern from "numpy/ndarraytypes.h":
802
+ ctypedef struct PyArray_DatetimeMetaData:
803
+ NPY_DATETIMEUNIT base
804
+ int64_t num
805
+
806
+ cdef extern from "numpy/arrayscalars.h":
807
+
808
+ # abstract types
809
+ ctypedef class numpy.generic [object PyObject]:
810
+ pass
811
+ ctypedef class numpy.number [object PyObject]:
812
+ pass
813
+ ctypedef class numpy.integer [object PyObject]:
814
+ pass
815
+ ctypedef class numpy.signedinteger [object PyObject]:
816
+ pass
817
+ ctypedef class numpy.unsignedinteger [object PyObject]:
818
+ pass
819
+ ctypedef class numpy.inexact [object PyObject]:
820
+ pass
821
+ ctypedef class numpy.floating [object PyObject]:
822
+ pass
823
+ ctypedef class numpy.complexfloating [object PyObject]:
824
+ pass
825
+ ctypedef class numpy.flexible [object PyObject]:
826
+ pass
827
+ ctypedef class numpy.character [object PyObject]:
828
+ pass
829
+
830
+ ctypedef struct PyDatetimeScalarObject:
831
+ # PyObject_HEAD
832
+ npy_datetime obval
833
+ PyArray_DatetimeMetaData obmeta
834
+
835
+ ctypedef struct PyTimedeltaScalarObject:
836
+ # PyObject_HEAD
837
+ npy_timedelta obval
838
+ PyArray_DatetimeMetaData obmeta
839
+
840
+ ctypedef enum NPY_DATETIMEUNIT:
841
+ NPY_FR_Y
842
+ NPY_FR_M
843
+ NPY_FR_W
844
+ NPY_FR_D
845
+ NPY_FR_B
846
+ NPY_FR_h
847
+ NPY_FR_m
848
+ NPY_FR_s
849
+ NPY_FR_ms
850
+ NPY_FR_us
851
+ NPY_FR_ns
852
+ NPY_FR_ps
853
+ NPY_FR_fs
854
+ NPY_FR_as
855
+ NPY_FR_GENERIC
856
+
857
+
858
+ #
859
+ # ufunc API
860
+ #
861
+
862
+ cdef extern from "numpy/ufuncobject.h":
863
+
864
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
865
+
866
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
867
+ cdef:
868
+ int nin, nout, nargs
869
+ int identity
870
+ PyUFuncGenericFunction *functions
871
+ void **data
872
+ int ntypes
873
+ int check_return
874
+ char *name
875
+ char *types
876
+ char *doc
877
+ void *ptr
878
+ PyObject *obj
879
+ PyObject *userloops
880
+
881
+ cdef enum:
882
+ PyUFunc_Zero
883
+ PyUFunc_One
884
+ PyUFunc_None
885
+ UFUNC_ERR_IGNORE
886
+ UFUNC_ERR_WARN
887
+ UFUNC_ERR_RAISE
888
+ UFUNC_ERR_CALL
889
+ UFUNC_ERR_PRINT
890
+ UFUNC_ERR_LOG
891
+ UFUNC_MASK_DIVIDEBYZERO
892
+ UFUNC_MASK_OVERFLOW
893
+ UFUNC_MASK_UNDERFLOW
894
+ UFUNC_MASK_INVALID
895
+ UFUNC_SHIFT_DIVIDEBYZERO
896
+ UFUNC_SHIFT_OVERFLOW
897
+ UFUNC_SHIFT_UNDERFLOW
898
+ UFUNC_SHIFT_INVALID
899
+ UFUNC_FPE_DIVIDEBYZERO
900
+ UFUNC_FPE_OVERFLOW
901
+ UFUNC_FPE_UNDERFLOW
902
+ UFUNC_FPE_INVALID
903
+ UFUNC_ERR_DEFAULT
904
+ UFUNC_ERR_DEFAULT2
905
+
906
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
907
+ void **, char *, int, int, int, int, char *, char *, int)
908
+ int PyUFunc_RegisterLoopForType(ufunc, int,
909
+ PyUFuncGenericFunction, int *, void *) except -1
910
+ void PyUFunc_f_f_As_d_d \
911
+ (char **, npy_intp *, npy_intp *, void *)
912
+ void PyUFunc_d_d \
913
+ (char **, npy_intp *, npy_intp *, void *)
914
+ void PyUFunc_f_f \
915
+ (char **, npy_intp *, npy_intp *, void *)
916
+ void PyUFunc_g_g \
917
+ (char **, npy_intp *, npy_intp *, void *)
918
+ void PyUFunc_F_F_As_D_D \
919
+ (char **, npy_intp *, npy_intp *, void *)
920
+ void PyUFunc_F_F \
921
+ (char **, npy_intp *, npy_intp *, void *)
922
+ void PyUFunc_D_D \
923
+ (char **, npy_intp *, npy_intp *, void *)
924
+ void PyUFunc_G_G \
925
+ (char **, npy_intp *, npy_intp *, void *)
926
+ void PyUFunc_O_O \
927
+ (char **, npy_intp *, npy_intp *, void *)
928
+ void PyUFunc_ff_f_As_dd_d \
929
+ (char **, npy_intp *, npy_intp *, void *)
930
+ void PyUFunc_ff_f \
931
+ (char **, npy_intp *, npy_intp *, void *)
932
+ void PyUFunc_dd_d \
933
+ (char **, npy_intp *, npy_intp *, void *)
934
+ void PyUFunc_gg_g \
935
+ (char **, npy_intp *, npy_intp *, void *)
936
+ void PyUFunc_FF_F_As_DD_D \
937
+ (char **, npy_intp *, npy_intp *, void *)
938
+ void PyUFunc_DD_D \
939
+ (char **, npy_intp *, npy_intp *, void *)
940
+ void PyUFunc_FF_F \
941
+ (char **, npy_intp *, npy_intp *, void *)
942
+ void PyUFunc_GG_G \
943
+ (char **, npy_intp *, npy_intp *, void *)
944
+ void PyUFunc_OO_O \
945
+ (char **, npy_intp *, npy_intp *, void *)
946
+ void PyUFunc_O_O_method \
947
+ (char **, npy_intp *, npy_intp *, void *)
948
+ void PyUFunc_OO_O_method \
949
+ (char **, npy_intp *, npy_intp *, void *)
950
+ void PyUFunc_On_Om \
951
+ (char **, npy_intp *, npy_intp *, void *)
952
+ int PyUFunc_GetPyValues \
953
+ (char *, int *, int *, PyObject **)
954
+ int PyUFunc_checkfperr \
955
+ (int, PyObject *, int *)
956
+ void PyUFunc_clearfperr()
957
+ int PyUFunc_getfperr()
958
+ int PyUFunc_handlefperr \
959
+ (int, PyObject *, int, int *) except -1
960
+ int PyUFunc_ReplaceLoopBySignature \
961
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
962
+ object PyUFunc_FromFuncAndDataAndSignature \
963
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
964
+ int, char *, char *, int, char *)
965
+
966
+ int _import_umath() except -1
967
+
968
+ cdef inline void set_array_base(ndarray arr, object base):
969
+ Py_INCREF(base) # important to do this before stealing the reference below!
970
+ PyArray_SetBaseObject(arr, base)
971
+
972
+ cdef inline object get_array_base(ndarray arr):
973
+ base = PyArray_BASE(arr)
974
+ if base is NULL:
975
+ return None
976
+ return <object>base
977
+
978
+ # Versions of the import_* functions which are more suitable for
979
+ # Cython code.
980
+ cdef inline int import_array() except -1:
981
+ try:
982
+ __pyx_import_array()
983
+ except Exception:
984
+ raise ImportError("numpy.core.multiarray failed to import")
985
+
986
+ cdef inline int import_umath() except -1:
987
+ try:
988
+ _import_umath()
989
+ except Exception:
990
+ raise ImportError("numpy.core.umath failed to import")
991
+
992
+ cdef inline int import_ufunc() except -1:
993
+ try:
994
+ _import_umath()
995
+ except Exception:
996
+ raise ImportError("numpy.core.umath failed to import")
997
+
998
+
999
+ cdef inline bint is_timedelta64_object(object obj):
1000
+ """
1001
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
1002
+
1003
+ Parameters
1004
+ ----------
1005
+ obj : object
1006
+
1007
+ Returns
1008
+ -------
1009
+ bool
1010
+ """
1011
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
1012
+
1013
+
1014
+ cdef inline bint is_datetime64_object(object obj):
1015
+ """
1016
+ Cython equivalent of `isinstance(obj, np.datetime64)`
1017
+
1018
+ Parameters
1019
+ ----------
1020
+ obj : object
1021
+
1022
+ Returns
1023
+ -------
1024
+ bool
1025
+ """
1026
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
1027
+
1028
+
1029
+ cdef inline npy_datetime get_datetime64_value(object obj) nogil:
1030
+ """
1031
+ returns the int64 value underlying scalar numpy datetime64 object
1032
+
1033
+ Note that to interpret this as a datetime, the corresponding unit is
1034
+ also needed. That can be found using `get_datetime64_unit`.
1035
+ """
1036
+ return (<PyDatetimeScalarObject*>obj).obval
1037
+
1038
+
1039
+ cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
1040
+ """
1041
+ returns the int64 value underlying scalar numpy timedelta64 object
1042
+ """
1043
+ return (<PyTimedeltaScalarObject*>obj).obval
1044
+
1045
+
1046
+ cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
1047
+ """
1048
+ returns the unit part of the dtype for a numpy datetime64 object.
1049
+ """
1050
+ return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__init__.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NumPy
3
+ =====
4
+
5
+ Provides
6
+ 1. An array object of arbitrary homogeneous items
7
+ 2. Fast mathematical operations over arrays
8
+ 3. Linear Algebra, Fourier Transforms, Random Number Generation
9
+
10
+ How to use the documentation
11
+ ----------------------------
12
+ Documentation is available in two forms: docstrings provided
13
+ with the code, and a loose standing reference guide, available from
14
+ `the NumPy homepage <https://numpy.org>`_.
15
+
16
+ We recommend exploring the docstrings using
17
+ `IPython <https://ipython.org>`_, an advanced Python shell with
18
+ TAB-completion and introspection capabilities. See below for further
19
+ instructions.
20
+
21
+ The docstring examples assume that `numpy` has been imported as ``np``::
22
+
23
+ >>> import numpy as np
24
+
25
+ Code snippets are indicated by three greater-than signs::
26
+
27
+ >>> x = 42
28
+ >>> x = x + 1
29
+
30
+ Use the built-in ``help`` function to view a function's docstring::
31
+
32
+ >>> help(np.sort)
33
+ ... # doctest: +SKIP
34
+
35
+ For some objects, ``np.info(obj)`` may provide additional help. This is
36
+ particularly true if you see the line "Help on ufunc object:" at the top
37
+ of the help() page. Ufuncs are implemented in C, not Python, for speed.
38
+ The native Python help() does not know how to view their help, but our
39
+ np.info() function does.
40
+
41
+ To search for documents containing a keyword, do::
42
+
43
+ >>> np.lookfor('keyword')
44
+ ... # doctest: +SKIP
45
+
46
+ General-purpose documents like a glossary and help on the basic concepts
47
+ of numpy are available under the ``doc`` sub-module::
48
+
49
+ >>> from numpy import doc
50
+ >>> help(doc)
51
+ ... # doctest: +SKIP
52
+
53
+ Available subpackages
54
+ ---------------------
55
+ lib
56
+ Basic functions used by several sub-packages.
57
+ random
58
+ Core Random Tools
59
+ linalg
60
+ Core Linear Algebra Tools
61
+ fft
62
+ Core FFT routines
63
+ polynomial
64
+ Polynomial tools
65
+ testing
66
+ NumPy testing tools
67
+ distutils
68
+ Enhancements to distutils with support for
69
+ Fortran compilers support and more (for Python <= 3.11).
70
+
71
+ Utilities
72
+ ---------
73
+ test
74
+ Run numpy unittests
75
+ show_config
76
+ Show numpy build configuration
77
+ matlib
78
+ Make everything matrices.
79
+ __version__
80
+ NumPy version string
81
+
82
+ Viewing documentation using IPython
83
+ -----------------------------------
84
+
85
+ Start IPython and import `numpy` usually under the alias ``np``: `import
86
+ numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
87
+ examples into the shell. To see which functions are available in `numpy`,
88
+ type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
89
+ ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
90
+ down the list. To view the docstring for a function, use
91
+ ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
92
+ the source code).
93
+
94
+ Copies vs. in-place operation
95
+ -----------------------------
96
+ Most of the functions in `numpy` return a copy of the array argument
97
+ (e.g., `np.sort`). In-place versions of these functions are often
98
+ available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
99
+ Exceptions to this rule are documented.
100
+
101
+ """
102
+ import sys
103
+ import warnings
104
+
105
+ from ._globals import _NoValue, _CopyMode
106
+ # These exceptions were moved in 1.25 and are hidden from __dir__()
107
+ from .exceptions import (
108
+ ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning,
109
+ TooHardError, AxisError)
110
+
111
+
112
+ # If a version with git hash was stored, use that instead
113
+ from . import version
114
+ from .version import __version__
115
+
116
+ # We first need to detect if we're being called as part of the numpy setup
117
+ # procedure itself in a reliable manner.
118
+ try:
119
+ __NUMPY_SETUP__
120
+ except NameError:
121
+ __NUMPY_SETUP__ = False
122
+
123
+ if __NUMPY_SETUP__:
124
+ sys.stderr.write('Running from numpy source directory.\n')
125
+ else:
126
+ # Allow distributors to run custom init code before importing numpy.core
127
+ from . import _distributor_init
128
+
129
+ try:
130
+ from numpy.__config__ import show as show_config
131
+ except ImportError as e:
132
+ msg = """Error importing numpy: you should not try to import numpy from
133
+ its source directory; please exit the numpy source tree, and relaunch
134
+ your python interpreter from there."""
135
+ raise ImportError(msg) from e
136
+
137
+ __all__ = [
138
+ 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
139
+ 'ComplexWarning', 'TooHardError', 'AxisError']
140
+
141
+ # mapping of {name: (value, deprecation_msg)}
142
+ __deprecated_attrs__ = {}
143
+
144
+ from . import core
145
+ from .core import *
146
+ from . import compat
147
+ from . import exceptions
148
+ from . import dtypes
149
+ from . import lib
150
+ # NOTE: to be revisited following future namespace cleanup.
151
+ # See gh-14454 and gh-15672 for discussion.
152
+ from .lib import *
153
+
154
+ from . import linalg
155
+ from . import fft
156
+ from . import polynomial
157
+ from . import random
158
+ from . import ctypeslib
159
+ from . import ma
160
+ from . import matrixlib as _mat
161
+ from .matrixlib import *
162
+
163
+ # Deprecations introduced in NumPy 1.20.0, 2020-06-06
164
+ import builtins as _builtins
165
+
166
+ _msg = (
167
+ "module 'numpy' has no attribute '{n}'.\n"
168
+ "`np.{n}` was a deprecated alias for the builtin `{n}`. "
169
+ "To avoid this error in existing code, use `{n}` by itself. "
170
+ "Doing this will not modify any behavior and is safe. {extended_msg}\n"
171
+ "The aliases was originally deprecated in NumPy 1.20; for more "
172
+ "details and guidance see the original release note at:\n"
173
+ " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
174
+
175
+ _specific_msg = (
176
+ "If you specifically wanted the numpy scalar type, use `np.{}` here.")
177
+
178
+ _int_extended_msg = (
179
+ "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
180
+ "or `np.int32` to specify the precision. If you wish to review "
181
+ "your current use, check the release note link for "
182
+ "additional information.")
183
+
184
+ _type_info = [
185
+ ("object", ""), # The NumPy scalar only exists by name.
186
+ ("bool", _specific_msg.format("bool_")),
187
+ ("float", _specific_msg.format("float64")),
188
+ ("complex", _specific_msg.format("complex128")),
189
+ ("str", _specific_msg.format("str_")),
190
+ ("int", _int_extended_msg.format("int"))]
191
+
192
+ __former_attrs__ = {
193
+ n: _msg.format(n=n, extended_msg=extended_msg)
194
+ for n, extended_msg in _type_info
195
+ }
196
+
197
+ # Future warning introduced in NumPy 1.24.0, 2022-11-17
198
+ _msg = (
199
+ "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
200
+
201
+ # Some of these are awkward (since `np.str` may be preferable in the long
202
+ # term), but overall the names ending in 0 seem undesirable
203
+ _type_info = [
204
+ ("bool8", bool_, "np.bool_"),
205
+ ("int0", intp, "np.intp"),
206
+ ("uint0", uintp, "np.uintp"),
207
+ ("str0", str_, "np.str_"),
208
+ ("bytes0", bytes_, "np.bytes_"),
209
+ ("void0", void, "np.void"),
210
+ ("object0", object_,
211
+ "`np.object0` is a deprecated alias for `np.object_`. "
212
+ "`object` can be used instead. (Deprecated NumPy 1.24)")]
213
+
214
+ # Some of these could be defined right away, but most were aliases to
215
+ # the Python objects and only removed in NumPy 1.24. Defining them should
216
+ # probably wait for NumPy 1.26 or 2.0.
217
+ # When defined, these should possibly not be added to `__all__` to avoid
218
+ # import with `from numpy import *`.
219
+ __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
220
+
221
+ __deprecated_attrs__.update({
222
+ n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
223
+
224
+ import math
225
+
226
+ __deprecated_attrs__['math'] = (math,
227
+ "`np.math` is a deprecated alias for the standard library `math` "
228
+ "module (Deprecated Numpy 1.25). Replace usages of `np.math` with "
229
+ "`math`")
230
+
231
+ del math, _msg, _type_info
232
+
233
+ from .core import abs
234
+ # now that numpy modules are imported, can initialize limits
235
+ core.getlimits._register_known_types()
236
+
237
+ __all__.extend(['__version__', 'show_config'])
238
+ __all__.extend(core.__all__)
239
+ __all__.extend(_mat.__all__)
240
+ __all__.extend(lib.__all__)
241
+ __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
242
+
243
+ # Remove min and max from __all__ to avoid `from numpy import *` override
244
+ # the builtins min/max. Temporary fix for 1.25.x/1.26.x, see gh-24229.
245
+ __all__.remove('min')
246
+ __all__.remove('max')
247
+ __all__.remove('round')
248
+
249
+ # Remove one of the two occurrences of `issubdtype`, which is exposed as
250
+ # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
251
+ __all__.remove('issubdtype')
252
+
253
+ # These are exported by np.core, but are replaced by the builtins below
254
+ # remove them to ensure that we don't end up with `np.long == np.int_`,
255
+ # which would be a breaking change.
256
+ del long, unicode
257
+ __all__.remove('long')
258
+ __all__.remove('unicode')
259
+
260
+ # Remove things that are in the numpy.lib but not in the numpy namespace
261
+ # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
262
+ # that prevents adding more things to the main namespace by accident.
263
+ # The list below will grow until the `from .lib import *` fixme above is
264
+ # taken care of
265
+ __all__.remove('Arrayterator')
266
+ del Arrayterator
267
+
268
+ # These names were removed in NumPy 1.20. For at least one release,
269
+ # attempts to access these names in the numpy namespace will trigger
270
+ # a warning, and calling the function will raise an exception.
271
+ _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
272
+ 'ppmt', 'pv', 'rate']
273
+ __expired_functions__ = {
274
+ name: (f'In accordance with NEP 32, the function {name} was removed '
275
+ 'from NumPy version 1.20. A replacement for this function '
276
+ 'is available in the numpy_financial library: '
277
+ 'https://pypi.org/project/numpy-financial')
278
+ for name in _financial_names}
279
+
280
+ # Filter out Cython harmless warnings
281
+ warnings.filterwarnings("ignore", message="numpy.dtype size changed")
282
+ warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
283
+ warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
284
+
285
+ # oldnumeric and numarray were removed in 1.9. In case some packages import
286
+ # but do not use them, we define them here for backward compatibility.
287
+ oldnumeric = 'removed'
288
+ numarray = 'removed'
289
+
290
+ def __getattr__(attr):
291
+ # Warn for expired attributes, and return a dummy function
292
+ # that always raises an exception.
293
+ import warnings
294
+ import math
295
+ try:
296
+ msg = __expired_functions__[attr]
297
+ except KeyError:
298
+ pass
299
+ else:
300
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
301
+
302
+ def _expired(*args, **kwds):
303
+ raise RuntimeError(msg)
304
+
305
+ return _expired
306
+
307
+ # Emit warnings for deprecated attributes
308
+ try:
309
+ val, msg = __deprecated_attrs__[attr]
310
+ except KeyError:
311
+ pass
312
+ else:
313
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
314
+ return val
315
+
316
+ if attr in __future_scalars__:
317
+ # And future warnings for those that will change, but also give
318
+ # the AttributeError
319
+ warnings.warn(
320
+ f"In the future `np.{attr}` will be defined as the "
321
+ "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
322
+
323
+ if attr in __former_attrs__:
324
+ raise AttributeError(__former_attrs__[attr])
325
+
326
+ if attr == 'testing':
327
+ import numpy.testing as testing
328
+ return testing
329
+ elif attr == 'Tester':
330
+ "Removed in NumPy 1.25.0"
331
+ raise RuntimeError("Tester was removed in NumPy 1.25.")
332
+
333
+ raise AttributeError("module {!r} has no attribute "
334
+ "{!r}".format(__name__, attr))
335
+
336
+ def __dir__():
337
+ public_symbols = globals().keys() | {'testing'}
338
+ public_symbols -= {
339
+ "core", "matrixlib",
340
+ # These were moved in 1.25 and may be deprecated eventually:
341
+ "ModuleDeprecationWarning", "VisibleDeprecationWarning",
342
+ "ComplexWarning", "TooHardError", "AxisError"
343
+ }
344
+ return list(public_symbols)
345
+
346
+ # Pytest testing
347
+ from numpy._pytesttester import PytestTester
348
+ test = PytestTester(__name__)
349
+ del PytestTester
350
+
351
+ def _sanity_check():
352
+ """
353
+ Quick sanity checks for common bugs caused by environment.
354
+ There are some cases e.g. with wrong BLAS ABI that cause wrong
355
+ results under specific runtime conditions that are not necessarily
356
+ achieved during test suite runs, and it is useful to catch those early.
357
+
358
+ See https://github.com/numpy/numpy/issues/8577 and other
359
+ similar bug reports.
360
+
361
+ """
362
+ try:
363
+ x = ones(2, dtype=float32)
364
+ if not abs(x.dot(x) - float32(2.0)) < 1e-5:
365
+ raise AssertionError()
366
+ except AssertionError:
367
+ msg = ("The current Numpy installation ({!r}) fails to "
368
+ "pass simple sanity checks. This can be caused for example "
369
+ "by incorrect BLAS library being linked in, or by mixing "
370
+ "package managers (pip, conda, apt, ...). Search closed "
371
+ "numpy issues for similar problems.")
372
+ raise RuntimeError(msg.format(__file__)) from None
373
+
374
+ _sanity_check()
375
+ del _sanity_check
376
+
377
+ def _mac_os_check():
378
+ """
379
+ Quick Sanity check for Mac OS look for accelerate build bugs.
380
+ Testing numpy polyfit calls init_dgelsd(LAPACK)
381
+ """
382
+ try:
383
+ c = array([3., 2., 1.])
384
+ x = linspace(0, 2, 5)
385
+ y = polyval(c, x)
386
+ _ = polyfit(x, y, 2, cov=True)
387
+ except ValueError:
388
+ pass
389
+
390
+ if sys.platform == "darwin":
391
+ from . import exceptions
392
+ with warnings.catch_warnings(record=True) as w:
393
+ _mac_os_check()
394
+ # Throw runtime error, if the test failed Check for warning and error_message
395
+ if len(w) > 0:
396
+ for _wn in w:
397
+ if _wn.category is exceptions.RankWarning:
398
+ # Ignore other warnings, they may not be relevant (see gh-25433).
399
+ error_message = f"{_wn.category.__name__}: {str(_wn.message)}"
400
+ msg = (
401
+ "Polyfit sanity test emitted a warning, most likely due "
402
+ "to using a buggy Accelerate backend."
403
+ "\nIf you compiled yourself, more information is available at:"
404
+ "\nhttps://numpy.org/devdocs/building/index.html"
405
+ "\nOtherwise report this to the vendor "
406
+ "that provided NumPy.\n\n{}\n".format(error_message))
407
+ raise RuntimeError(msg)
408
+ del _wn
409
+ del w
410
+ del _mac_os_check
411
+
412
+ # We usually use madvise hugepages support, but on some old kernels it
413
+ # is slow and thus better avoided.
414
+ # Specifically kernel version 4.6 had a bug fix which probably fixed this:
415
+ # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
416
+ import os
417
+ use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
418
+ if sys.platform == "linux" and use_hugepage is None:
419
+ # If there is an issue with parsing the kernel version,
420
+ # set use_hugepages to 0. Usage of LooseVersion will handle
421
+ # the kernel version parsing better, but avoided since it
422
+ # will increase the import time. See: #16679 for related discussion.
423
+ try:
424
+ use_hugepage = 1
425
+ kernel_version = os.uname().release.split(".")[:2]
426
+ kernel_version = tuple(int(v) for v in kernel_version)
427
+ if kernel_version < (4, 6):
428
+ use_hugepage = 0
429
+ except ValueError:
430
+ use_hugepages = 0
431
+ elif use_hugepage is None:
432
+ # This is not Linux, so it should not matter, just enable anyway
433
+ use_hugepage = 1
434
+ else:
435
+ use_hugepage = int(use_hugepage)
436
+
437
+ # Note that this will currently only make a difference on Linux
438
+ core.multiarray._set_madvise_hugepage(use_hugepage)
439
+ del use_hugepage
440
+
441
+ # Give a warning if NumPy is reloaded or imported on a sub-interpreter
442
+ # We do this from python, since the C-module may not be reloaded and
443
+ # it is tidier organized.
444
+ core.multiarray._multiarray_umath._reload_guard()
445
+
446
+ # default to "weak" promotion for "NumPy 2".
447
+ core._set_promotion_state(
448
+ os.environ.get("NPY_PROMOTION_STATE",
449
+ "weak" if _using_numpy2_behavior() else "legacy"))
450
+
451
+ # Tell PyInstaller where to find hook-numpy.py
452
+ def _pyinstaller_hooks_dir():
453
+ from pathlib import Path
454
+ return [str(Path(__file__).with_name("_pyinstaller").resolve())]
455
+
456
+ # Remove symbols imported for internal use
457
+ del os
458
+
459
+
460
+ # Remove symbols imported for internal use
461
+ del sys, warnings
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/__init__.pyi ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/_distributor_init.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Distributor init file
2
+
3
+ Distributors: you can add custom code here to support particular distributions
4
+ of numpy.
5
+
6
+ For example, this is a good place to put any BLAS/LAPACK initialization code.
7
+
8
+ The numpy standard source distribution will not put code in this file, so you
9
+ can safely replace this file with your own version.
10
+ """
11
+
12
+ try:
13
+ from . import _distributor_init_local
14
+ except ImportError:
15
+ pass
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/_globals.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module defining global singleton classes.
3
+
4
+ This module raises a RuntimeError if an attempt to reload it is made. In that
5
+ way the identities of the classes defined here are fixed and will remain so
6
+ even if numpy itself is reloaded. In particular, a function like the following
7
+ will still work correctly after numpy is reloaded::
8
+
9
+ def foo(arg=np._NoValue):
10
+ if arg is np._NoValue:
11
+ ...
12
+
13
+ That was not the case when the singleton classes were defined in the numpy
14
+ ``__init__.py`` file. See gh-7844 for a discussion of the reload problem that
15
+ motivated this module.
16
+
17
+ """
18
+ import enum
19
+
20
+ from ._utils import set_module as _set_module
21
+
22
+ __all__ = ['_NoValue', '_CopyMode']
23
+
24
+
25
+ # Disallow reloading this module so as to preserve the identities of the
26
+ # classes defined here.
27
+ if '_is_loaded' in globals():
28
+ raise RuntimeError('Reloading numpy._globals is not allowed')
29
+ _is_loaded = True
30
+
31
+
32
+ class _NoValueType:
33
+ """Special keyword value.
34
+
35
+ The instance of this class may be used as the default value assigned to a
36
+ keyword if no other obvious default (e.g., `None`) is suitable,
37
+
38
+ Common reasons for using this keyword are:
39
+
40
+ - A new keyword is added to a function, and that function forwards its
41
+ inputs to another function or method which can be defined outside of
42
+ NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims``
43
+ keyword was added that could only be forwarded if the user explicitly
44
+ specified ``keepdims``; downstream array libraries may not have added
45
+ the same keyword, so adding ``x.std(..., keepdims=keepdims)``
46
+ unconditionally could have broken previously working code.
47
+ - A keyword is being deprecated, and a deprecation warning must only be
48
+ emitted when the keyword is used.
49
+
50
+ """
51
+ __instance = None
52
+ def __new__(cls):
53
+ # ensure that only one instance exists
54
+ if not cls.__instance:
55
+ cls.__instance = super().__new__(cls)
56
+ return cls.__instance
57
+
58
+ def __repr__(self):
59
+ return "<no value>"
60
+
61
+
62
+ _NoValue = _NoValueType()
63
+
64
+
65
+ @_set_module("numpy")
66
+ class _CopyMode(enum.Enum):
67
+ """
68
+ An enumeration for the copy modes supported
69
+ by numpy.copy() and numpy.array(). The following three modes are supported,
70
+
71
+ - ALWAYS: This means that a deep copy of the input
72
+ array will always be taken.
73
+ - IF_NEEDED: This means that a deep copy of the input
74
+ array will be taken only if necessary.
75
+ - NEVER: This means that the deep copy will never be taken.
76
+ If a copy cannot be avoided then a `ValueError` will be
77
+ raised.
78
+
79
+ Note that the buffer-protocol could in theory do copies. NumPy currently
80
+ assumes an object exporting the buffer protocol will never do this.
81
+ """
82
+
83
+ ALWAYS = True
84
+ IF_NEEDED = False
85
+ NEVER = 2
86
+
87
+ def __bool__(self):
88
+ # For backwards compatibility
89
+ if self == _CopyMode.ALWAYS:
90
+ return True
91
+
92
+ if self == _CopyMode.IF_NEEDED:
93
+ return False
94
+
95
+ raise ValueError(f"{self} is neither True nor False.")
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/_pytesttester.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pytest test running.
3
+
4
+ This module implements the ``test()`` function for NumPy modules. The usual
5
+ boiler plate for doing that is to put the following in the module
6
+ ``__init__.py`` file::
7
+
8
+ from numpy._pytesttester import PytestTester
9
+ test = PytestTester(__name__)
10
+ del PytestTester
11
+
12
+
13
+ Warnings filtering and other runtime settings should be dealt with in the
14
+ ``pytest.ini`` file in the numpy repo root. The behavior of the test depends on
15
+ whether or not that file is found as follows:
16
+
17
+ * ``pytest.ini`` is present (develop mode)
18
+ All warnings except those explicitly filtered out are raised as error.
19
+ * ``pytest.ini`` is absent (release mode)
20
+ DeprecationWarnings and PendingDeprecationWarnings are ignored, other
21
+ warnings are passed through.
22
+
23
+ In practice, tests run from the numpy repo are run in develop mode. That
24
+ includes the standard ``python runtests.py`` invocation.
25
+
26
+ This module is imported by every numpy subpackage, so lies at the top level to
27
+ simplify circular import issues. For the same reason, it contains no numpy
28
+ imports at module scope, instead importing numpy within function calls.
29
+ """
30
+ import sys
31
+ import os
32
+
33
+ __all__ = ['PytestTester']
34
+
35
+
36
+ def _show_numpy_info():
37
+ import numpy as np
38
+
39
+ print("NumPy version %s" % np.__version__)
40
+ relaxed_strides = np.ones((10, 1), order="C").flags.f_contiguous
41
+ print("NumPy relaxed strides checking option:", relaxed_strides)
42
+ info = np.lib.utils._opt_info()
43
+ print("NumPy CPU features: ", (info if info else 'nothing enabled'))
44
+
45
+
46
+ class PytestTester:
47
+ """
48
+ Pytest test runner.
49
+
50
+ A test function is typically added to a package's __init__.py like so::
51
+
52
+ from numpy._pytesttester import PytestTester
53
+ test = PytestTester(__name__).test
54
+ del PytestTester
55
+
56
+ Calling this test function finds and runs all tests associated with the
57
+ module and all its sub-modules.
58
+
59
+ Attributes
60
+ ----------
61
+ module_name : str
62
+ Full path to the package to test.
63
+
64
+ Parameters
65
+ ----------
66
+ module_name : module name
67
+ The name of the module to test.
68
+
69
+ Notes
70
+ -----
71
+ Unlike the previous ``nose``-based implementation, this class is not
72
+ publicly exposed as it performs some ``numpy``-specific warning
73
+ suppression.
74
+
75
+ """
76
+ def __init__(self, module_name):
77
+ self.module_name = module_name
78
+
79
+ def __call__(self, label='fast', verbose=1, extra_argv=None,
80
+ doctests=False, coverage=False, durations=-1, tests=None):
81
+ """
82
+ Run tests for module using pytest.
83
+
84
+ Parameters
85
+ ----------
86
+ label : {'fast', 'full'}, optional
87
+ Identifies the tests to run. When set to 'fast', tests decorated
88
+ with `pytest.mark.slow` are skipped, when 'full', the slow marker
89
+ is ignored.
90
+ verbose : int, optional
91
+ Verbosity value for test outputs, in the range 1-3. Default is 1.
92
+ extra_argv : list, optional
93
+ List with any extra arguments to pass to pytests.
94
+ doctests : bool, optional
95
+ .. note:: Not supported
96
+ coverage : bool, optional
97
+ If True, report coverage of NumPy code. Default is False.
98
+ Requires installation of (pip) pytest-cov.
99
+ durations : int, optional
100
+ If < 0, do nothing, If 0, report time of all tests, if > 0,
101
+ report the time of the slowest `timer` tests. Default is -1.
102
+ tests : test or list of tests
103
+ Tests to be executed with pytest '--pyargs'
104
+
105
+ Returns
106
+ -------
107
+ result : bool
108
+ Return True on success, false otherwise.
109
+
110
+ Notes
111
+ -----
112
+ Each NumPy module exposes `test` in its namespace to run all tests for
113
+ it. For example, to run all tests for numpy.lib:
114
+
115
+ >>> np.lib.test() #doctest: +SKIP
116
+
117
+ Examples
118
+ --------
119
+ >>> result = np.lib.test() #doctest: +SKIP
120
+ ...
121
+ 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds
122
+ >>> result
123
+ True
124
+
125
+ """
126
+ import pytest
127
+ import warnings
128
+
129
+ module = sys.modules[self.module_name]
130
+ module_path = os.path.abspath(module.__path__[0])
131
+
132
+ # setup the pytest arguments
133
+ pytest_args = ["-l"]
134
+
135
+ # offset verbosity. The "-q" cancels a "-v".
136
+ pytest_args += ["-q"]
137
+
138
+ if sys.version_info < (3, 12):
139
+ with warnings.catch_warnings():
140
+ warnings.simplefilter("always")
141
+ # Filter out distutils cpu warnings (could be localized to
142
+ # distutils tests). ASV has problems with top level import,
143
+ # so fetch module for suppression here.
144
+ from numpy.distutils import cpuinfo
145
+
146
+ with warnings.catch_warnings(record=True):
147
+ # Ignore the warning from importing the array_api submodule. This
148
+ # warning is done on import, so it would break pytest collection,
149
+ # but importing it early here prevents the warning from being
150
+ # issued when it imported again.
151
+ import numpy.array_api
152
+
153
+ # Filter out annoying import messages. Want these in both develop and
154
+ # release mode.
155
+ pytest_args += [
156
+ "-W ignore:Not importing directory",
157
+ "-W ignore:numpy.dtype size changed",
158
+ "-W ignore:numpy.ufunc size changed",
159
+ "-W ignore::UserWarning:cpuinfo",
160
+ ]
161
+
162
+ # When testing matrices, ignore their PendingDeprecationWarnings
163
+ pytest_args += [
164
+ "-W ignore:the matrix subclass is not",
165
+ "-W ignore:Importing from numpy.matlib is",
166
+ ]
167
+
168
+ if doctests:
169
+ pytest_args += ["--doctest-modules"]
170
+
171
+ if extra_argv:
172
+ pytest_args += list(extra_argv)
173
+
174
+ if verbose > 1:
175
+ pytest_args += ["-" + "v"*(verbose - 1)]
176
+
177
+ if coverage:
178
+ pytest_args += ["--cov=" + module_path]
179
+
180
+ if label == "fast":
181
+ # not importing at the top level to avoid circular import of module
182
+ from numpy.testing import IS_PYPY
183
+ if IS_PYPY:
184
+ pytest_args += ["-m", "not slow and not slow_pypy"]
185
+ else:
186
+ pytest_args += ["-m", "not slow"]
187
+
188
+ elif label != "full":
189
+ pytest_args += ["-m", label]
190
+
191
+ if durations >= 0:
192
+ pytest_args += ["--durations=%s" % durations]
193
+
194
+ if tests is None:
195
+ tests = [self.module_name]
196
+
197
+ pytest_args += ["--pyargs"] + list(tests)
198
+
199
+ # run tests.
200
+ _show_numpy_info()
201
+
202
+ try:
203
+ code = pytest.main(pytest_args)
204
+ except SystemExit as exc:
205
+ code = exc.code
206
+
207
+ return code == 0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/ctypeslib.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ============================
3
+ ``ctypes`` Utility Functions
4
+ ============================
5
+
6
+ See Also
7
+ --------
8
+ load_library : Load a C library.
9
+ ndpointer : Array restype/argtype with verification.
10
+ as_ctypes : Create a ctypes array from an ndarray.
11
+ as_array : Create an ndarray from a ctypes array.
12
+
13
+ References
14
+ ----------
15
+ .. [1] "SciPy Cookbook: ctypes", https://scipy-cookbook.readthedocs.io/items/Ctypes.html
16
+
17
+ Examples
18
+ --------
19
+ Load the C library:
20
+
21
+ >>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP
22
+
23
+ Our result type, an ndarray that must be of type double, be 1-dimensional
24
+ and is C-contiguous in memory:
25
+
26
+ >>> array_1d_double = np.ctypeslib.ndpointer(
27
+ ... dtype=np.double,
28
+ ... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP
29
+
30
+ Our C-function typically takes an array and updates its values
31
+ in-place. For example::
32
+
33
+ void foo_func(double* x, int length)
34
+ {
35
+ int i;
36
+ for (i = 0; i < length; i++) {
37
+ x[i] = i*i;
38
+ }
39
+ }
40
+
41
+ We wrap it using:
42
+
43
+ >>> _lib.foo_func.restype = None #doctest: +SKIP
44
+ >>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP
45
+
46
+ Then, we're ready to call ``foo_func``:
47
+
48
+ >>> out = np.empty(15, dtype=np.double)
49
+ >>> _lib.foo_func(out, len(out)) #doctest: +SKIP
50
+
51
+ """
52
+ __all__ = ['load_library', 'ndpointer', 'c_intp', 'as_ctypes', 'as_array',
53
+ 'as_ctypes_type']
54
+
55
+ import os
56
+ from numpy import (
57
+ integer, ndarray, dtype as _dtype, asarray, frombuffer
58
+ )
59
+ from numpy.core.multiarray import _flagdict, flagsobj
60
+
61
+ try:
62
+ import ctypes
63
+ except ImportError:
64
+ ctypes = None
65
+
66
+ if ctypes is None:
67
+ def _dummy(*args, **kwds):
68
+ """
69
+ Dummy object that raises an ImportError if ctypes is not available.
70
+
71
+ Raises
72
+ ------
73
+ ImportError
74
+ If ctypes is not available.
75
+
76
+ """
77
+ raise ImportError("ctypes is not available.")
78
+ load_library = _dummy
79
+ as_ctypes = _dummy
80
+ as_array = _dummy
81
+ from numpy import intp as c_intp
82
+ _ndptr_base = object
83
+ else:
84
+ import numpy.core._internal as nic
85
+ c_intp = nic._getintp_ctype()
86
+ del nic
87
+ _ndptr_base = ctypes.c_void_p
88
+
89
+ # Adapted from Albert Strasheim
90
+ def load_library(libname, loader_path):
91
+ """
92
+ It is possible to load a library using
93
+
94
+ >>> lib = ctypes.cdll[<full_path_name>] # doctest: +SKIP
95
+
96
+ But there are cross-platform considerations, such as library file extensions,
97
+ plus the fact Windows will just load the first library it finds with that name.
98
+ NumPy supplies the load_library function as a convenience.
99
+
100
+ .. versionchanged:: 1.20.0
101
+ Allow libname and loader_path to take any
102
+ :term:`python:path-like object`.
103
+
104
+ Parameters
105
+ ----------
106
+ libname : path-like
107
+ Name of the library, which can have 'lib' as a prefix,
108
+ but without an extension.
109
+ loader_path : path-like
110
+ Where the library can be found.
111
+
112
+ Returns
113
+ -------
114
+ ctypes.cdll[libpath] : library object
115
+ A ctypes library object
116
+
117
+ Raises
118
+ ------
119
+ OSError
120
+ If there is no library with the expected extension, or the
121
+ library is defective and cannot be loaded.
122
+ """
123
+ # Convert path-like objects into strings
124
+ libname = os.fsdecode(libname)
125
+ loader_path = os.fsdecode(loader_path)
126
+
127
+ ext = os.path.splitext(libname)[1]
128
+ if not ext:
129
+ import sys
130
+ import sysconfig
131
+ # Try to load library with platform-specific name, otherwise
132
+ # default to libname.[so|dll|dylib]. Sometimes, these files are
133
+ # built erroneously on non-linux platforms.
134
+ base_ext = ".so"
135
+ if sys.platform.startswith("darwin"):
136
+ base_ext = ".dylib"
137
+ elif sys.platform.startswith("win"):
138
+ base_ext = ".dll"
139
+ libname_ext = [libname + base_ext]
140
+ so_ext = sysconfig.get_config_var("EXT_SUFFIX")
141
+ if not so_ext == base_ext:
142
+ libname_ext.insert(0, libname + so_ext)
143
+ else:
144
+ libname_ext = [libname]
145
+
146
+ loader_path = os.path.abspath(loader_path)
147
+ if not os.path.isdir(loader_path):
148
+ libdir = os.path.dirname(loader_path)
149
+ else:
150
+ libdir = loader_path
151
+
152
+ for ln in libname_ext:
153
+ libpath = os.path.join(libdir, ln)
154
+ if os.path.exists(libpath):
155
+ try:
156
+ return ctypes.cdll[libpath]
157
+ except OSError:
158
+ ## defective lib file
159
+ raise
160
+ ## if no successful return in the libname_ext loop:
161
+ raise OSError("no file with expected extension")
162
+
163
+
164
+ def _num_fromflags(flaglist):
165
+ num = 0
166
+ for val in flaglist:
167
+ num += _flagdict[val]
168
+ return num
169
+
170
+ _flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE',
171
+ 'OWNDATA', 'WRITEBACKIFCOPY']
172
+ def _flags_fromnum(num):
173
+ res = []
174
+ for key in _flagnames:
175
+ value = _flagdict[key]
176
+ if (num & value):
177
+ res.append(key)
178
+ return res
179
+
180
+
181
+ class _ndptr(_ndptr_base):
182
+ @classmethod
183
+ def from_param(cls, obj):
184
+ if not isinstance(obj, ndarray):
185
+ raise TypeError("argument must be an ndarray")
186
+ if cls._dtype_ is not None \
187
+ and obj.dtype != cls._dtype_:
188
+ raise TypeError("array must have data type %s" % cls._dtype_)
189
+ if cls._ndim_ is not None \
190
+ and obj.ndim != cls._ndim_:
191
+ raise TypeError("array must have %d dimension(s)" % cls._ndim_)
192
+ if cls._shape_ is not None \
193
+ and obj.shape != cls._shape_:
194
+ raise TypeError("array must have shape %s" % str(cls._shape_))
195
+ if cls._flags_ is not None \
196
+ and ((obj.flags.num & cls._flags_) != cls._flags_):
197
+ raise TypeError("array must have flags %s" %
198
+ _flags_fromnum(cls._flags_))
199
+ return obj.ctypes
200
+
201
+
202
+ class _concrete_ndptr(_ndptr):
203
+ """
204
+ Like _ndptr, but with `_shape_` and `_dtype_` specified.
205
+
206
+ Notably, this means the pointer has enough information to reconstruct
207
+ the array, which is not generally true.
208
+ """
209
+ def _check_retval_(self):
210
+ """
211
+ This method is called when this class is used as the .restype
212
+ attribute for a shared-library function, to automatically wrap the
213
+ pointer into an array.
214
+ """
215
+ return self.contents
216
+
217
+ @property
218
+ def contents(self):
219
+ """
220
+ Get an ndarray viewing the data pointed to by this pointer.
221
+
222
+ This mirrors the `contents` attribute of a normal ctypes pointer
223
+ """
224
+ full_dtype = _dtype((self._dtype_, self._shape_))
225
+ full_ctype = ctypes.c_char * full_dtype.itemsize
226
+ buffer = ctypes.cast(self, ctypes.POINTER(full_ctype)).contents
227
+ return frombuffer(buffer, dtype=full_dtype).squeeze(axis=0)
228
+
229
+
230
+ # Factory for an array-checking class with from_param defined for
231
+ # use with ctypes argtypes mechanism
232
+ _pointer_type_cache = {}
233
+ def ndpointer(dtype=None, ndim=None, shape=None, flags=None):
234
+ """
235
+ Array-checking restype/argtypes.
236
+
237
+ An ndpointer instance is used to describe an ndarray in restypes
238
+ and argtypes specifications. This approach is more flexible than
239
+ using, for example, ``POINTER(c_double)``, since several restrictions
240
+ can be specified, which are verified upon calling the ctypes function.
241
+ These include data type, number of dimensions, shape and flags. If a
242
+ given array does not satisfy the specified restrictions,
243
+ a ``TypeError`` is raised.
244
+
245
+ Parameters
246
+ ----------
247
+ dtype : data-type, optional
248
+ Array data-type.
249
+ ndim : int, optional
250
+ Number of array dimensions.
251
+ shape : tuple of ints, optional
252
+ Array shape.
253
+ flags : str or tuple of str
254
+ Array flags; may be one or more of:
255
+
256
+ - C_CONTIGUOUS / C / CONTIGUOUS
257
+ - F_CONTIGUOUS / F / FORTRAN
258
+ - OWNDATA / O
259
+ - WRITEABLE / W
260
+ - ALIGNED / A
261
+ - WRITEBACKIFCOPY / X
262
+
263
+ Returns
264
+ -------
265
+ klass : ndpointer type object
266
+ A type object, which is an ``_ndtpr`` instance containing
267
+ dtype, ndim, shape and flags information.
268
+
269
+ Raises
270
+ ------
271
+ TypeError
272
+ If a given array does not satisfy the specified restrictions.
273
+
274
+ Examples
275
+ --------
276
+ >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
277
+ ... ndim=1,
278
+ ... flags='C_CONTIGUOUS')]
279
+ ... #doctest: +SKIP
280
+ >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
281
+ ... #doctest: +SKIP
282
+
283
+ """
284
+
285
+ # normalize dtype to an Optional[dtype]
286
+ if dtype is not None:
287
+ dtype = _dtype(dtype)
288
+
289
+ # normalize flags to an Optional[int]
290
+ num = None
291
+ if flags is not None:
292
+ if isinstance(flags, str):
293
+ flags = flags.split(',')
294
+ elif isinstance(flags, (int, integer)):
295
+ num = flags
296
+ flags = _flags_fromnum(num)
297
+ elif isinstance(flags, flagsobj):
298
+ num = flags.num
299
+ flags = _flags_fromnum(num)
300
+ if num is None:
301
+ try:
302
+ flags = [x.strip().upper() for x in flags]
303
+ except Exception as e:
304
+ raise TypeError("invalid flags specification") from e
305
+ num = _num_fromflags(flags)
306
+
307
+ # normalize shape to an Optional[tuple]
308
+ if shape is not None:
309
+ try:
310
+ shape = tuple(shape)
311
+ except TypeError:
312
+ # single integer -> 1-tuple
313
+ shape = (shape,)
314
+
315
+ cache_key = (dtype, ndim, shape, num)
316
+
317
+ try:
318
+ return _pointer_type_cache[cache_key]
319
+ except KeyError:
320
+ pass
321
+
322
+ # produce a name for the new type
323
+ if dtype is None:
324
+ name = 'any'
325
+ elif dtype.names is not None:
326
+ name = str(id(dtype))
327
+ else:
328
+ name = dtype.str
329
+ if ndim is not None:
330
+ name += "_%dd" % ndim
331
+ if shape is not None:
332
+ name += "_"+"x".join(str(x) for x in shape)
333
+ if flags is not None:
334
+ name += "_"+"_".join(flags)
335
+
336
+ if dtype is not None and shape is not None:
337
+ base = _concrete_ndptr
338
+ else:
339
+ base = _ndptr
340
+
341
+ klass = type("ndpointer_%s"%name, (base,),
342
+ {"_dtype_": dtype,
343
+ "_shape_" : shape,
344
+ "_ndim_" : ndim,
345
+ "_flags_" : num})
346
+ _pointer_type_cache[cache_key] = klass
347
+ return klass
348
+
349
+
350
+ if ctypes is not None:
351
+ def _ctype_ndarray(element_type, shape):
352
+ """ Create an ndarray of the given element type and shape """
353
+ for dim in shape[::-1]:
354
+ element_type = dim * element_type
355
+ # prevent the type name include np.ctypeslib
356
+ element_type.__module__ = None
357
+ return element_type
358
+
359
+
360
+ def _get_scalar_type_map():
361
+ """
362
+ Return a dictionary mapping native endian scalar dtype to ctypes types
363
+ """
364
+ ct = ctypes
365
+ simple_types = [
366
+ ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong,
367
+ ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong,
368
+ ct.c_float, ct.c_double,
369
+ ct.c_bool,
370
+ ]
371
+ return {_dtype(ctype): ctype for ctype in simple_types}
372
+
373
+
374
+ _scalar_type_map = _get_scalar_type_map()
375
+
376
+
377
+ def _ctype_from_dtype_scalar(dtype):
378
+ # swapping twice ensure that `=` is promoted to <, >, or |
379
+ dtype_with_endian = dtype.newbyteorder('S').newbyteorder('S')
380
+ dtype_native = dtype.newbyteorder('=')
381
+ try:
382
+ ctype = _scalar_type_map[dtype_native]
383
+ except KeyError as e:
384
+ raise NotImplementedError(
385
+ "Converting {!r} to a ctypes type".format(dtype)
386
+ ) from None
387
+
388
+ if dtype_with_endian.byteorder == '>':
389
+ ctype = ctype.__ctype_be__
390
+ elif dtype_with_endian.byteorder == '<':
391
+ ctype = ctype.__ctype_le__
392
+
393
+ return ctype
394
+
395
+
396
+ def _ctype_from_dtype_subarray(dtype):
397
+ element_dtype, shape = dtype.subdtype
398
+ ctype = _ctype_from_dtype(element_dtype)
399
+ return _ctype_ndarray(ctype, shape)
400
+
401
+
402
+ def _ctype_from_dtype_structured(dtype):
403
+ # extract offsets of each field
404
+ field_data = []
405
+ for name in dtype.names:
406
+ field_dtype, offset = dtype.fields[name][:2]
407
+ field_data.append((offset, name, _ctype_from_dtype(field_dtype)))
408
+
409
+ # ctypes doesn't care about field order
410
+ field_data = sorted(field_data, key=lambda f: f[0])
411
+
412
+ if len(field_data) > 1 and all(offset == 0 for offset, name, ctype in field_data):
413
+ # union, if multiple fields all at address 0
414
+ size = 0
415
+ _fields_ = []
416
+ for offset, name, ctype in field_data:
417
+ _fields_.append((name, ctype))
418
+ size = max(size, ctypes.sizeof(ctype))
419
+
420
+ # pad to the right size
421
+ if dtype.itemsize != size:
422
+ _fields_.append(('', ctypes.c_char * dtype.itemsize))
423
+
424
+ # we inserted manual padding, so always `_pack_`
425
+ return type('union', (ctypes.Union,), dict(
426
+ _fields_=_fields_,
427
+ _pack_=1,
428
+ __module__=None,
429
+ ))
430
+ else:
431
+ last_offset = 0
432
+ _fields_ = []
433
+ for offset, name, ctype in field_data:
434
+ padding = offset - last_offset
435
+ if padding < 0:
436
+ raise NotImplementedError("Overlapping fields")
437
+ if padding > 0:
438
+ _fields_.append(('', ctypes.c_char * padding))
439
+
440
+ _fields_.append((name, ctype))
441
+ last_offset = offset + ctypes.sizeof(ctype)
442
+
443
+
444
+ padding = dtype.itemsize - last_offset
445
+ if padding > 0:
446
+ _fields_.append(('', ctypes.c_char * padding))
447
+
448
+ # we inserted manual padding, so always `_pack_`
449
+ return type('struct', (ctypes.Structure,), dict(
450
+ _fields_=_fields_,
451
+ _pack_=1,
452
+ __module__=None,
453
+ ))
454
+
455
+
456
+ def _ctype_from_dtype(dtype):
457
+ if dtype.fields is not None:
458
+ return _ctype_from_dtype_structured(dtype)
459
+ elif dtype.subdtype is not None:
460
+ return _ctype_from_dtype_subarray(dtype)
461
+ else:
462
+ return _ctype_from_dtype_scalar(dtype)
463
+
464
+
465
+ def as_ctypes_type(dtype):
466
+ r"""
467
+ Convert a dtype into a ctypes type.
468
+
469
+ Parameters
470
+ ----------
471
+ dtype : dtype
472
+ The dtype to convert
473
+
474
+ Returns
475
+ -------
476
+ ctype
477
+ A ctype scalar, union, array, or struct
478
+
479
+ Raises
480
+ ------
481
+ NotImplementedError
482
+ If the conversion is not possible
483
+
484
+ Notes
485
+ -----
486
+ This function does not losslessly round-trip in either direction.
487
+
488
+ ``np.dtype(as_ctypes_type(dt))`` will:
489
+
490
+ - insert padding fields
491
+ - reorder fields to be sorted by offset
492
+ - discard field titles
493
+
494
+ ``as_ctypes_type(np.dtype(ctype))`` will:
495
+
496
+ - discard the class names of `ctypes.Structure`\ s and
497
+ `ctypes.Union`\ s
498
+ - convert single-element `ctypes.Union`\ s into single-element
499
+ `ctypes.Structure`\ s
500
+ - insert padding fields
501
+
502
+ """
503
+ return _ctype_from_dtype(_dtype(dtype))
504
+
505
+
506
+ def as_array(obj, shape=None):
507
+ """
508
+ Create a numpy array from a ctypes array or POINTER.
509
+
510
+ The numpy array shares the memory with the ctypes object.
511
+
512
+ The shape parameter must be given if converting from a ctypes POINTER.
513
+ The shape parameter is ignored if converting from a ctypes array
514
+ """
515
+ if isinstance(obj, ctypes._Pointer):
516
+ # convert pointers to an array of the desired shape
517
+ if shape is None:
518
+ raise TypeError(
519
+ 'as_array() requires a shape argument when called on a '
520
+ 'pointer')
521
+ p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape))
522
+ obj = ctypes.cast(obj, p_arr_type).contents
523
+
524
+ return asarray(obj)
525
+
526
+
527
+ def as_ctypes(obj):
528
+ """Create and return a ctypes object from a numpy array. Actually
529
+ anything that exposes the __array_interface__ is accepted."""
530
+ ai = obj.__array_interface__
531
+ if ai["strides"]:
532
+ raise TypeError("strided arrays not supported")
533
+ if ai["version"] != 3:
534
+ raise TypeError("only __array_interface__ version 3 supported")
535
+ addr, readonly = ai["data"]
536
+ if readonly:
537
+ raise TypeError("readonly arrays unsupported")
538
+
539
+ # can't use `_dtype((ai["typestr"], ai["shape"]))` here, as it overflows
540
+ # dtype.itemsize (gh-14214)
541
+ ctype_scalar = as_ctypes_type(ai["typestr"])
542
+ result_type = _ctype_ndarray(ctype_scalar, ai["shape"])
543
+ result = result_type.from_address(addr)
544
+ result.__keep = obj
545
+ return result
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/exceptions.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Exceptions and Warnings (:mod:`numpy.exceptions`)
3
+ =================================================
4
+
5
+ General exceptions used by NumPy. Note that some exceptions may be module
6
+ specific, such as linear algebra errors.
7
+
8
+ .. versionadded:: NumPy 1.25
9
+
10
+ The exceptions module is new in NumPy 1.25. Older exceptions remain
11
+ available through the main NumPy namespace for compatibility.
12
+
13
+ .. currentmodule:: numpy.exceptions
14
+
15
+ Warnings
16
+ --------
17
+ .. autosummary::
18
+ :toctree: generated/
19
+
20
+ ComplexWarning Given when converting complex to real.
21
+ VisibleDeprecationWarning Same as a DeprecationWarning, but more visible.
22
+
23
+ Exceptions
24
+ ----------
25
+ .. autosummary::
26
+ :toctree: generated/
27
+
28
+ AxisError Given when an axis was invalid.
29
+ DTypePromotionError Given when no common dtype could be found.
30
+ TooHardError Error specific to `numpy.shares_memory`.
31
+
32
+ """
33
+
34
+
35
+ __all__ = [
36
+ "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning",
37
+ "TooHardError", "AxisError", "DTypePromotionError"]
38
+
39
+
40
+ # Disallow reloading this module so as to preserve the identities of the
41
+ # classes defined here.
42
+ if '_is_loaded' in globals():
43
+ raise RuntimeError('Reloading numpy._globals is not allowed')
44
+ _is_loaded = True
45
+
46
+
47
+ class ComplexWarning(RuntimeWarning):
48
+ """
49
+ The warning raised when casting a complex dtype to a real dtype.
50
+
51
+ As implemented, casting a complex number to a real discards its imaginary
52
+ part, but this behavior may not be what the user actually wants.
53
+
54
+ """
55
+ pass
56
+
57
+
58
+ class ModuleDeprecationWarning(DeprecationWarning):
59
+ """Module deprecation warning.
60
+
61
+ .. warning::
62
+
63
+ This warning should not be used, since nose testing is not relevant
64
+ anymore.
65
+
66
+ The nose tester turns ordinary Deprecation warnings into test failures.
67
+ That makes it hard to deprecate whole modules, because they get
68
+ imported by default. So this is a special Deprecation warning that the
69
+ nose tester will let pass without making tests fail.
70
+
71
+ """
72
+
73
+
74
+ class VisibleDeprecationWarning(UserWarning):
75
+ """Visible deprecation warning.
76
+
77
+ By default, python will not show deprecation warnings, so this class
78
+ can be used when a very visible warning is helpful, for example because
79
+ the usage is most likely a user bug.
80
+
81
+ """
82
+
83
+
84
+ # Exception used in shares_memory()
85
+ class TooHardError(RuntimeError):
86
+ """max_work was exceeded.
87
+
88
+ This is raised whenever the maximum number of candidate solutions
89
+ to consider specified by the ``max_work`` parameter is exceeded.
90
+ Assigning a finite number to max_work may have caused the operation
91
+ to fail.
92
+
93
+ """
94
+
95
+ pass
96
+
97
+
98
+ class AxisError(ValueError, IndexError):
99
+ """Axis supplied was invalid.
100
+
101
+ This is raised whenever an ``axis`` parameter is specified that is larger
102
+ than the number of array dimensions.
103
+ For compatibility with code written against older numpy versions, which
104
+ raised a mixture of `ValueError` and `IndexError` for this situation, this
105
+ exception subclasses both to ensure that ``except ValueError`` and
106
+ ``except IndexError`` statements continue to catch `AxisError`.
107
+
108
+ .. versionadded:: 1.13
109
+
110
+ Parameters
111
+ ----------
112
+ axis : int or str
113
+ The out of bounds axis or a custom exception message.
114
+ If an axis is provided, then `ndim` should be specified as well.
115
+ ndim : int, optional
116
+ The number of array dimensions.
117
+ msg_prefix : str, optional
118
+ A prefix for the exception message.
119
+
120
+ Attributes
121
+ ----------
122
+ axis : int, optional
123
+ The out of bounds axis or ``None`` if a custom exception
124
+ message was provided. This should be the axis as passed by
125
+ the user, before any normalization to resolve negative indices.
126
+
127
+ .. versionadded:: 1.22
128
+ ndim : int, optional
129
+ The number of array dimensions or ``None`` if a custom exception
130
+ message was provided.
131
+
132
+ .. versionadded:: 1.22
133
+
134
+
135
+ Examples
136
+ --------
137
+ >>> array_1d = np.arange(10)
138
+ >>> np.cumsum(array_1d, axis=1)
139
+ Traceback (most recent call last):
140
+ ...
141
+ numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
142
+
143
+ Negative axes are preserved:
144
+
145
+ >>> np.cumsum(array_1d, axis=-2)
146
+ Traceback (most recent call last):
147
+ ...
148
+ numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1
149
+
150
+ The class constructor generally takes the axis and arrays'
151
+ dimensionality as arguments:
152
+
153
+ >>> print(np.AxisError(2, 1, msg_prefix='error'))
154
+ error: axis 2 is out of bounds for array of dimension 1
155
+
156
+ Alternatively, a custom exception message can be passed:
157
+
158
+ >>> print(np.AxisError('Custom error message'))
159
+ Custom error message
160
+
161
+ """
162
+
163
+ __slots__ = ("axis", "ndim", "_msg")
164
+
165
+ def __init__(self, axis, ndim=None, msg_prefix=None):
166
+ if ndim is msg_prefix is None:
167
+ # single-argument form: directly set the error message
168
+ self._msg = axis
169
+ self.axis = None
170
+ self.ndim = None
171
+ else:
172
+ self._msg = msg_prefix
173
+ self.axis = axis
174
+ self.ndim = ndim
175
+
176
+ def __str__(self):
177
+ axis = self.axis
178
+ ndim = self.ndim
179
+
180
+ if axis is ndim is None:
181
+ return self._msg
182
+ else:
183
+ msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
184
+ if self._msg is not None:
185
+ msg = f"{self._msg}: {msg}"
186
+ return msg
187
+
188
+
189
+ class DTypePromotionError(TypeError):
190
+ """Multiple DTypes could not be converted to a common one.
191
+
192
+ This exception derives from ``TypeError`` and is raised whenever dtypes
193
+ cannot be converted to a single common one. This can be because they
194
+ are of a different category/class or incompatible instances of the same
195
+ one (see Examples).
196
+
197
+ Notes
198
+ -----
199
+ Many functions will use promotion to find the correct result and
200
+ implementation. For these functions the error will typically be chained
201
+ with a more specific error indicating that no implementation was found
202
+ for the input dtypes.
203
+
204
+ Typically promotion should be considered "invalid" between the dtypes of
205
+ two arrays when `arr1 == arr2` can safely return all ``False`` because the
206
+ dtypes are fundamentally different.
207
+
208
+ Examples
209
+ --------
210
+ Datetimes and complex numbers are incompatible classes and cannot be
211
+ promoted:
212
+
213
+ >>> np.result_type(np.dtype("M8[s]"), np.complex128)
214
+ DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
215
+ be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
216
+ DType exists for the given inputs. For example they cannot be stored in a
217
+ single array unless the dtype is `object`. The full list of DTypes is:
218
+ (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)
219
+
220
+ For example for structured dtypes, the structure can mismatch and the
221
+ same ``DTypePromotionError`` is given when two structured dtypes with
222
+ a mismatch in their number of fields is given:
223
+
224
+ >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
225
+ >>> dtype2 = np.dtype([("field1", np.float64)])
226
+ >>> np.promote_types(dtype1, dtype2)
227
+ DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
228
+ mismatch.
229
+
230
+ """
231
+ pass
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/matlib.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ # 2018-05-29, PendingDeprecationWarning added to matrix.__new__
4
+ # 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning
5
+ warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. "
6
+ "The matrix subclass is not the recommended way to represent "
7
+ "matrices or deal with linear algebra (see "
8
+ "https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). "
9
+ "Please adjust your code to use regular ndarray. ",
10
+ PendingDeprecationWarning, stacklevel=2)
11
+
12
+ import numpy as np
13
+ from numpy.matrixlib.defmatrix import matrix, asmatrix
14
+ # Matlib.py contains all functions in the numpy namespace with a few
15
+ # replacements. See doc/source/reference/routines.matlib.rst for details.
16
+ # Need * as we're copying the numpy namespace.
17
+ from numpy import * # noqa: F403
18
+
19
+ __version__ = np.__version__
20
+
21
+ __all__ = np.__all__[:] # copy numpy namespace
22
+ __all__ += ['rand', 'randn', 'repmat']
23
+
24
+ def empty(shape, dtype=None, order='C'):
25
+ """Return a new matrix of given shape and type, without initializing entries.
26
+
27
+ Parameters
28
+ ----------
29
+ shape : int or tuple of int
30
+ Shape of the empty matrix.
31
+ dtype : data-type, optional
32
+ Desired output data-type.
33
+ order : {'C', 'F'}, optional
34
+ Whether to store multi-dimensional data in row-major
35
+ (C-style) or column-major (Fortran-style) order in
36
+ memory.
37
+
38
+ See Also
39
+ --------
40
+ empty_like, zeros
41
+
42
+ Notes
43
+ -----
44
+ `empty`, unlike `zeros`, does not set the matrix values to zero,
45
+ and may therefore be marginally faster. On the other hand, it requires
46
+ the user to manually set all the values in the array, and should be
47
+ used with caution.
48
+
49
+ Examples
50
+ --------
51
+ >>> import numpy.matlib
52
+ >>> np.matlib.empty((2, 2)) # filled with random data
53
+ matrix([[ 6.76425276e-320, 9.79033856e-307], # random
54
+ [ 7.39337286e-309, 3.22135945e-309]])
55
+ >>> np.matlib.empty((2, 2), dtype=int)
56
+ matrix([[ 6600475, 0], # random
57
+ [ 6586976, 22740995]])
58
+
59
+ """
60
+ return ndarray.__new__(matrix, shape, dtype, order=order)
61
+
62
+ def ones(shape, dtype=None, order='C'):
63
+ """
64
+ Matrix of ones.
65
+
66
+ Return a matrix of given shape and type, filled with ones.
67
+
68
+ Parameters
69
+ ----------
70
+ shape : {sequence of ints, int}
71
+ Shape of the matrix
72
+ dtype : data-type, optional
73
+ The desired data-type for the matrix, default is np.float64.
74
+ order : {'C', 'F'}, optional
75
+ Whether to store matrix in C- or Fortran-contiguous order,
76
+ default is 'C'.
77
+
78
+ Returns
79
+ -------
80
+ out : matrix
81
+ Matrix of ones of given shape, dtype, and order.
82
+
83
+ See Also
84
+ --------
85
+ ones : Array of ones.
86
+ matlib.zeros : Zero matrix.
87
+
88
+ Notes
89
+ -----
90
+ If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
91
+ `out` becomes a single row matrix of shape ``(1,N)``.
92
+
93
+ Examples
94
+ --------
95
+ >>> np.matlib.ones((2,3))
96
+ matrix([[1., 1., 1.],
97
+ [1., 1., 1.]])
98
+
99
+ >>> np.matlib.ones(2)
100
+ matrix([[1., 1.]])
101
+
102
+ """
103
+ a = ndarray.__new__(matrix, shape, dtype, order=order)
104
+ a.fill(1)
105
+ return a
106
+
107
+ def zeros(shape, dtype=None, order='C'):
108
+ """
109
+ Return a matrix of given shape and type, filled with zeros.
110
+
111
+ Parameters
112
+ ----------
113
+ shape : int or sequence of ints
114
+ Shape of the matrix
115
+ dtype : data-type, optional
116
+ The desired data-type for the matrix, default is float.
117
+ order : {'C', 'F'}, optional
118
+ Whether to store the result in C- or Fortran-contiguous order,
119
+ default is 'C'.
120
+
121
+ Returns
122
+ -------
123
+ out : matrix
124
+ Zero matrix of given shape, dtype, and order.
125
+
126
+ See Also
127
+ --------
128
+ numpy.zeros : Equivalent array function.
129
+ matlib.ones : Return a matrix of ones.
130
+
131
+ Notes
132
+ -----
133
+ If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
134
+ `out` becomes a single row matrix of shape ``(1,N)``.
135
+
136
+ Examples
137
+ --------
138
+ >>> import numpy.matlib
139
+ >>> np.matlib.zeros((2, 3))
140
+ matrix([[0., 0., 0.],
141
+ [0., 0., 0.]])
142
+
143
+ >>> np.matlib.zeros(2)
144
+ matrix([[0., 0.]])
145
+
146
+ """
147
+ a = ndarray.__new__(matrix, shape, dtype, order=order)
148
+ a.fill(0)
149
+ return a
150
+
151
+ def identity(n,dtype=None):
152
+ """
153
+ Returns the square identity matrix of given size.
154
+
155
+ Parameters
156
+ ----------
157
+ n : int
158
+ Size of the returned identity matrix.
159
+ dtype : data-type, optional
160
+ Data-type of the output. Defaults to ``float``.
161
+
162
+ Returns
163
+ -------
164
+ out : matrix
165
+ `n` x `n` matrix with its main diagonal set to one,
166
+ and all other elements zero.
167
+
168
+ See Also
169
+ --------
170
+ numpy.identity : Equivalent array function.
171
+ matlib.eye : More general matrix identity function.
172
+
173
+ Examples
174
+ --------
175
+ >>> import numpy.matlib
176
+ >>> np.matlib.identity(3, dtype=int)
177
+ matrix([[1, 0, 0],
178
+ [0, 1, 0],
179
+ [0, 0, 1]])
180
+
181
+ """
182
+ a = array([1]+n*[0], dtype=dtype)
183
+ b = empty((n, n), dtype=dtype)
184
+ b.flat = a
185
+ return b
186
+
187
+ def eye(n,M=None, k=0, dtype=float, order='C'):
188
+ """
189
+ Return a matrix with ones on the diagonal and zeros elsewhere.
190
+
191
+ Parameters
192
+ ----------
193
+ n : int
194
+ Number of rows in the output.
195
+ M : int, optional
196
+ Number of columns in the output, defaults to `n`.
197
+ k : int, optional
198
+ Index of the diagonal: 0 refers to the main diagonal,
199
+ a positive value refers to an upper diagonal,
200
+ and a negative value to a lower diagonal.
201
+ dtype : dtype, optional
202
+ Data-type of the returned matrix.
203
+ order : {'C', 'F'}, optional
204
+ Whether the output should be stored in row-major (C-style) or
205
+ column-major (Fortran-style) order in memory.
206
+
207
+ .. versionadded:: 1.14.0
208
+
209
+ Returns
210
+ -------
211
+ I : matrix
212
+ A `n` x `M` matrix where all elements are equal to zero,
213
+ except for the `k`-th diagonal, whose values are equal to one.
214
+
215
+ See Also
216
+ --------
217
+ numpy.eye : Equivalent array function.
218
+ identity : Square identity matrix.
219
+
220
+ Examples
221
+ --------
222
+ >>> import numpy.matlib
223
+ >>> np.matlib.eye(3, k=1, dtype=float)
224
+ matrix([[0., 1., 0.],
225
+ [0., 0., 1.],
226
+ [0., 0., 0.]])
227
+
228
+ """
229
+ return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
230
+
231
+ def rand(*args):
232
+ """
233
+ Return a matrix of random values with given shape.
234
+
235
+ Create a matrix of the given shape and propagate it with
236
+ random samples from a uniform distribution over ``[0, 1)``.
237
+
238
+ Parameters
239
+ ----------
240
+ \\*args : Arguments
241
+ Shape of the output.
242
+ If given as N integers, each integer specifies the size of one
243
+ dimension.
244
+ If given as a tuple, this tuple gives the complete shape.
245
+
246
+ Returns
247
+ -------
248
+ out : ndarray
249
+ The matrix of random values with shape given by `\\*args`.
250
+
251
+ See Also
252
+ --------
253
+ randn, numpy.random.RandomState.rand
254
+
255
+ Examples
256
+ --------
257
+ >>> np.random.seed(123)
258
+ >>> import numpy.matlib
259
+ >>> np.matlib.rand(2, 3)
260
+ matrix([[0.69646919, 0.28613933, 0.22685145],
261
+ [0.55131477, 0.71946897, 0.42310646]])
262
+ >>> np.matlib.rand((2, 3))
263
+ matrix([[0.9807642 , 0.68482974, 0.4809319 ],
264
+ [0.39211752, 0.34317802, 0.72904971]])
265
+
266
+ If the first argument is a tuple, other arguments are ignored:
267
+
268
+ >>> np.matlib.rand((2, 3), 4)
269
+ matrix([[0.43857224, 0.0596779 , 0.39804426],
270
+ [0.73799541, 0.18249173, 0.17545176]])
271
+
272
+ """
273
+ if isinstance(args[0], tuple):
274
+ args = args[0]
275
+ return asmatrix(np.random.rand(*args))
276
+
277
+ def randn(*args):
278
+ """
279
+ Return a random matrix with data from the "standard normal" distribution.
280
+
281
+ `randn` generates a matrix filled with random floats sampled from a
282
+ univariate "normal" (Gaussian) distribution of mean 0 and variance 1.
283
+
284
+ Parameters
285
+ ----------
286
+ \\*args : Arguments
287
+ Shape of the output.
288
+ If given as N integers, each integer specifies the size of one
289
+ dimension. If given as a tuple, this tuple gives the complete shape.
290
+
291
+ Returns
292
+ -------
293
+ Z : matrix of floats
294
+ A matrix of floating-point samples drawn from the standard normal
295
+ distribution.
296
+
297
+ See Also
298
+ --------
299
+ rand, numpy.random.RandomState.randn
300
+
301
+ Notes
302
+ -----
303
+ For random samples from the normal distribution with mean ``mu`` and
304
+ standard deviation ``sigma``, use::
305
+
306
+ sigma * np.matlib.randn(...) + mu
307
+
308
+ Examples
309
+ --------
310
+ >>> np.random.seed(123)
311
+ >>> import numpy.matlib
312
+ >>> np.matlib.randn(1)
313
+ matrix([[-1.0856306]])
314
+ >>> np.matlib.randn(1, 2, 3)
315
+ matrix([[ 0.99734545, 0.2829785 , -1.50629471],
316
+ [-0.57860025, 1.65143654, -2.42667924]])
317
+
318
+ Two-by-four matrix of samples from the normal distribution with
319
+ mean 3 and standard deviation 2.5:
320
+
321
+ >>> 2.5 * np.matlib.randn((2, 4)) + 3
322
+ matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462],
323
+ [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]])
324
+
325
+ """
326
+ if isinstance(args[0], tuple):
327
+ args = args[0]
328
+ return asmatrix(np.random.randn(*args))
329
+
330
+ def repmat(a, m, n):
331
+ """
332
+ Repeat a 0-D to 2-D array or matrix MxN times.
333
+
334
+ Parameters
335
+ ----------
336
+ a : array_like
337
+ The array or matrix to be repeated.
338
+ m, n : int
339
+ The number of times `a` is repeated along the first and second axes.
340
+
341
+ Returns
342
+ -------
343
+ out : ndarray
344
+ The result of repeating `a`.
345
+
346
+ Examples
347
+ --------
348
+ >>> import numpy.matlib
349
+ >>> a0 = np.array(1)
350
+ >>> np.matlib.repmat(a0, 2, 3)
351
+ array([[1, 1, 1],
352
+ [1, 1, 1]])
353
+
354
+ >>> a1 = np.arange(4)
355
+ >>> np.matlib.repmat(a1, 2, 2)
356
+ array([[0, 1, 2, 3, 0, 1, 2, 3],
357
+ [0, 1, 2, 3, 0, 1, 2, 3]])
358
+
359
+ >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3))
360
+ >>> np.matlib.repmat(a2, 2, 3)
361
+ matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2],
362
+ [3, 4, 5, 3, 4, 5, 3, 4, 5],
363
+ [0, 1, 2, 0, 1, 2, 0, 1, 2],
364
+ [3, 4, 5, 3, 4, 5, 3, 4, 5]])
365
+
366
+ """
367
+ a = asanyarray(a)
368
+ ndim = a.ndim
369
+ if ndim == 0:
370
+ origrows, origcols = (1, 1)
371
+ elif ndim == 1:
372
+ origrows, origcols = (1, a.shape[0])
373
+ else:
374
+ origrows, origcols = a.shape
375
+ rows = origrows * m
376
+ cols = origcols * n
377
+ c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0)
378
+ return c.reshape(rows, cols)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/__init__.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_torch_greater_or_equal
17
+
18
+
19
+ _import_structure = {
20
+ "aqlm": ["replace_with_aqlm_linear"],
21
+ "awq": [
22
+ "post_init_awq_exllama_modules",
23
+ "replace_quantization_scales",
24
+ "replace_with_awq_linear",
25
+ ],
26
+ "bitnet": [
27
+ "BitLinear",
28
+ "pack_weights",
29
+ "replace_with_bitnet_linear",
30
+ "unpack_weights",
31
+ ],
32
+ "bitsandbytes": [
33
+ "Bnb4bitQuantize",
34
+ "dequantize_and_replace",
35
+ "replace_with_bnb_linear",
36
+ "validate_bnb_backend_availability",
37
+ ],
38
+ "deepspeed": [
39
+ "HfDeepSpeedConfig",
40
+ "HfTrainerDeepSpeedConfig",
41
+ "deepspeed_config",
42
+ "deepspeed_init",
43
+ "deepspeed_load_checkpoint",
44
+ "deepspeed_optim_sched",
45
+ "is_deepspeed_available",
46
+ "is_deepspeed_zero3_enabled",
47
+ "set_hf_deepspeed_config",
48
+ "unset_hf_deepspeed_config",
49
+ ],
50
+ "eetq": ["replace_with_eetq_linear"],
51
+ "fbgemm_fp8": ["FbgemmFp8Linear", "FbgemmFp8Llama4TextExperts", "replace_with_fbgemm_fp8_linear"],
52
+ "finegrained_fp8": ["FP8Linear", "replace_with_fp8_linear"],
53
+ "fsdp": ["is_fsdp_enabled", "is_fsdp_managed_module"],
54
+ "ggml": [
55
+ "GGUF_CONFIG_DEFAULTS_MAPPING",
56
+ "GGUF_CONFIG_MAPPING",
57
+ "GGUF_TOKENIZER_MAPPING",
58
+ "_gguf_parse_value",
59
+ "load_dequant_gguf_tensor",
60
+ "load_gguf",
61
+ ],
62
+ "higgs": [
63
+ "HiggsLinear",
64
+ "dequantize_higgs",
65
+ "quantize_with_higgs",
66
+ "replace_with_higgs_linear",
67
+ ],
68
+ "hqq": ["prepare_for_hqq_linear"],
69
+ "hub_kernels": [
70
+ "LayerRepository",
71
+ "lazy_load_kernel",
72
+ "register_kernel_mapping",
73
+ "replace_kernel_forward_from_hub",
74
+ "use_kernel_forward_from_hub",
75
+ "use_kernel_func_from_hub",
76
+ "use_kernelized_func",
77
+ ],
78
+ "integration_utils": [
79
+ "INTEGRATION_TO_CALLBACK",
80
+ "AzureMLCallback",
81
+ "ClearMLCallback",
82
+ "CodeCarbonCallback",
83
+ "CometCallback",
84
+ "DagsHubCallback",
85
+ "DVCLiveCallback",
86
+ "FlyteCallback",
87
+ "KubeflowCallback",
88
+ "MLflowCallback",
89
+ "NeptuneCallback",
90
+ "NeptuneMissingConfiguration",
91
+ "SwanLabCallback",
92
+ "TensorBoardCallback",
93
+ "TrackioCallback",
94
+ "WandbCallback",
95
+ "get_available_reporting_integrations",
96
+ "get_reporting_integration_callbacks",
97
+ "hp_params",
98
+ "is_azureml_available",
99
+ "is_clearml_available",
100
+ "is_codecarbon_available",
101
+ "is_comet_available",
102
+ "is_dagshub_available",
103
+ "is_dvclive_available",
104
+ "is_flyte_deck_standard_available",
105
+ "is_flytekit_available",
106
+ "is_kubeflow_available",
107
+ "is_mlflow_available",
108
+ "is_neptune_available",
109
+ "is_optuna_available",
110
+ "is_ray_available",
111
+ "is_ray_tune_available",
112
+ "is_swanlab_available",
113
+ "is_tensorboard_available",
114
+ "is_trackio_available",
115
+ "is_wandb_available",
116
+ "rewrite_logs",
117
+ "run_hp_search_optuna",
118
+ "run_hp_search_ray",
119
+ "run_hp_search_wandb",
120
+ ],
121
+ "liger": ["apply_liger_kernel"],
122
+ "metal_quantization": [
123
+ "MetalLinear",
124
+ "replace_with_metal_linear",
125
+ ],
126
+ "moe": [
127
+ "batched_mm_experts_forward",
128
+ "grouped_mm_experts_forward",
129
+ "use_experts_implementation",
130
+ ],
131
+ "mxfp4": [
132
+ "Mxfp4GptOssExperts",
133
+ "convert_moe_packed_tensors",
134
+ "dequantize",
135
+ "load_and_swizzle_mxfp4",
136
+ "quantize_to_mxfp4",
137
+ "replace_with_mxfp4_linear",
138
+ "swizzle_mxfp4",
139
+ ],
140
+ "neftune": [
141
+ "activate_neftune",
142
+ "deactivate_neftune",
143
+ "neftune_post_forward_hook",
144
+ ],
145
+ "peft": ["PeftAdapterMixin"],
146
+ "quanto": ["replace_with_quanto_layers"],
147
+ "sinq": ["SinqDeserialize", "SinqQuantize"],
148
+ "spqr": ["replace_with_spqr_linear"],
149
+ "vptq": ["replace_with_vptq_linear"],
150
+ }
151
+
152
+ try:
153
+ if not is_torch_available():
154
+ raise OptionalDependencyNotAvailable()
155
+ except OptionalDependencyNotAvailable:
156
+ pass
157
+ else:
158
+ _import_structure["executorch"] = [
159
+ "TorchExportableModuleWithStaticCache",
160
+ "convert_and_export_with_cache",
161
+ ]
162
+
163
+ _import_structure["tensor_parallel"] = [
164
+ "shard_and_distribute_module",
165
+ "ALL_PARALLEL_STYLES",
166
+ "translate_to_torch_parallel_style",
167
+ ]
168
+ try:
169
+ if not is_torch_greater_or_equal("2.5"):
170
+ raise OptionalDependencyNotAvailable()
171
+ except OptionalDependencyNotAvailable:
172
+ pass
173
+ else:
174
+ _import_structure["flex_attention"] = [
175
+ "make_flex_block_causal_mask",
176
+ ]
177
+
178
+ if TYPE_CHECKING:
179
+ from .aqlm import replace_with_aqlm_linear
180
+ from .awq import (
181
+ post_init_awq_exllama_modules,
182
+ replace_quantization_scales,
183
+ replace_with_awq_linear,
184
+ )
185
+ from .bitnet import (
186
+ BitLinear,
187
+ pack_weights,
188
+ replace_with_bitnet_linear,
189
+ unpack_weights,
190
+ )
191
+ from .bitsandbytes import (
192
+ Bnb4bitQuantize,
193
+ dequantize_and_replace,
194
+ replace_with_bnb_linear,
195
+ validate_bnb_backend_availability,
196
+ )
197
+ from .deepspeed import (
198
+ HfDeepSpeedConfig,
199
+ HfTrainerDeepSpeedConfig,
200
+ deepspeed_config,
201
+ deepspeed_init,
202
+ deepspeed_load_checkpoint,
203
+ deepspeed_optim_sched,
204
+ is_deepspeed_available,
205
+ is_deepspeed_zero3_enabled,
206
+ set_hf_deepspeed_config,
207
+ unset_hf_deepspeed_config,
208
+ )
209
+ from .eetq import replace_with_eetq_linear
210
+ from .fbgemm_fp8 import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts, replace_with_fbgemm_fp8_linear
211
+ from .finegrained_fp8 import FP8Linear, replace_with_fp8_linear
212
+ from .fsdp import is_fsdp_enabled, is_fsdp_managed_module
213
+ from .ggml import (
214
+ GGUF_CONFIG_DEFAULTS_MAPPING,
215
+ GGUF_CONFIG_MAPPING,
216
+ GGUF_TOKENIZER_MAPPING,
217
+ _gguf_parse_value,
218
+ load_dequant_gguf_tensor,
219
+ load_gguf,
220
+ )
221
+ from .higgs import HiggsLinear, dequantize_higgs, quantize_with_higgs, replace_with_higgs_linear
222
+ from .hqq import prepare_for_hqq_linear
223
+ from .hub_kernels import (
224
+ LayerRepository,
225
+ lazy_load_kernel,
226
+ register_kernel_mapping,
227
+ replace_kernel_forward_from_hub,
228
+ use_kernel_forward_from_hub,
229
+ use_kernel_func_from_hub,
230
+ use_kernelized_func,
231
+ )
232
+ from .integration_utils import (
233
+ INTEGRATION_TO_CALLBACK,
234
+ AzureMLCallback,
235
+ ClearMLCallback,
236
+ CodeCarbonCallback,
237
+ CometCallback,
238
+ DagsHubCallback,
239
+ DVCLiveCallback,
240
+ FlyteCallback,
241
+ KubeflowCallback,
242
+ MLflowCallback,
243
+ NeptuneCallback,
244
+ NeptuneMissingConfiguration,
245
+ SwanLabCallback,
246
+ TensorBoardCallback,
247
+ TrackioCallback,
248
+ WandbCallback,
249
+ get_available_reporting_integrations,
250
+ get_reporting_integration_callbacks,
251
+ hp_params,
252
+ is_azureml_available,
253
+ is_clearml_available,
254
+ is_codecarbon_available,
255
+ is_comet_available,
256
+ is_dagshub_available,
257
+ is_dvclive_available,
258
+ is_flyte_deck_standard_available,
259
+ is_flytekit_available,
260
+ is_kubeflow_available,
261
+ is_mlflow_available,
262
+ is_neptune_available,
263
+ is_optuna_available,
264
+ is_ray_available,
265
+ is_ray_tune_available,
266
+ is_swanlab_available,
267
+ is_tensorboard_available,
268
+ is_trackio_available,
269
+ is_wandb_available,
270
+ rewrite_logs,
271
+ run_hp_search_optuna,
272
+ run_hp_search_ray,
273
+ run_hp_search_wandb,
274
+ )
275
+ from .liger import apply_liger_kernel
276
+ from .metal_quantization import (
277
+ MetalLinear,
278
+ replace_with_metal_linear,
279
+ )
280
+ from .moe import (
281
+ batched_mm_experts_forward,
282
+ grouped_mm_experts_forward,
283
+ use_experts_implementation,
284
+ )
285
+ from .mxfp4 import (
286
+ Mxfp4GptOssExperts,
287
+ dequantize,
288
+ load_and_swizzle_mxfp4,
289
+ quantize_to_mxfp4,
290
+ replace_with_mxfp4_linear,
291
+ swizzle_mxfp4,
292
+ )
293
+ from .neftune import activate_neftune, deactivate_neftune, neftune_post_forward_hook
294
+ from .peft import PeftAdapterMixin
295
+ from .quanto import replace_with_quanto_layers
296
+ from .sinq import SinqDeserialize, SinqQuantize
297
+ from .spqr import replace_with_spqr_linear
298
+ from .vptq import replace_with_vptq_linear
299
+
300
+ try:
301
+ if not is_torch_available():
302
+ raise OptionalDependencyNotAvailable()
303
+ except OptionalDependencyNotAvailable:
304
+ pass
305
+ else:
306
+ from .executorch import TorchExportableModuleWithStaticCache, convert_and_export_with_cache
307
+
308
+ from .tensor_parallel import (
309
+ ALL_PARALLEL_STYLES,
310
+ shard_and_distribute_module,
311
+ translate_to_torch_parallel_style,
312
+ )
313
+
314
+ try:
315
+ if not is_torch_greater_or_equal("2.5"):
316
+ raise OptionalDependencyNotAvailable()
317
+ except OptionalDependencyNotAvailable:
318
+ pass
319
+ else:
320
+ from .flex_attention import make_flex_block_causal_mask
321
+ else:
322
+ import sys
323
+
324
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/awq.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ "AWQ (Activation aware Weight Quantization) integration file"
15
+
16
+ from ..quantizers.quantizers_utils import should_convert_module
17
+ from ..utils import is_torch_available, logging
18
+
19
+
20
+ if is_torch_available():
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ AWQ_SCALES_MAPPINGS = {
28
+ "starcoder2": {"act": "act", "layer_before_act": "c_fc"},
29
+ "RefinedWebModel": {"act": "act", "layer_before_act": "dense_h_to_4h"},
30
+ "falcon": {"act": "act", "layer_before_act": "dense_h_to_4h"},
31
+ "mpt": {"act": "act", "layer_before_act": "up_proj"},
32
+ "gptj": {"act": "act", "layer_before_act": "fc_in"},
33
+ "gpt_neox": {"act": "act", "layer_before_act": "dense_h_to_4h"},
34
+ "gpt_bigcode": {"act": "act", "layer_before_act": "c_fc"},
35
+ "bloom": {"act": "gelu_impl", "layer_before_act": "dense_h_to_4h"},
36
+ }
37
+
38
+
39
+ def replace_quantization_scales(model, model_type):
40
+ from gptqmodel.quantization.awq.modules.act import ScaledActivation
41
+
42
+ if model_type not in AWQ_SCALES_MAPPINGS:
43
+ return model
44
+ for name, module in model.named_children():
45
+ act_name = AWQ_SCALES_MAPPINGS[model_type]["act"]
46
+ layer_before_act_name = AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"]
47
+ if name == act_name and hasattr(model, layer_before_act_name):
48
+ layer_before_act = getattr(model, AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"])
49
+ size = layer_before_act.out_features
50
+ scale_like = torch.ones(size)
51
+ model._modules[name] = ScaledActivation(module, scale_like)
52
+ _ = replace_quantization_scales(module, model_type)
53
+ return model
54
+
55
+
56
+ def replace_with_awq_linear(
57
+ model,
58
+ modules_to_not_convert=None,
59
+ quantization_config=None,
60
+ device_map: str | dict | None = None,
61
+ ) -> bool:
62
+ """
63
+ Public method that replaces the linear layers of the given model with awq quantized layers.
64
+
65
+ Args:
66
+ model (`torch.nn.Module`):
67
+ The model to convert, can be any `torch.nn.Module` instance.
68
+ quantization_config (`AwqConfig`):
69
+ The quantization config object that contains the quantization parameters.
70
+ modules_to_not_convert (`list[str]`, *optional*, defaults to `None`):
71
+ A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
72
+ converted.
73
+ device_map (`Union[str, dict]`, *optional*, defaults to `None`):
74
+ The device map that maps the parameters to the device
75
+ """
76
+ from gptqmodel.quantization import METHOD
77
+ from gptqmodel.utils.importer import hf_select_quant_linear_v2
78
+
79
+ target_cls = hf_select_quant_linear_v2(
80
+ bits=quantization_config.bits,
81
+ group_size=quantization_config.group_size,
82
+ desc_act=False,
83
+ sym=False,
84
+ format=quantization_config.format,
85
+ backend=quantization_config.backend,
86
+ device_map=device_map,
87
+ quant_method=METHOD.AWQ,
88
+ zero_point=quantization_config.zero_point,
89
+ pack=False,
90
+ )
91
+
92
+ for module_name, module in model.named_modules():
93
+ if not should_convert_module(module_name, modules_to_not_convert):
94
+ continue
95
+ with torch.device("meta"):
96
+ if isinstance(module, nn.Linear):
97
+ new_module = target_cls(
98
+ bits=quantization_config.bits,
99
+ sym=quantization_config.sym,
100
+ desc_act=quantization_config.desc_act,
101
+ group_size=quantization_config.group_size,
102
+ in_features=module.in_features,
103
+ out_features=module.out_features,
104
+ bias=module.bias is not None,
105
+ dev=module.weight.device,
106
+ register_buffers=True,
107
+ )
108
+ new_module.requires_grad_(False)
109
+ model.set_submodule(module_name, new_module)
110
+ has_been_replaced = True
111
+
112
+ if not has_been_replaced:
113
+ logger.warning(
114
+ "You are loading your model using eetq but no linear modules were found in your model."
115
+ " Please double check your model architecture, or submit an issue on github if you think this is"
116
+ " a bug."
117
+ )
118
+
119
+ return model
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/executorch.py ADDED
@@ -0,0 +1,1137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5
+ # the License. You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10
+ # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11
+ # specific language governing permissions and limitations under the License.
12
+
13
+ import logging
14
+
15
+ import torch
16
+
17
+ from ..cache_utils import (
18
+ DynamicCache,
19
+ DynamicLayer,
20
+ DynamicSlidingWindowLayer,
21
+ EncoderDecoderCache,
22
+ StaticCache,
23
+ StaticLayer,
24
+ StaticSlidingWindowLayer,
25
+ )
26
+ from ..generation.configuration_utils import GenerationConfig
27
+ from ..modeling_utils import PreTrainedModel
28
+ from ..pytorch_utils import (
29
+ is_torch_greater_or_equal,
30
+ is_torch_greater_or_equal_than_2_6,
31
+ )
32
+
33
+
34
+ class TorchExportableModuleForVLM:
35
+ """
36
+ A wrapper class for exporting Vision-Language Models (VLMs) like SmolVLM2 for ExecuTorch.
37
+
38
+ This class handles the export of three main components:
39
+ 1. Vision encoder (processes images to visual features)
40
+ 2. Connector/projector (maps visual features to text embedding space)
41
+ 3. Text decoder (generates text from combined visual and text tokens)
42
+ """
43
+
44
+ def __init__(self, model, max_batch_size: int = 1, max_cache_len: int = 1024):
45
+ """
46
+ Initialize the exportable VLM module.
47
+
48
+ Args:
49
+ model: The VLM (e.g. SmolVLM) model instance
50
+ max_batch_size: Maximum batch size. Always 1 for ExecuTorch
51
+ max_cache_len: Maximum cache length for text generation
52
+ """
53
+ self.model = model
54
+ self.max_batch_size = max_batch_size
55
+ self.max_cache_len = max_cache_len
56
+ self.config = model.config
57
+
58
+ # Extract individual components
59
+ self.vision_encoder = model.model.vision_model
60
+ self.connector = model.model.connector
61
+ self.text_decoder = model.model.text_model
62
+
63
+ # Store exported programs
64
+ self.exported_vision_encoder = None
65
+ self.exported_connector = None
66
+ self.exported_text_decoder = None
67
+
68
+ def export_vision_encoder(self):
69
+ """Export the vision encoder component."""
70
+ self.vision_encoder.eval()
71
+
72
+ # Create example input
73
+ pixel_values = torch.randn(1, 3, 384, 384, dtype=torch.float32)
74
+
75
+ # Define dynamic shapes
76
+ dynamic_shapes = {
77
+ "pixel_values": {
78
+ 2: torch.export.Dim.AUTO,
79
+ 3: torch.export.Dim.AUTO,
80
+ }
81
+ }
82
+
83
+ self.exported_vision_encoder = torch.export.export(
84
+ self.vision_encoder,
85
+ args=(pixel_values,),
86
+ dynamic_shapes=dynamic_shapes,
87
+ strict=False,
88
+ )
89
+
90
+ return self.exported_vision_encoder
91
+
92
+ def export_connector(self):
93
+ """Export the connector component."""
94
+ self.connector.eval()
95
+
96
+ # Vision encoder output shape: [batch_size, num_patches, vision_hidden_size]
97
+ vision_hidden_size = self.config.vision_config.hidden_size
98
+ image_size = self.config.vision_config.image_size
99
+ patch_size = self.config.vision_config.patch_size
100
+ patches_per_dim = image_size // patch_size
101
+ num_patches = patches_per_dim * patches_per_dim
102
+ image_hidden_states = torch.randn(1, num_patches, vision_hidden_size, dtype=torch.float32)
103
+
104
+ # Define dynamic shapes - static batch_size=1, dynamic num_patches
105
+ dynamic_shapes = {"image_hidden_states": {1: torch.export.Dim.AUTO}}
106
+
107
+ # Export the connector using torch.export
108
+ self.exported_connector = torch.export.export(
109
+ self.connector,
110
+ args=(image_hidden_states,),
111
+ dynamic_shapes=dynamic_shapes,
112
+ strict=False,
113
+ )
114
+
115
+ return self.exported_connector
116
+
117
+ def export_text_decoder(self):
118
+ """Export the text decoder component."""
119
+
120
+ # Create text decoder exportable wrapper
121
+ self.exportable_text_decoder = TorchExportableModuleForDecoderOnlyLM(model=self.text_decoder)
122
+
123
+ # Use the existing text decoder exportable wrapper
124
+ seq_length = 3
125
+ input_ids = torch.zeros((1, seq_length), dtype=torch.long)
126
+ cache_position = torch.arange(seq_length, dtype=torch.long)
127
+ max_seq_length = min(self.max_cache_len, self.config.text_config.max_position_embeddings)
128
+ seq_len_dim = torch.export.Dim("seq_length_dim", max=max_seq_length - 1)
129
+
130
+ dynamic_shapes = {
131
+ "input_ids": {1: seq_len_dim},
132
+ "cache_position": {0: seq_len_dim},
133
+ }
134
+
135
+ self.exported_text_decoder = self.exportable_text_decoder.export(
136
+ input_ids=input_ids,
137
+ cache_position=cache_position,
138
+ dynamic_shapes=dynamic_shapes,
139
+ strict=False,
140
+ )
141
+
142
+ return self.exported_text_decoder
143
+
144
+ def export(self, **kwargs):
145
+ """Export all components of the VLM model."""
146
+ self.export_vision_encoder(**kwargs)
147
+ self.export_connector(**kwargs)
148
+ self.export_text_decoder(**kwargs)
149
+ return {
150
+ "vision_encoder": self.exported_vision_encoder,
151
+ "connector": self.exported_connector,
152
+ "text_decoder": self.exported_text_decoder,
153
+ }
154
+
155
+ def forward(self, pixel_values, input_ids, cache_position):
156
+ """
157
+ Simplified forward pass for inference with guaranteed non-null input_ids and cache_position.
158
+
159
+ Args:
160
+ pixel_values: Input images [1, channels, height, width] (optional)
161
+ input_ids: Text token IDs [1, seq_len] (required - won't be None)
162
+ cache_position: Cache positions [seq_len] (required - won't be None)
163
+
164
+ Returns:
165
+ Output with logits for text generation
166
+ """
167
+
168
+ def generate(
169
+ self, pixel_values=None, input_ids=None, max_new_tokens=50, do_sample=False, temperature=1.0, **kwargs
170
+ ):
171
+ """
172
+ Simplified generate method with guaranteed non-null input_ids.
173
+
174
+ Args:
175
+ pixel_values: Input images [1, channels, height, width] (optional)
176
+ input_ids: Initial text tokens [1, seq_len] (required - won't be None)
177
+ max_new_tokens: Maximum number of tokens to generate
178
+ do_sample: Whether to use sampling or greedy decoding
179
+ temperature: Temperature for sampling
180
+
181
+ Returns:
182
+ Generated sequences
183
+ """
184
+
185
+
186
+ class TorchExportableModuleForDecoderOnlyLM(torch.nn.Module):
187
+ """
188
+ A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
189
+ specifically for decoder-only LM with cache. This module ensures that the
190
+ exported model is compatible with further lowering and execution in `ExecuTorch`.
191
+ """
192
+
193
+ def __init__(
194
+ self,
195
+ model: PreTrainedModel,
196
+ batch_size: int | None = None,
197
+ max_cache_len: int | None = None,
198
+ device: torch.device | None = None,
199
+ ) -> None:
200
+ """
201
+ Initializes the exportable module.
202
+
203
+ Args:
204
+ model (`PreTrainedModel`): The pretrained model to wrap.
205
+
206
+ Raises:
207
+ ValueError: If the model is configured with a unsupported cache implementation.
208
+ """
209
+ super().__init__()
210
+
211
+ config = model.config.get_text_config()
212
+
213
+ if not hasattr(config, "use_cache") or config.use_cache is False:
214
+ raise ValueError("The model must have caching enabled to be performant.")
215
+
216
+ if hasattr(config, "layer_types") and getattr(config, "sliding_window", None) is not None:
217
+ self.model = TorchExportableModuleWithHybridCache(model, batch_size, max_cache_len, device)
218
+ else:
219
+ # If `layer_types` is not specified explicitly in the config or `sliding_window` is null,
220
+ # there is only 1 type of layers, so export will use `StaticCache` by default.
221
+ logging.info(
222
+ "Using `StaticCache` for export as `layer_types` is not specified or `sliding_window` is `null` in the config."
223
+ )
224
+ self.model = TorchExportableModuleWithStaticCache(model, batch_size, max_cache_len, device)
225
+
226
+ def forward(
227
+ self,
228
+ input_ids: torch.Tensor | None = None,
229
+ inputs_embeds: torch.Tensor | None = None,
230
+ cache_position: torch.Tensor | None = None,
231
+ ) -> torch.Tensor:
232
+ """
233
+ Forward pass of the module, which is compatible with the ExecuTorch llm runner.
234
+
235
+ Args:
236
+ input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
237
+ inputs_embeds (`torch.Tensor`): Tensor representing current input embeddings to the module.
238
+ cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
239
+
240
+ Returns:
241
+ torch.Tensor: Logits output from the model.
242
+ """
243
+ return self.model.forward(input_ids=input_ids, inputs_embeds=inputs_embeds)
244
+
245
+ def export(
246
+ self,
247
+ input_ids: torch.Tensor | None = None,
248
+ inputs_embeds: torch.Tensor | None = None,
249
+ cache_position: torch.Tensor | None = None,
250
+ dynamic_shapes: dict | None = None,
251
+ strict: bool | None = None,
252
+ ) -> torch.export.ExportedProgram:
253
+ """
254
+ Export the wrapped module using `torch.export`.
255
+
256
+ Args:
257
+ input_ids (`Optional[torch.Tensor]`):
258
+ Tensor representing current input token id to the module. Must specify either this or inputs_embeds.
259
+ inputs_embeds (`Optional[torch.Tensor]`):
260
+ Tensor representing current input embeddings to the module. Must specify either this or input_ids.
261
+ cache_position (`Optional[torch.Tensor]`):
262
+ Tensor representing current input position in the cache. If not provided, a default tensor will be used.
263
+ dynamic_shapes (`Optional[dict]`):
264
+ Dynamic shapes to use for export if specified.
265
+ strict(`Optional[bool]`):
266
+ Flag to instruct `torch.export` to use `torchdynamo`.
267
+
268
+ Returns:
269
+ torch.export.ExportedProgram: The exported program that can be used for inference.
270
+
271
+ Examples:
272
+ Export with input_ids:
273
+ ```python
274
+ # Prepare inputs
275
+ input_ids = torch.tensor([[1, 2, 3]], dtype=torch.long, device=model.device)
276
+ cache_position = torch.arange(input_ids.shape[-1], dtype=torch.long, device=model.device)
277
+
278
+ # Export
279
+ exported = exportable_module.export(
280
+ input_ids=input_ids,
281
+ cache_position=cache_position
282
+ )
283
+ ```
284
+
285
+ Export with inputs_embeds:
286
+ ```python
287
+ # Prepare embeddings
288
+ inputs_embeds = torch.randn(1, 3, 768, device=model.device) # batch_size=1, seq_len=3, hidden_size=768
289
+ cache_position = torch.arange(inputs_embeds.shape[1], dtype=torch.long, device=model.device)
290
+
291
+ # Export
292
+ exported = exportable_module.export(
293
+ inputs_embeds=inputs_embeds,
294
+ cache_position=cache_position
295
+ )
296
+ ```
297
+ """
298
+ if not (input_ids is None) ^ (inputs_embeds is None):
299
+ raise ValueError("Need to specify either input_ids or inputs_embeds.")
300
+
301
+ if hasattr(self.model, "base_model_prefix"):
302
+ base = getattr(self.model, self.model.base_model_prefix, self.model)
303
+ model_device = base.device
304
+ elif hasattr(self.model, "model"):
305
+ model_device = self.model.model.device
306
+ else:
307
+ model_device = "cpu"
308
+ logging.warning(
309
+ "TorchExportableModuleForDecoderOnlyLM.export Can't infer device from the model. Set to CPU by default."
310
+ )
311
+
312
+ if input_ids is not None:
313
+ input_kwargs = {
314
+ "input_ids": input_ids,
315
+ "cache_position": cache_position
316
+ if cache_position is not None
317
+ else torch.arange(input_ids.shape[-1], dtype=torch.long, device=model_device),
318
+ }
319
+ else: # inputs_embeds
320
+ input_kwargs = {
321
+ "inputs_embeds": inputs_embeds,
322
+ "cache_position": cache_position
323
+ if cache_position is not None
324
+ else torch.arange(inputs_embeds.shape[1], dtype=torch.long, device=model_device),
325
+ }
326
+
327
+ exported_program = torch.export.export(
328
+ self.model,
329
+ args=(),
330
+ kwargs=input_kwargs,
331
+ dynamic_shapes=dynamic_shapes,
332
+ strict=strict if strict is not None else True,
333
+ )
334
+
335
+ return exported_program
336
+
337
+ @staticmethod
338
+ def generate(
339
+ exported_program: torch.export.ExportedProgram,
340
+ tokenizer,
341
+ prompt: str,
342
+ max_new_tokens: int = 20,
343
+ do_sample: bool = False,
344
+ temperature: float = 1.0,
345
+ top_k: int = 50,
346
+ top_p: float = 1.0,
347
+ device: str = "cpu",
348
+ ) -> str:
349
+ """
350
+ Generate a sequence of tokens using an exported program.
351
+
352
+ Args:
353
+ exported_program (`torch.export.ExportedProgram`): The exported model being used for generate.
354
+ tokenizer: The tokenizer to use.
355
+ prompt (str): The input prompt.
356
+ max_new_tokens (int): Maximum number of new tokens to generate.
357
+ do_sample (bool): Whether to use sampling or greedy decoding.
358
+ temperature (float): The temperature for sampling.
359
+ top_k (int): The number of highest probability tokens to keep for top-k sampling.
360
+ top_p (float): The cumulative probability for nucleus sampling.
361
+ device (str): The device to use.
362
+
363
+ Returns:
364
+ str: The generated text.
365
+ """
366
+ # Get the module from the exported program
367
+ exported_module = exported_program.module()
368
+
369
+ # Tokenize the prompt
370
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
371
+
372
+ # Initialize with the prompt
373
+ generated_ids = input_ids.clone()
374
+
375
+ # Process the prompt tokens first
376
+ curr_position = 0
377
+ for i in range(input_ids.shape[1]):
378
+ # Process one token at a time
379
+ curr_input_ids = input_ids[:, i : i + 1]
380
+ curr_cache_position = torch.tensor([curr_position], dtype=torch.long, device=device)
381
+
382
+ # Forward pass
383
+ _ = exported_module(input_ids=curr_input_ids, cache_position=curr_cache_position)
384
+ curr_position += 1
385
+
386
+ # Generate new tokens
387
+ for _ in range(max_new_tokens):
388
+ # Get the last token as input
389
+ curr_input_ids = generated_ids[:, -1:]
390
+ curr_cache_position = torch.tensor([curr_position], dtype=torch.long, device=device)
391
+
392
+ # Forward pass to get next token logits
393
+ outputs = exported_module(input_ids=curr_input_ids, cache_position=curr_cache_position)
394
+
395
+ # Get the next token ID
396
+ if do_sample:
397
+ # Apply temperature
398
+ if temperature > 0:
399
+ logits = outputs / temperature
400
+ else:
401
+ logits = outputs
402
+
403
+ # Apply top-k filtering
404
+ if top_k > 0:
405
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
406
+ logits[indices_to_remove] = float("-inf")
407
+
408
+ # Apply top-p (nucleus) filtering
409
+ if top_p < 1.0:
410
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
411
+ cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
412
+
413
+ # Remove tokens with cumulative probability above the threshold
414
+ sorted_indices_to_remove = cumulative_probs > top_p
415
+ # Shift the indices to the right to keep also the first token above the threshold
416
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
417
+ sorted_indices_to_remove[..., 0] = 0
418
+
419
+ # Scatter sorted tensors to original indexing
420
+ indices_to_remove = sorted_indices_to_remove.scatter(-1, sorted_indices, sorted_indices_to_remove)
421
+ logits[indices_to_remove] = float("-inf")
422
+
423
+ # Sample from the filtered distribution
424
+ probs = torch.softmax(logits, dim=-1)
425
+ next_token_id = torch.multinomial(probs, num_samples=1)
426
+ else:
427
+ # Greedy decoding
428
+ next_token_id = outputs.argmax(dim=-1, keepdim=True)
429
+
430
+ # Ensure next_token_id has the right shape before concatenation
431
+ if next_token_id.dim() > 2:
432
+ next_token_id = next_token_id.squeeze(-1)
433
+
434
+ # Append to the generated sequence
435
+ generated_ids = torch.cat([generated_ids, next_token_id], dim=-1)
436
+ curr_position += 1
437
+
438
+ # Stop if we generate an EOS token
439
+ if next_token_id.item() == tokenizer.eos_token_id:
440
+ break
441
+
442
+ # Decode the generated text
443
+ return tokenizer.decode(generated_ids[0], skip_special_tokens=True)
444
+
445
+
446
+ def get_head_shapes(config) -> tuple[int | list[int], int | list[int]]:
447
+ """Returns a tuple `(num_heads, head_dim)` containing either 2 ints, or a list of int with the value for each
448
+ layer."""
449
+ # Gemma4 has different head_dim and num_heads depending on layer type
450
+ if hasattr(config, "global_head_dim"):
451
+ head_dim = [
452
+ config.global_head_dim if layer == "full_attention" else config.head_dim
453
+ for layer in config.layer_types[: -config.num_kv_shared_layers]
454
+ ]
455
+ num_heads = [
456
+ config.num_global_key_value_heads
457
+ if layer == "full_attention" and config.attention_k_eq_v
458
+ else config.num_key_value_heads
459
+ for layer in config.layer_types[: -config.num_kv_shared_layers]
460
+ ]
461
+ else:
462
+ head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
463
+ num_heads = getattr(config, "num_key_value_heads", config.num_attention_heads)
464
+
465
+ return num_heads, head_dim
466
+
467
+
468
+ class TorchExportableModuleWithStaticCache(torch.nn.Module):
469
+ """
470
+ A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
471
+ specifically for decoder-only LM to `StaticCache`. This module ensures that the
472
+ exported model is compatible with further lowering and execution in `ExecuTorch`.
473
+
474
+ Note:
475
+ This class is specifically designed to support export process using `torch.export`
476
+ in a way that ensures the model can be further lowered and run efficiently in `ExecuTorch`.
477
+ """
478
+
479
+ def __init__(
480
+ self,
481
+ model: PreTrainedModel,
482
+ batch_size: int | None = None,
483
+ max_cache_len: int | None = None,
484
+ device: torch.device | None = None,
485
+ ) -> None:
486
+ """
487
+ Initializes the wrapper module with the pretrained model.
488
+
489
+ Args:
490
+ model (`PreTrainedModel`): The pretrained model to wrap. The model must have caching
491
+ enabled and use a 'static' caching implementation.
492
+ batch_size (`Optional[int]`): The batch size of the model. If not provided, we check if a value can be found
493
+ in `generation_config.cache_config` and otherwise we raise a ValueError.
494
+ max_cache_len (`Optional[int]`): The maximum cache length for generation. Same mechanism as `batch_size` if
495
+ not provided.
496
+ device (`Optional[torch.device]`): The device to use. If not provided, we check if a value can be found
497
+ in `generation_config.cache_config` and otherwise we use `model.device` (no error is raised).
498
+
499
+ Raises:
500
+ AssertionError: If the pretrained model does not have caching enabled or if it does
501
+ not use a 'static' caching implementation in `model.generation_config`.
502
+ ValueError: If `batch_size` or `max_cache_len` is not provided, either as an argument or in `cache_config`.
503
+ """
504
+ super().__init__()
505
+
506
+ config = model.config.get_text_config()
507
+ generation_config = model.generation_config
508
+
509
+ # Sanity checks
510
+ if generation_config is None:
511
+ raise AssertionError(
512
+ "The model must have a generation config to be exported with static caching. "
513
+ "Please set `generation_config` in `model`."
514
+ )
515
+ if not generation_config.use_cache:
516
+ raise AssertionError(
517
+ "The model must have caching enabled to be exported with static caching. "
518
+ "Please set `generation_config.use_cache=True`."
519
+ )
520
+ if generation_config.cache_implementation != "static":
521
+ raise AssertionError(
522
+ "The model must use a 'static' caching implementation to be exported with static caching. "
523
+ "Please set `generation_config.cache_implementation='static'`."
524
+ )
525
+
526
+ cache_config = {} if generation_config.cache_config is None else generation_config.cache_config
527
+
528
+ # Ensure batch_size and max_cache_len are set
529
+ if batch_size is None:
530
+ batch_size = cache_config.get("batch_size", None)
531
+ if batch_size is None:
532
+ raise ValueError("batch_size must be provided, either as an argument or in cache_config.")
533
+ if max_cache_len is None:
534
+ max_cache_len = cache_config.get("max_cache_len", None)
535
+ if max_cache_len is None:
536
+ raise ValueError("max_cache_len must be provided, either as an argument or in cache_config.")
537
+ # Infer device if not provided
538
+ if device is None:
539
+ device = cache_config.get("device", model.device)
540
+
541
+ # Initialize the static cache
542
+ self.model = model
543
+ self.static_cache = StaticCache(max_cache_len=max_cache_len, config=config)
544
+ # Since StaticSlidingWindow have dynamic control flow that cannot be avoided, we have to replace them here by
545
+ # simple StaticLayer... It means that any generation beyond the window is unfortunately unsupported
546
+ for i, layer in enumerate(self.static_cache.layers):
547
+ if isinstance(layer, StaticSlidingWindowLayer):
548
+ self.static_cache.layers[i] = StaticLayer(max_cache_len)
549
+ num_heads, head_dim = get_head_shapes(config)
550
+ dtype = self.model.dtype
551
+ # We need this call to initialize all the layers (otherwise it's done lazily, which is not exportable)
552
+ self.static_cache.early_initialization(batch_size, num_heads, head_dim, dtype, device)
553
+
554
+ # Register cache buffers to make them exportable
555
+ for i, layer in enumerate(self.static_cache.layers):
556
+ self.register_buffer(f"key_cache_{i}", layer.keys, persistent=False)
557
+ self.register_buffer(f"value_cache_{i}", layer.values, persistent=False)
558
+ self.register_buffer(f"cumulative_length_{i}", layer.cumulative_length, persistent=False)
559
+
560
+ def forward(
561
+ self,
562
+ input_ids: torch.LongTensor | None = None,
563
+ inputs_embeds: torch.Tensor | None = None,
564
+ cache_position: torch.Tensor | None = None,
565
+ ):
566
+ """
567
+ Forward pass of the module, which is compatible with the ExecuTorch runtime.
568
+
569
+ Args:
570
+ input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
571
+ inputs_embeds (`torch.Tensor`): Tensor representing current input embeddings to the module.
572
+ cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
573
+
574
+ Returns:
575
+ torch.Tensor: Logits output from the model.
576
+
577
+ This forward adapter serves two primary purposes:
578
+
579
+ 1. **Making the Model `torch.export`-Compatible**:
580
+ The adapter hides unsupported objects, such as the `Cache`, from the graph inputs and outputs,
581
+ enabling the model to be exportable using `torch.export` without encountering issues.
582
+
583
+ 2. **Ensuring Compatibility with `ExecuTorch` runtime**:
584
+ The adapter matches the model's forward signature with that in `executorch/extension/llm/runner`,
585
+ ensuring that the exported model can be executed in `ExecuTorch` out-of-the-box.
586
+ """
587
+ # Start by resetting static cache (it's needed to be able to run several generations with the same exported program,
588
+ # as otherwise it's mutated in-place indefinitely - we cannot call reset in-between the `generate` as the program was
589
+ # already exported)
590
+ for layer in self.static_cache.layers:
591
+ layer.cumulative_length.copy_(cache_position[0:1])
592
+
593
+ past_key_values = self.static_cache
594
+
595
+ outs = self.model(
596
+ input_ids=input_ids,
597
+ inputs_embeds=inputs_embeds,
598
+ attention_mask=None,
599
+ past_key_values=past_key_values,
600
+ use_cache=True,
601
+ )
602
+ if hasattr(outs, "logits"):
603
+ # Returned outputs is `CausalLMOutputWithPast`
604
+ return outs.logits
605
+ else:
606
+ # Returned the `last_hidden_state` from `BaseModelOutputWithPast`
607
+ return outs.last_hidden_state
608
+
609
+ @staticmethod
610
+ def generate(
611
+ exported_program: torch.export.ExportedProgram,
612
+ prompt_token_ids: torch.Tensor,
613
+ max_new_tokens: int,
614
+ ) -> torch.Tensor:
615
+ """
616
+ Generate a sequence of tokens using an exported program.
617
+
618
+ This util function is designed to test exported models by simulating the generation process.
619
+ It processes the input prompt tokens sequentially (no parallel prefill).
620
+ This generate function is not intended to replace the original `generate` method, and the support
621
+ for leveraging the original `generate` is potentially planned!
622
+
623
+ Args:
624
+ exported_program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
625
+ prompt_token_ids (`torch.Tensor`): Tensor representing the input prompt token IDs.
626
+ max_new_tokens (`int`): Maximum number of new tokens to generate. Note that the total generation
627
+ length is limited by both `max_new_tokens` and the model's cache size.
628
+
629
+ Returns:
630
+ torch.Tensor: A tensor containing the generated sequence of token IDs, including the original prompt tokens.
631
+ """
632
+ device = prompt_token_ids.device
633
+ prompt_token_len = prompt_token_ids.shape[-1]
634
+ max_generation_length = prompt_token_len + max_new_tokens
635
+ for buffer_name, buffer in exported_program.named_buffers():
636
+ if buffer_name.startswith("key_cache"):
637
+ max_cache_len = buffer.shape[2]
638
+ max_generation_length = min(max_generation_length, max_cache_len)
639
+ break
640
+
641
+ response_tokens = []
642
+ for input_pos in range(min(max_generation_length, prompt_token_len)):
643
+ result = exported_program.module().forward(
644
+ input_ids=prompt_token_ids[:, input_pos : input_pos + 1],
645
+ cache_position=torch.tensor([input_pos], dtype=torch.long, device=device),
646
+ )
647
+ response_tokens.append(prompt_token_ids[0][input_pos].item())
648
+
649
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
650
+ response_tokens.append(current_token)
651
+
652
+ while len(response_tokens) < max_generation_length:
653
+ result = exported_program.module().forward(
654
+ input_ids=torch.tensor([[current_token]], dtype=torch.long, device=device),
655
+ cache_position=torch.tensor([len(response_tokens)], dtype=torch.long, device=device),
656
+ )
657
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
658
+ response_tokens.append(current_token)
659
+
660
+ return torch.tensor([response_tokens], dtype=torch.long, device=device)
661
+
662
+
663
+ class TorchExportableModuleWithHybridCache(torch.nn.Module):
664
+ """
665
+ A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
666
+ specifically for decoder-only LM to hybrid `StaticCache`. This module ensures that the
667
+ exported model is compatible with further lowering and execution in `ExecuTorch`.
668
+ """
669
+
670
+ def __init__(
671
+ self,
672
+ model: PreTrainedModel,
673
+ batch_size: int | None = None,
674
+ max_cache_len: int | None = None,
675
+ device: torch.device | None = None,
676
+ ) -> None:
677
+ """
678
+ Initializes the exportable module.
679
+
680
+ Args:
681
+ model (`PreTrainedModel`): The pretrained model to wrap.
682
+ batch_size (`Optional[int]`): The batch size of the model. If not provided, we check if a value can be found
683
+ in `generation_config.cache_config` and otherwise we raise a ValueError.
684
+ max_cache_len (`Optional[int]`): The maximum cache length for generation. Same mechanism as `batch_size` if
685
+ not provided.
686
+ device (`Optional[torch.device]`): The device to use. If not provided, we check if a value can be found
687
+ in `generation_config.cache_config` and otherwise we use `model.device` (no error is raised).
688
+ Raises:
689
+ AssertionError: If the model doesn't have the expected configuration for hybrid StaticCache.
690
+ ValueError: If `batch_size` or `max_cache_len` is not provided, either as an argument or in `cache_config`.
691
+ """
692
+ super().__init__()
693
+ self.model = model
694
+ config = model.config.get_text_config()
695
+ generation_config = model.generation_config
696
+
697
+ # Sanity checks
698
+ if generation_config is None:
699
+ raise AssertionError(
700
+ "The model must have a generation config to be exported with static caching. "
701
+ "Please set `generation_config` in `model`."
702
+ )
703
+ if not config.use_cache:
704
+ raise AssertionError("Model must have caching enabled.")
705
+
706
+ cache_config = {} if generation_config.cache_config is None else generation_config.cache_config
707
+ # Ensure batch_size and max_cache_len are set
708
+ if batch_size is None:
709
+ batch_size = cache_config.get("batch_size", None)
710
+ if batch_size is None:
711
+ raise ValueError("batch_size must be provided, either as an argument or in cache_config.")
712
+ if max_cache_len is None:
713
+ max_cache_len = cache_config.get("max_cache_len", None)
714
+ if max_cache_len is None:
715
+ raise ValueError("max_cache_len must be provided, either as an argument or in cache_config.")
716
+ # Infer device if not provided
717
+ if device is None:
718
+ device = cache_config.get("device", model.device)
719
+
720
+ # Initialize the cache
721
+ self.cache = StaticCache(config=config, max_cache_len=max_cache_len)
722
+ # Since StaticSlidingWindow have dynamic control flow that cannot be avoided, we have to replace them here by
723
+ # simple StaticLayer... It means that any generation beyond the window is unfortunately unsupported
724
+ for i, layer in enumerate(self.cache.layers):
725
+ if isinstance(layer, StaticSlidingWindowLayer):
726
+ self.cache.layers[i] = StaticLayer(max_cache_len)
727
+ num_heads, head_dim = get_head_shapes(config)
728
+ dtype = self.model.dtype
729
+ # We need this call to initialize all the layers (otherwise it's done lazily, which is not exportable)
730
+ self.cache.early_initialization(batch_size, num_heads, head_dim, dtype, device)
731
+
732
+ # Register cache buffers to make them exportable
733
+ for i, layer in enumerate(self.cache.layers):
734
+ self.register_buffer(f"key_cache_{i}", layer.keys, persistent=False)
735
+ self.register_buffer(f"value_cache_{i}", layer.values, persistent=False)
736
+ self.register_buffer(f"cumulative_length_{i}", layer.cumulative_length, persistent=False)
737
+
738
+ def forward(
739
+ self,
740
+ input_ids: torch.LongTensor | None = None,
741
+ inputs_embeds: torch.Tensor | None = None,
742
+ cache_position: torch.Tensor | None = None,
743
+ ) -> torch.Tensor:
744
+ """
745
+ Forward pass of the module, which is compatible with the ExecuTorch llm runner.
746
+
747
+ Args:
748
+ input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
749
+ inputs_embeds (`Optional[torch.Tensor]`): Tensor representing current input embeddings to the module.
750
+ cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
751
+
752
+ Returns:
753
+ torch.Tensor: Logits output from the model.
754
+ """
755
+ # Start by resetting static cache (it's needed to be able to run several generations with the same exported program,
756
+ # as otherwise it's mutated in-place indefinitely - we cannot call reset in-between the `generate` as the program was
757
+ # already exported)
758
+ for layer in self.cache.layers:
759
+ layer.cumulative_length.copy_(cache_position[0:1])
760
+
761
+ # Forward pass with the model
762
+ outputs = self.model(
763
+ input_ids=input_ids,
764
+ inputs_embeds=inputs_embeds,
765
+ attention_mask=None,
766
+ past_key_values=self.cache,
767
+ use_cache=True,
768
+ )
769
+
770
+ # Return only the logits to simplify the export
771
+ return outputs.logits
772
+
773
+
774
+ def convert_and_export_with_cache(
775
+ model: PreTrainedModel,
776
+ example_input_ids: torch.Tensor | None = None,
777
+ example_cache_position: torch.Tensor | None = None,
778
+ dynamic_shapes: dict | None = None,
779
+ strict: bool | None = None,
780
+ ):
781
+ """
782
+ Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`,
783
+ ensuring the exported model is compatible with `ExecuTorch`.
784
+
785
+ Args:
786
+ model (`PreTrainedModel`): The pretrained model to be exported.
787
+ example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`.
788
+ example_cache_position (`Optional[torch.Tensor]`): Example current cache position used by `torch.export`.
789
+ dynamic_shapes(`Optional[dict]`): Dynamic shapes used by `torch.export`.
790
+ strict(`Optional[bool]`): Flag to instruct `torch.export` to use `torchdynamo`.
791
+
792
+ Returns:
793
+ Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
794
+ """
795
+
796
+ import torch.export._trace
797
+
798
+ with torch.no_grad():
799
+ # TODO: The default inputs only work for text models. We need to add support for vision/audio models.
800
+ example_input_ids = (
801
+ example_input_ids
802
+ if example_input_ids is not None
803
+ else torch.tensor([[1]], dtype=torch.long, device=model.device)
804
+ )
805
+ example_cache_position = (
806
+ example_cache_position
807
+ if example_cache_position is not None
808
+ else torch.tensor([0], dtype=torch.long, device=model.device)
809
+ )
810
+
811
+ if is_torch_greater_or_equal("2.6.0"):
812
+ exported_program = torch.export.export(
813
+ TorchExportableModuleWithStaticCache(model),
814
+ args=(),
815
+ kwargs={"input_ids": example_input_ids, "cache_position": example_cache_position},
816
+ dynamic_shapes=dynamic_shapes,
817
+ strict=strict if strict is not None else True,
818
+ )
819
+ else:
820
+ if dynamic_shapes is not None:
821
+ logging.warning(
822
+ "Dynamic shapes spec will be ignored by convert_and_export_with_cache for torch < 2.6.0."
823
+ )
824
+ if strict is not None:
825
+ logging.warning("The strict flag will be ignored by convert_and_export_with_cache for torch < 2.6.0.")
826
+ # We have to keep this path for BC.
827
+ #
828
+ # Due to issue https://github.com/pytorch/pytorch/issues/128394, we need to switch to use an internal
829
+ # export API and pre_dispatch=False. Switch to use the public API once the issue is included in 2.5 release.
830
+ exported_program = torch.export._trace._export(
831
+ TorchExportableModuleWithStaticCache(model),
832
+ args=(),
833
+ kwargs={"input_ids": example_input_ids, "cache_position": example_cache_position},
834
+ pre_dispatch=False,
835
+ strict=True,
836
+ )
837
+ return exported_program
838
+
839
+
840
+ class Seq2SeqLMEncoderExportableModule(torch.nn.Module):
841
+ """
842
+ A wrapper module designed to make a Seq2Seq LM encoder exportable with `torch.export`.
843
+ This module ensures that the exported encoder model is compatible with ExecuTorch.
844
+ """
845
+
846
+ def __init__(self, encoder_model):
847
+ super().__init__()
848
+ self.encoder = encoder_model
849
+
850
+ def forward(self, input_ids):
851
+ return self.encoder(input_ids=input_ids).last_hidden_state
852
+
853
+
854
+ class Seq2SeqLMDecoderExportableModuleWithStaticCache(torch.nn.Module):
855
+ """
856
+ A wrapper module designed to make a Seq2Seq LM decoder exportable with `torch.export`,
857
+ specifically for use with static caching. This module ensures the exported decoder
858
+ is compatible with ExecuTorch.
859
+ """
860
+
861
+ def __init__(self, model, max_static_cache_length, batch_size):
862
+ super().__init__()
863
+
864
+ # Get the decoder component
865
+ self.decoder = model.get_decoder()
866
+ self.lm_head = model.lm_head
867
+ self.config = model.config
868
+
869
+ # Detect the device of the exported models by checking a parameter
870
+ # We'll use the model's device as the target device
871
+ model_device = next(model.parameters()).device
872
+
873
+ # Initialize static cache for decoder and DynamicCache for encoder
874
+ self.static_cache = StaticCache(config=self.config, max_cache_len=max_static_cache_length)
875
+ # Since StaticSlidingWindow have dynamic control flow that cannot be avoided, we have to replace them here by
876
+ # simple StaticLayer... It means that any generation beyond the window is unfortunately unsupported
877
+ for i, layer in enumerate(self.static_cache.layers):
878
+ if isinstance(layer, StaticSlidingWindowLayer):
879
+ self.static_cache.layers[i] = StaticLayer(max_static_cache_length)
880
+ num_heads, head_dim = get_head_shapes(self.config)
881
+ self.static_cache.early_initialization(batch_size, num_heads, head_dim, torch.float32, model_device)
882
+ self.cache = EncoderDecoderCache(self.static_cache, DynamicCache(config=self.config))
883
+
884
+ register_dynamic_cache_export_support()
885
+
886
+ # Register cache buffers to make them exportable
887
+ for i, layer in enumerate(self.static_cache.layers):
888
+ self.register_buffer(f"key_cache_{i}", layer.keys, persistent=False)
889
+ self.register_buffer(f"value_cache_{i}", layer.values, persistent=False)
890
+ self.register_buffer(f"cumulative_length_{i}", layer.cumulative_length, persistent=False)
891
+
892
+ def forward(self, decoder_input_ids, encoder_hidden_states, cache_position):
893
+ # Start by resetting static cache (it's needed to be able to run several generations with the same exported program,
894
+ # as otherwise it's mutated in-place indefinitely - we cannot call reset in-between the `generate` as the program was
895
+ # already exported)
896
+ for layer in self.static_cache.layers:
897
+ layer.cumulative_length.copy_(cache_position[0:1])
898
+
899
+ # Get outputs from decoder
900
+ outputs = self.decoder(
901
+ input_ids=decoder_input_ids,
902
+ encoder_hidden_states=encoder_hidden_states,
903
+ past_key_values=self.cache,
904
+ use_cache=True,
905
+ )
906
+
907
+ # Apply language model head
908
+ lm_logits = self.lm_head(outputs[0])
909
+
910
+ return lm_logits
911
+
912
+
913
+ class Seq2SeqLMExportableModule(torch.nn.Module):
914
+ def __init__(
915
+ self, model, batch_size=1, max_hidden_seq_length=4096, cache_implementation="static", max_cache_length=1024
916
+ ):
917
+ super().__init__()
918
+
919
+ self.full_model = model
920
+ self.encoder = model.get_encoder()
921
+ self.config = model.config
922
+ self.max_hidden_seq_length = max_hidden_seq_length
923
+ self.generation_config = GenerationConfig(
924
+ use_cache=True,
925
+ max_length=max_cache_length,
926
+ cache_implementation=cache_implementation,
927
+ cache_config={
928
+ "batch_size": batch_size,
929
+ "max_cache_len": max_cache_length,
930
+ },
931
+ eos_token_id=model.generation_config.eos_token_id,
932
+ )
933
+ self.exported_encoder = None
934
+ self.exported_decoder = None
935
+
936
+ def _export_encoder(self, encoder_input_ids):
937
+ wrapped_encoder = Seq2SeqLMEncoderExportableModule(self.encoder).to(self.full_model.device).eval()
938
+
939
+ # Define dynamic sequence length for encoder
940
+ seq_len_dim = torch.export.Dim("encoder_seq_length", max=self.max_hidden_seq_length)
941
+
942
+ # Export the encoder
943
+ with torch.no_grad():
944
+ exported_encoder = torch.export.export(
945
+ wrapped_encoder, (encoder_input_ids,), dynamic_shapes={"input_ids": {1: seq_len_dim}}, strict=True
946
+ )
947
+
948
+ return exported_encoder
949
+
950
+ def _export_decoder(self, decoder_input_ids, encoder_hidden_states, cache_position):
951
+ target_device = self.full_model.device
952
+ wrapped_decoder = (
953
+ Seq2SeqLMDecoderExportableModuleWithStaticCache(
954
+ model=self.full_model,
955
+ max_static_cache_length=self.generation_config.cache_config.get("max_cache_len"),
956
+ batch_size=self.generation_config.cache_config.get("batch_size"),
957
+ )
958
+ .to(target_device)
959
+ .eval()
960
+ )
961
+
962
+ # Move input tensors to the same device as the wrapped decoder
963
+ decoder_input_ids = decoder_input_ids.to(target_device)
964
+ encoder_hidden_states = encoder_hidden_states.to(target_device)
965
+ cache_position = cache_position.to(target_device)
966
+
967
+ # Define dynamic dimension for encoder output sequence length
968
+ encoder_seq_len_dim = torch.export.Dim("encoder_hidden_seq_length", max=self.max_hidden_seq_length)
969
+
970
+ # Export the decoder
971
+ with torch.no_grad():
972
+ exported_decoder = torch.export.export(
973
+ wrapped_decoder,
974
+ (decoder_input_ids, encoder_hidden_states, cache_position),
975
+ dynamic_shapes={
976
+ "decoder_input_ids": None,
977
+ "encoder_hidden_states": {1: encoder_seq_len_dim},
978
+ "cache_position": None,
979
+ },
980
+ strict=True,
981
+ )
982
+
983
+ return exported_decoder
984
+
985
+ def export(self, encoder_input_ids=None, decoder_input_ids=None, encoder_hidden_states=None, cache_position=None):
986
+ device = self.full_model.device
987
+ example_encoder_input_ids = (
988
+ encoder_input_ids
989
+ if encoder_input_ids is not None
990
+ else torch.ones((1, 10), dtype=torch.long, device=device)
991
+ )
992
+ example_decoder_input_ids = (
993
+ decoder_input_ids
994
+ if decoder_input_ids is not None
995
+ else torch.tensor([[0]], dtype=torch.long, device=device)
996
+ ) # Start token
997
+ example_cache_position = (
998
+ cache_position if cache_position is not None else torch.tensor([0], dtype=torch.long, device=device)
999
+ )
1000
+ example_encoder_hidden_states = (
1001
+ encoder_hidden_states
1002
+ if encoder_hidden_states is not None
1003
+ else torch.zeros(
1004
+ (self.generation_config.cache_config.get("batch_size"), 10, self.config.d_model),
1005
+ dtype=torch.float32,
1006
+ device=device,
1007
+ )
1008
+ )
1009
+ self.exported_encoder = self._export_encoder(example_encoder_input_ids)
1010
+ self.exported_decoder = self._export_decoder(
1011
+ example_decoder_input_ids, example_encoder_hidden_states, example_cache_position
1012
+ )
1013
+
1014
+ # Return self to allow chaining
1015
+ return self
1016
+
1017
+ def generate(self, prompt_token_ids, max_new_tokens):
1018
+ with torch.no_grad():
1019
+ model_device = self.full_model.device
1020
+
1021
+ # Move input to the model's device if it's on a different device
1022
+ if prompt_token_ids.device != model_device:
1023
+ prompt_token_ids = prompt_token_ids.to(model_device)
1024
+
1025
+ # Run encoder
1026
+ encoder_output = self.exported_encoder.module()(prompt_token_ids)
1027
+
1028
+ # Initialize with start token (0 for T5) on the correct device
1029
+ decoder_input_ids = torch.tensor([[0]], dtype=torch.long, device=model_device)
1030
+ generated_ids = [0]
1031
+
1032
+ # Generate tokens one by one
1033
+ for i in range(max_new_tokens - 1):
1034
+ # Run decoder for next token prediction
1035
+ logits = self.exported_decoder.module()(
1036
+ decoder_input_ids, encoder_output, torch.tensor([i], dtype=torch.long, device=model_device)
1037
+ )
1038
+
1039
+ # Get next token
1040
+ next_token = torch.argmax(logits[:, -1, :], dim=-1).item()
1041
+ generated_ids.append(next_token)
1042
+
1043
+ # Update input for next iteration on the correct device
1044
+ decoder_input_ids = torch.tensor([[next_token]], dtype=torch.long, device=model_device)
1045
+
1046
+ # Check if EOS token
1047
+ if next_token == self.generation_config.eos_token_id:
1048
+ break
1049
+
1050
+ return generated_ids
1051
+
1052
+
1053
+ def export_with_dynamic_cache(
1054
+ model: PreTrainedModel,
1055
+ example_input_ids: torch.Tensor | None = None,
1056
+ example_attention_mask: torch.Tensor | None = None,
1057
+ ):
1058
+ """
1059
+ Export a model with DynamicCache using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`.
1060
+
1061
+ Args:
1062
+ model (`PreTrainedModel`): The pretrained model to be exported.
1063
+ example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`.
1064
+ example_attention_mask (`Optional[torch.Tensor]`): Example attention mask used by `torch.export`.
1065
+
1066
+ Returns:
1067
+ Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
1068
+ """
1069
+
1070
+ register_dynamic_cache_export_support()
1071
+
1072
+ with torch.no_grad():
1073
+ exported_program = torch.export.export(
1074
+ model,
1075
+ (),
1076
+ {
1077
+ "input_ids": example_input_ids,
1078
+ "attention_mask": example_attention_mask,
1079
+ "past_key_values": DynamicCache(config=model.config),
1080
+ "use_cache": True,
1081
+ },
1082
+ strict=False,
1083
+ )
1084
+ return exported_program
1085
+
1086
+
1087
+ def register_dynamic_cache_export_support():
1088
+ """
1089
+ Utilities for `DynamicCache` <> torch.export support
1090
+ """
1091
+
1092
+ try:
1093
+ torch.utils._pytree.register_pytree_node(
1094
+ DynamicCache,
1095
+ lambda dynamic_cache: torch.utils._pytree._dict_flatten(_get_cache_dict(dynamic_cache)),
1096
+ _unflatten_dynamic_cache,
1097
+ serialized_type_name=f"{DynamicCache.__module__}.{DynamicCache.__name__}",
1098
+ flatten_with_keys_fn=lambda dynamic_cache: torch.utils._pytree._dict_flatten_with_keys(
1099
+ _get_cache_dict(dynamic_cache)
1100
+ ),
1101
+ )
1102
+ # TODO (tmanlaibaatar) This won't be needed in torch 2.7.
1103
+ torch.fx._pytree.register_pytree_flatten_spec(
1104
+ DynamicCache,
1105
+ lambda cache, spec: torch.fx._pytree._dict_flatten_spec(_get_cache_dict(cache), spec),
1106
+ )
1107
+ # Catching this in case there are multiple runs for some test runs
1108
+ except ValueError as e:
1109
+ if "already registered as pytree node" not in str(e):
1110
+ raise
1111
+
1112
+
1113
+ def _get_cache_dict(cache: DynamicCache):
1114
+ """Convert cache to dictionary format for pytree operations."""
1115
+ if any(not isinstance(layer, (DynamicLayer, DynamicSlidingWindowLayer)) for layer in cache.layers):
1116
+ raise RuntimeError("This pytree flattening function should only be applied to DynamicCache")
1117
+
1118
+ if not is_torch_greater_or_equal_than_2_6:
1119
+ logging.warning("DynamicCache + torch.export is tested on torch 2.6.0+ and may not work on earlier versions.")
1120
+
1121
+ return {
1122
+ "key_cache": [layer.keys for layer in cache.layers if layer.keys is not None],
1123
+ "value_cache": [layer.values for layer in cache.layers if layer.values is not None],
1124
+ }
1125
+
1126
+
1127
+ def _unflatten_dynamic_cache(values, context: torch.utils._pytree.Context):
1128
+ dictionary = torch.utils._pytree._dict_unflatten(values, context)
1129
+ cache = DynamicCache()
1130
+ # Reconstruct layers from keys and values lists
1131
+ key_list = dictionary.get("key_cache", [])
1132
+ value_list = dictionary.get("value_cache", [])
1133
+ for idx in range(max(len(key_list), len(value_list))):
1134
+ key = key_list[idx] if idx < len(key_list) else None
1135
+ value = value_list[idx] if idx < len(value_list) else None
1136
+ cache.update(key, value, idx)
1137
+ return cache
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/hub_kernels.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import importlib.metadata
15
+ import os
16
+ import re
17
+ from collections.abc import Callable
18
+ from contextlib import contextmanager
19
+ from types import ModuleType
20
+
21
+ from packaging import version as pkg_version
22
+
23
+ from ..utils import ENV_VARS_TRUE_VALUES, logging
24
+ from ..utils.import_utils import is_kernels_available
25
+ from .flash_attention import flash_attention_forward
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ try:
31
+ from kernels import (
32
+ Device,
33
+ LayerRepository,
34
+ Mode,
35
+ register_kernel_mapping,
36
+ replace_kernel_forward_from_hub,
37
+ )
38
+ from kernels import (
39
+ get_kernel as get_kernel_hub,
40
+ )
41
+ from kernels import (
42
+ use_kernel_forward_from_hub as _kernels_use_kernel_forward_from_hub,
43
+ )
44
+
45
+ # Try to import FuncRepository, fallback if not available
46
+ try:
47
+ from kernels import FuncRepository
48
+ except ImportError:
49
+ FuncRepository = None
50
+
51
+ # Try to import use_kernel_func_from_hub, fallback if not available
52
+ try:
53
+ from kernels import use_kernel_func_from_hub as _kernels_use_kernel_func_from_hub
54
+
55
+ _has_use_kernel_func_from_hub = True
56
+ except ImportError:
57
+ _has_use_kernel_func_from_hub = False
58
+
59
+ _TRANSFORMERS_USE_HUB_KERNELS = os.environ.get("USE_HUB_KERNELS", "YES").upper()
60
+ _kernels_available = True
61
+ _kernels_enabled = _TRANSFORMERS_USE_HUB_KERNELS in ENV_VARS_TRUE_VALUES
62
+
63
+ def use_kernel_forward_from_hub(layer_name: str):
64
+ if _kernels_enabled:
65
+ return _kernels_use_kernel_forward_from_hub(layer_name)
66
+ else:
67
+ logger.warning_once(
68
+ f"kernels hub usage is disabled through the environment USE_HUB_KERNELS={_TRANSFORMERS_USE_HUB_KERNELS}"
69
+ )
70
+ return lambda cls: cls
71
+
72
+ def use_kernel_func_from_hub(func_name: str):
73
+ if _kernels_enabled and _has_use_kernel_func_from_hub:
74
+ return _kernels_use_kernel_func_from_hub(func_name)
75
+ else:
76
+ if not _has_use_kernel_func_from_hub:
77
+ logger.warning_once(
78
+ "use_kernel_func_from_hub is not available in the installed kernels version. "
79
+ "Please upgrade kernels to use this feature."
80
+ )
81
+ else:
82
+ logger.warning_once(
83
+ f"kernels hub usage is disabled through the environment USE_HUB_KERNELS={_TRANSFORMERS_USE_HUB_KERNELS}"
84
+ )
85
+ return lambda func: func
86
+
87
+ _KERNEL_MAPPING: dict[str, dict[Device | str, LayerRepository | dict[Mode, LayerRepository]]] = {
88
+ "MultiScaleDeformableAttention": {
89
+ "cuda": LayerRepository(
90
+ repo_id="kernels-community/deformable-detr",
91
+ layer_name="MultiScaleDeformableAttention",
92
+ )
93
+ },
94
+ "Llama4TextMoe": {
95
+ "cuda": LayerRepository(
96
+ repo_id="kernels-community/moe",
97
+ layer_name="Llama4TextMoe",
98
+ )
99
+ },
100
+ "RMSNorm": {
101
+ "cuda": {
102
+ Mode.INFERENCE: LayerRepository(
103
+ repo_id="kernels-community/liger_kernels",
104
+ layer_name="LigerRMSNorm",
105
+ # revision="pure-layer-test",
106
+ ),
107
+ },
108
+ "rocm": {
109
+ Mode.INFERENCE: LayerRepository(
110
+ repo_id="kernels-community/liger_kernels",
111
+ layer_name="LigerRMSNorm",
112
+ )
113
+ },
114
+ "xpu": {
115
+ Mode.INFERENCE: LayerRepository(
116
+ repo_id="kernels-community/rmsnorm",
117
+ layer_name="RMSNorm",
118
+ )
119
+ },
120
+ "mps": {
121
+ Mode.INFERENCE: LayerRepository(
122
+ repo_id="kernels-community/mlx_rmsnorm",
123
+ layer_name="RMSNorm",
124
+ )
125
+ },
126
+ "npu": {
127
+ Mode.INFERENCE: LayerRepository(
128
+ repo_id="kernels-community/liger_kernels",
129
+ layer_name="LigerRMSNorm",
130
+ )
131
+ },
132
+ },
133
+ "MLP": {
134
+ "cuda": LayerRepository(
135
+ repo_id="medmekk/triton-llama-mlp",
136
+ layer_name="TritonLlamaMLP",
137
+ )
138
+ },
139
+ "MegaBlocksMoeMLP": {
140
+ "cuda": {
141
+ Mode.TRAINING: LayerRepository(
142
+ repo_id="kernels-community/megablocks",
143
+ layer_name="MegaBlocksMoeMLP",
144
+ ),
145
+ Mode.INFERENCE: LayerRepository(
146
+ repo_id="kernels-community/megablocks",
147
+ layer_name="MegaBlocksMoeMLP",
148
+ ),
149
+ },
150
+ "rocm": {
151
+ Mode.INFERENCE: LayerRepository(
152
+ repo_id="ahadnagy/megablocks",
153
+ layer_name="MegaBlocksMoeMLP",
154
+ )
155
+ },
156
+ "xpu": {
157
+ Mode.INFERENCE: LayerRepository(
158
+ repo_id="kernels-community/megablocks",
159
+ layer_name="MegaBlocksMoeMLP",
160
+ )
161
+ },
162
+ "cpu": {
163
+ Mode.INFERENCE: LayerRepository(
164
+ repo_id="kernels-community/megablocks",
165
+ layer_name="CPUMegaBlocksMoeMLP",
166
+ )
167
+ },
168
+ },
169
+ "FastGELU": {
170
+ "cuda": {
171
+ Mode.INFERENCE | Mode.TORCH_COMPILE: LayerRepository(
172
+ repo_id="kernels-community/activation",
173
+ layer_name="FastGELU",
174
+ version=1,
175
+ )
176
+ }
177
+ },
178
+ "QuickGELU": {
179
+ "cuda": {
180
+ Mode.INFERENCE | Mode.TORCH_COMPILE: LayerRepository(
181
+ repo_id="kernels-community/activation",
182
+ layer_name="QuickGELU",
183
+ version=1,
184
+ )
185
+ }
186
+ },
187
+ "NewGELU": {
188
+ "cuda": {
189
+ Mode.INFERENCE | Mode.TORCH_COMPILE: LayerRepository(
190
+ repo_id="kernels-community/activation",
191
+ layer_name="NewGELU",
192
+ version=1,
193
+ )
194
+ }
195
+ },
196
+ "SiLU": {
197
+ "cuda": {
198
+ Mode.INFERENCE | Mode.TORCH_COMPILE: LayerRepository(
199
+ repo_id="kernels-community/activation", layer_name="Silu", version=1
200
+ )
201
+ }
202
+ },
203
+ "GeLU": {
204
+ "cuda": {
205
+ Mode.INFERENCE | Mode.TORCH_COMPILE: LayerRepository(
206
+ repo_id="kernels-community/activation", layer_name="Gelu", version=1
207
+ )
208
+ }
209
+ },
210
+ "GeluTanh": {
211
+ "cuda": {
212
+ Mode.INFERENCE | Mode.TORCH_COMPILE: LayerRepository(
213
+ repo_id="kernels-community/activation", layer_name="GeluTanh", version=1
214
+ )
215
+ }
216
+ },
217
+ }
218
+
219
+ # Add function kernel mappings if FuncRepository is available
220
+ if FuncRepository is not None:
221
+ _KERNEL_MAPPING["rotary_pos_emb"] = {
222
+ "xpu": {
223
+ Mode.INFERENCE: FuncRepository(
224
+ repo_id="kernels-community/rotary", func_name="apply_rotary_transformers"
225
+ )
226
+ },
227
+ "cuda": {
228
+ Mode.TRAINING: FuncRepository(
229
+ repo_id="kernels-community/rotary", func_name="apply_rotary_transformers"
230
+ ),
231
+ Mode.INFERENCE: FuncRepository(
232
+ repo_id="kernels-community/rotary", func_name="apply_rotary_transformers"
233
+ ),
234
+ },
235
+ }
236
+
237
+ def has_key(d, key):
238
+ return key in d or any(isinstance(v, dict) and has_key(v, key) for v in d.values())
239
+
240
+ def register_kernel_mapping_transformers(mapping=None):
241
+ if mapping is None:
242
+ mapping = _KERNEL_MAPPING
243
+ if has_key(mapping, "xpu") and not is_kernels_available(MIN_VERSION="0.10.2"):
244
+ raise ImportError(
245
+ "kernels uses an incompatible version. Please install the latest version with `pip install -U kernels`."
246
+ )
247
+ register_kernel_mapping(mapping)
248
+
249
+
250
+ except ImportError:
251
+ _kernels_available = False
252
+ _kernels_enabled = False
253
+
254
+ # Stub to make decorators int transformers work when `kernels`
255
+ # is not installed.
256
+ def use_kernel_forward_from_hub(*args, **kwargs):
257
+ def decorator(cls):
258
+ return cls
259
+
260
+ return decorator
261
+
262
+ def use_kernel_func_from_hub(*args, **kwargs):
263
+ def decorator(func):
264
+ return func
265
+
266
+ return decorator
267
+
268
+ class LayerRepository:
269
+ def __init__(self, *args, **kwargs):
270
+ raise RuntimeError("LayerRepository requires `kernels` to be installed. Run `pip install kernels`.")
271
+
272
+ def replace_kernel_forward_from_hub(*args, **kwargs):
273
+ raise RuntimeError(
274
+ "replace_kernel_forward_from_hub requires `kernels` to be installed. Run `pip install kernels`."
275
+ )
276
+
277
+ def register_kernel_mapping(*args, **kwargs):
278
+ raise RuntimeError("register_kernel_mapping requires `kernels` to be installed. Run `pip install kernels`.")
279
+
280
+ def register_kernel_mapping_transformers(*args, **kwargs):
281
+ raise RuntimeError(
282
+ "register_kernel_mapping_transformers requires `kernels` to be installed. Run `pip install kernels`."
283
+ )
284
+
285
+
286
+ _HUB_KERNEL_MAPPING: dict[str, dict[str, str]] = {
287
+ "causal-conv1d": {"repo_id": "kernels-community/causal-conv1d", "version": 1},
288
+ "mamba-ssm": {"repo_id": "kernels-community/mamba-ssm", "version": 1},
289
+ "falcon_mamba-ssm": {"repo_id": "kernels-community/mamba-ssm", "version": 1},
290
+ "finegrained-fp8": {"repo_id": "kernels-community/finegrained-fp8", "version": 1},
291
+ "deep-gemm": {"repo_id": "kernels-community/deep-gemm", "version": 1},
292
+ "sonic-moe": {"repo_id": "kernels-community/sonic-moe", "revision": "ep-support"},
293
+ }
294
+
295
+ _KERNEL_MODULE_MAPPING: dict[str, ModuleType | None] = {}
296
+
297
+
298
+ def is_kernel(attn_implementation: str | None) -> bool:
299
+ """Check whether `attn_implementation` matches a kernel pattern from the hub."""
300
+ return (
301
+ attn_implementation is not None
302
+ and re.search(r"^[^/:]+/[^/:]+(?:@[^/:]+)?(?::[^/:]+)?$", attn_implementation) is not None
303
+ )
304
+
305
+
306
+ def load_and_register_attn_kernel(
307
+ attn_implementation: str, attention_wrapper: Callable | None = None, allow_all_kernels: bool = False
308
+ ) -> ModuleType | None:
309
+ """
310
+ Load and register the kernel associated to `attn_implementation`.
311
+
312
+ Args:
313
+ attn_implementation: A string, usually a kernel repo like "kernels-community/flash-mla".
314
+ attn_wrapper: a callable for the wrapper around the attention implementation. In `transformers` we
315
+ have a wrapper around the `flash_attn_var_len` call, and the same goes for `sdpa` and `eager`.
316
+ They just prepare the arguments properly. This is mostly used for continious batching, where we
317
+ want the `paged` wrapper, which calls the paged cache.
318
+ allow_all_kernels (`bool`, optional):
319
+ Whether to load kernels from unverified hub repos, if it is a custom kernel outside of the `kernels-community`
320
+ hub repository.
321
+ """
322
+ from ..masking_utils import ALL_MASK_ATTENTION_FUNCTIONS
323
+ from ..modeling_utils import ALL_ATTENTION_FUNCTIONS
324
+
325
+ actual_attn_name = attn_implementation.split("|")[1] if "|" in attn_implementation else attn_implementation
326
+ if not is_kernel(actual_attn_name):
327
+ return None
328
+ if not _kernels_available:
329
+ raise ImportError(
330
+ "`kernels` is either not installed or uses an incompatible version. "
331
+ "Please install the latest version with `pip install -U kernels`."
332
+ )
333
+
334
+ # Extract repo_id and kernel_name from the string
335
+ if ":" in actual_attn_name:
336
+ repo_id, kernel_name = actual_attn_name.split(":")
337
+ kernel_name = kernel_name.strip()
338
+ else:
339
+ repo_id = actual_attn_name
340
+ kernel_name = None
341
+ repo_id = repo_id.strip()
342
+ # extract the rev after the @ if it exists
343
+ repo_id, _, rev = repo_id.partition("@")
344
+ repo_id = repo_id.strip()
345
+ rev = rev.strip() if rev else None
346
+
347
+ # Load the kernel from hub
348
+ try:
349
+ kernel = get_kernel(repo_id, revision=rev, allow_all_kernels=allow_all_kernels)
350
+ except Exception as e:
351
+ raise ValueError(f"An error occurred while trying to load from '{repo_id}': {e}.")
352
+ # correctly wrap the kernel
353
+ if hasattr(kernel, "flash_attn_varlen_func"):
354
+ if attention_wrapper is None:
355
+ attention_wrapper = flash_attention_forward
356
+ kernel_function = attention_wrapper
357
+ elif kernel_name is not None:
358
+ kernel_function = getattr(kernel, kernel_name)
359
+
360
+ # Register the kernel as a valid attention
361
+ ALL_ATTENTION_FUNCTIONS.register(attn_implementation, kernel_function)
362
+ ALL_MASK_ATTENTION_FUNCTIONS.register(attn_implementation, ALL_MASK_ATTENTION_FUNCTIONS["flash_attention_2"])
363
+
364
+ return kernel
365
+
366
+
367
+ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _KERNEL_MODULE_MAPPING):
368
+ if kernel_name in mapping and isinstance(mapping[kernel_name], ModuleType):
369
+ return mapping[kernel_name]
370
+ if kernel_name not in _HUB_KERNEL_MAPPING:
371
+ logger.warning_once(f"Kernel {kernel_name} not found in _HUB_KERNEL_MAPPING")
372
+ mapping[kernel_name] = None
373
+ return None
374
+ if _kernels_available:
375
+ try:
376
+ repo_id = _HUB_KERNEL_MAPPING[kernel_name]["repo_id"]
377
+ revision = _HUB_KERNEL_MAPPING[kernel_name].get("revision", None)
378
+ version = _HUB_KERNEL_MAPPING[kernel_name].get("version", None)
379
+ kernel = get_kernel(repo_id, revision=revision, version=version)
380
+ mapping[kernel_name] = kernel
381
+ except FileNotFoundError as e:
382
+ mapping[kernel_name] = None
383
+ logger.warning_once(f"Failed to load kernel {kernel_name}: {e}")
384
+ except AssertionError:
385
+ # Happens when torch is built without an accelerator backend; fall back to slow path.
386
+ mapping[kernel_name] = None
387
+
388
+ else:
389
+ # Try to import is_{kernel_name}_available from ..utils
390
+ import importlib
391
+
392
+ new_kernel_name = kernel_name.replace("-", "_")
393
+ func_name = f"is_{new_kernel_name}_available"
394
+
395
+ try:
396
+ utils_mod = importlib.import_module("..utils.import_utils", __package__)
397
+ is_kernel_available = getattr(utils_mod, func_name, None)
398
+ except Exception:
399
+ is_kernel_available = None
400
+
401
+ if callable(is_kernel_available) and is_kernel_available():
402
+ # Try to import the module "{kernel_name}" from parent package level
403
+ try:
404
+ module = importlib.import_module(f"{new_kernel_name}")
405
+ mapping[kernel_name] = module
406
+ return module
407
+ except Exception:
408
+ mapping[kernel_name] = None
409
+ else:
410
+ mapping[kernel_name] = None
411
+
412
+ return mapping[kernel_name]
413
+
414
+
415
+ def get_kernel(
416
+ kernel_name: str,
417
+ revision: str | None = None,
418
+ version: int | str | None = None,
419
+ allow_all_kernels: bool = False,
420
+ ) -> ModuleType:
421
+ from .. import __version__
422
+
423
+ if not _kernels_available:
424
+ raise ImportError(
425
+ "`kernels` is either not installed or uses an incompatible version. Please install the latest version "
426
+ "with `pip install -U kernels`."
427
+ )
428
+
429
+ repo_parent = kernel_name.split("/")[0]
430
+ # all `kernels-community` repos are trusted by default!
431
+ if repo_parent != "kernels-community" and not allow_all_kernels:
432
+ raise ValueError(
433
+ "You need to specify `allow_all_kernels=True` to use kernels outside of the `kernels-community` repository"
434
+ )
435
+
436
+ user_agent = {"framework": "transformers", "version": __version__, "repo_id": kernel_name}
437
+ kernels_version = importlib.metadata.version("kernels")
438
+ if pkg_version.parse(kernels_version) >= pkg_version.parse("0.10.4"):
439
+ return get_kernel_hub(kernel_name, revision=revision, version=version, user_agent=user_agent)
440
+ else:
441
+ return get_kernel_hub(kernel_name, revision=revision, version=version)
442
+
443
+
444
+ def use_kernelized_func(module_names: list[Callable] | Callable):
445
+ """
446
+ This decorator attaches the target function within the module as a plain attribute (not as a submodule).
447
+ Keep in mind that this registration is only meant for `kernelize` to recognize its target modules (i.e.
448
+ function exchanged for a weightless `nn.Module` with the same forward) to then exchange to the kernel
449
+ variation (in-place) if the conditions are met.
450
+
451
+ We cache each of these function-based registrations: After proper registration and exchange it is removed
452
+ from the module's `_modules` dict as it does not really act as `nn.Module` but a base function.
453
+ """
454
+ if isinstance(module_names, Callable):
455
+ module_names = [module_names]
456
+
457
+ def decorator(cls):
458
+ orig_init = cls.__init__
459
+
460
+ def new_init(self, *args, **kwargs):
461
+ orig_init(self, *args, **kwargs)
462
+
463
+ # Register new function as non-submodule within the modules dict
464
+ hidden_kernels = self.__dict__.setdefault("_hidden_kernels", {})
465
+ for fn in module_names:
466
+ name = (
467
+ getattr(fn, "__name__", None)
468
+ or getattr(fn, "kernel_layer_name", None)
469
+ or getattr(fn, "func_name", None)
470
+ )
471
+ if name is None:
472
+ raise ValueError(f"Could not infer kernel function name for {fn!r}")
473
+
474
+ # Do not register as submodule! Hide it behind a dict to be removed later after registering it
475
+ hidden_kernels[name] = fn
476
+
477
+ cls.__init__ = new_init
478
+ return cls
479
+
480
+ return decorator
481
+
482
+
483
+ # Whether to allow hub kernels coming from untrusted repos, i.e. repos outside `kernels-community`
484
+ ALLOW_ALL_KERNELS = False
485
+
486
+
487
+ @contextmanager
488
+ def allow_all_hub_kernels():
489
+ """
490
+ Context manager used to adjust the value of the global `ALLOW_HUB_KERNELS`. This is needed, as this argument
491
+ cannot be forwarded directly to the `__init__` of the models, where we set the attention implementation.
492
+ """
493
+ global ALLOW_ALL_KERNELS
494
+
495
+ try:
496
+ ALLOW_ALL_KERNELS = True
497
+
498
+ yield
499
+ finally:
500
+ # Set back the original
501
+ ALLOW_ALL_KERNELS = False
502
+
503
+
504
+ __all__ = [
505
+ "LayerRepository",
506
+ "use_kernel_forward_from_hub",
507
+ "use_kernel_func_from_hub",
508
+ "register_kernel_mapping",
509
+ "register_kernel_mapping_transformers",
510
+ "replace_kernel_forward_from_hub",
511
+ "lazy_load_kernel",
512
+ "get_kernel",
513
+ "use_kernelized_func",
514
+ ] # type: ignore
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/moe.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Callable
17
+ from functools import wraps
18
+
19
+ from ..utils import logging
20
+ from ..utils.generic import GeneralInterface
21
+ from ..utils.import_utils import (
22
+ is_torch_available,
23
+ is_torch_greater_or_equal,
24
+ is_torch_less_or_equal,
25
+ is_torchdynamo_compiling,
26
+ )
27
+ from .sonicmoe import sonicmoe_experts_forward
28
+
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+ # Patch the version-check helpers so dynamo doesn't trace into them — they transitively call
34
+ # `importlib.util.find_spec`, which dynamo refuses to trace. `assume_constant_result` makes
35
+ # dynamo evaluate them once at trace time and inline the bool, no body tracing.
36
+ is_torch_greater_or_equal = torch._dynamo.assume_constant_result(is_torch_greater_or_equal)
37
+ is_torch_less_or_equal = torch._dynamo.assume_constant_result(is_torch_less_or_equal)
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ # Examples of experts class with its eager mm implementation
44
+ # class Experts(torch.nn.Module):
45
+ # """Collection of expert weights stored as 3D tensors."""
46
+
47
+ # def __init__(self, config):
48
+ # super().__init__()
49
+ # self.num_experts = config.n_routed_experts
50
+ # self.hidden_dim = config.hidden_size
51
+ # self.intermediate_dim = config.moe_intermediate_size
52
+ # self.gate_up_proj = torch.nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
53
+ # self.down_proj = torch.nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
54
+ # self.act_fn = ACT2FN[config.hidden_act]
55
+
56
+ # def forward(
57
+ # self,
58
+ # hidden_states: torch.Tensor,
59
+ # top_k_index: torch.Tensor,
60
+ # top_k_weights: torch.Tensor,
61
+ # ) -> torch.Tensor:
62
+ # final_hidden_states = torch.zeros_like(hidden_states)
63
+ # with torch.no_grad():
64
+ # expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
65
+ # expert_mask = expert_mask.permute(2, 1, 0)
66
+ # expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
67
+
68
+ # for expert_idx in expert_hit:
69
+ # expert_idx = expert_idx[0]
70
+ # if expert_idx == self.num_experts:
71
+ # continue
72
+ # top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
73
+ # current_state = hidden_states[token_idx]
74
+ # gate, up = torch.nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
75
+ # current_hidden_states = self.act_fn(gate) * up
76
+ # current_hidden_states = torch.nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
77
+ # current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
78
+ # final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
79
+
80
+ # return final_hidden_states
81
+
82
+
83
+ def _batched_linear(
84
+ input: torch.Tensor,
85
+ weight: torch.Tensor,
86
+ bias: torch.Tensor | None = None,
87
+ is_transposed: bool = False,
88
+ ) -> torch.Tensor:
89
+ """Batched linear layer supporting optional bias and transposed weights.
90
+
91
+ Args:
92
+ input (`torch.Tensor`):
93
+ Input tensor of shape (batch_size, input_dim).
94
+ weight (`torch.Tensor`):
95
+ Weight tensor of shape (batch_size, output_dim, input_dim) if transposed is `False`,
96
+ else of shape (batch_size, input_dim, output_dim).
97
+ bias (`torch.Tensor`, *optional*):
98
+ Bias tensor of shape (batch_size, output_dim). Default is `None`.
99
+ is_transposed (`bool`, *optional*, defaults to `False`):
100
+ Whether the weight tensor is transposed.
101
+ Returns:
102
+ `torch.Tensor`: Output tensor of shape (batch_size, output_dim).
103
+ """
104
+ if is_transposed:
105
+ # (batch_size, 1, input_dim) @ (batch_size, input_dim, output_dim) -> (batch_size, 1, output_dim) -> (batch_size, output_dim)
106
+ out = torch.bmm(input.unsqueeze(1), weight).squeeze(1)
107
+ else:
108
+ # (batch_size, output_dim, input_dim) @ (batch_size, input_dim, 1) -> (batch_size, output_dim, 1) -> (batch_size, output_dim)
109
+ out = torch.bmm(weight, input.unsqueeze(-1)).squeeze(-1)
110
+
111
+ if bias is not None:
112
+ out.add_(bias)
113
+
114
+ return out
115
+
116
+
117
+ def batched_mm_experts_forward(
118
+ self: torch.nn.Module,
119
+ hidden_states: torch.Tensor,
120
+ top_k_index: torch.Tensor,
121
+ top_k_weights: torch.Tensor,
122
+ ) -> torch.Tensor:
123
+ num_top_k = top_k_index.size(-1)
124
+ num_tokens = hidden_states.size(0)
125
+ hidden_dim = hidden_states.size(-1)
126
+
127
+ # S is the number of selected tokens-experts pairs (S = num_tokens * num_top_k)
128
+ # Replicate each token num_top_k times to align with the flattened (S,) routing tensors.
129
+ selected_hidden_states = hidden_states.repeat_interleave(num_top_k, dim=0)
130
+ sample_weights = top_k_weights.reshape(-1) # (S,)
131
+ expert_ids = top_k_index.reshape(-1) # (S,)
132
+
133
+ # Clamp EP sentinels so `gate_up_proj[expert_ids]` stays in-bounds. Routing weights are already
134
+ # zero at sentinel slots (RouterParallel masks them at dispatch), so the weighted mul drops
135
+ # those contributions — we pay the wasted GEMM compute because batched_mm has no offset to skip.
136
+ expert_ids.clamp_(0, self.num_experts - 1)
137
+
138
+ # Select gate_up or just up projection weights and biases
139
+ if self.has_gate:
140
+ selected_weights = self.gate_up_proj[expert_ids]
141
+ selected_biases = self.gate_up_proj_bias[expert_ids] if self.has_bias else None
142
+ else:
143
+ selected_weights = self.up_proj[expert_ids]
144
+ selected_biases = self.up_proj_bias[expert_ids] if self.has_bias else None
145
+
146
+ # --- Up projection per expert (batched) ---
147
+ proj_out = _batched_linear(
148
+ selected_hidden_states, selected_weights, bias=selected_biases, is_transposed=self.is_transposed
149
+ ) # (S, 2 * intermediate_dim) or (S, intermediate_dim) depending on whether we have gating
150
+
151
+ # Apply gating or activation
152
+ if self.has_gate:
153
+ # for gated experts we apply the custom/default gating mechanism
154
+ proj_out = self._apply_gate(proj_out) # (S, intermediate_dim)
155
+ else:
156
+ # for non-gated experts we just apply the activation function
157
+ proj_out = self.act_fn(proj_out) # (S, intermediate_dim)
158
+
159
+ # Select down projection weights and biases for selected samples
160
+ selected_weights = self.down_proj[expert_ids]
161
+ selected_biases = self.down_proj_bias[expert_ids] if self.has_bias else None
162
+
163
+ # --- Down projection per expert (batched) ---
164
+ proj_out = _batched_linear(
165
+ proj_out, selected_weights, bias=selected_biases, is_transposed=self.is_transposed
166
+ ) # (S, hidden_dim)
167
+
168
+ # Apply routing weights
169
+ weighted_out = proj_out * sample_weights.unsqueeze(-1) # (S, hidden_dim)
170
+
171
+ # Accumulate results using deterministic reshape+sum instead of index_add_
172
+ # index_add_ with duplicate indices is non-deterministic on CUDA due to atomicAdd
173
+ # index_add_ accumulates in-place using the dtype of the output tensor (fp16/bf16)
174
+ # reshape+sum accumulates in fp32 which is more stable for low precision training/inference.
175
+ final_hidden_states = weighted_out.view(num_tokens, num_top_k, hidden_dim).sum(dim=1)
176
+
177
+ return final_hidden_states.to(hidden_states.dtype)
178
+
179
+
180
+ # torch.compiler.disable does not work with fullgraph=True, so we implement a custom operator to opaque this function.
181
+ # This is not "free compilation compatibility" because now inductor won't be able to optimize matmuls inside the loop,
182
+ # but since the matmuls here have dynamic shapes, inductor wouldn't have been able to optimize them anyway.
183
+ def _grouped_mm_fallback(input: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> torch.Tensor:
184
+ """
185
+ Fallback grouped matrix multiplication used when `torch.nn.functional.grouped_mm` and `torch._grouped_mm`
186
+ are unavailable or incompatible with `torch.compile` (e.g. non-bfloat16 weights).
187
+
188
+ Args:
189
+ input (`torch.Tensor`): Input of shape (S, input_dim), sorted by expert id.
190
+ weight (`torch.Tensor`): Expert weights of shape (num_experts, input_dim, output_dim).
191
+ offs (`torch.Tensor`): Cumulative token counts per expert of shape (num_experts,).
192
+ Returns:
193
+ `torch.Tensor`: Output of shape (S, output_dim).
194
+ """
195
+ output = torch.zeros(input.size(0), weight.size(2), device=input.device, dtype=input.dtype) # (S, output_dim)
196
+
197
+ start = 0
198
+ # single cpu<->gpu sync point here,
199
+ # avoids multiple syncs inside the loop
200
+ for i, end in enumerate(offs.tolist()):
201
+ if start == end:
202
+ continue
203
+ torch.mm(input[start:end], weight[i], out=output[start:end])
204
+ start = end
205
+
206
+ return output
207
+
208
+
209
+ def _grouped_mm_fallback_fake(input: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> torch.Tensor:
210
+ """Shape/dtype inference stub for `_grouped_mm_fallback` required by `torch.compile`."""
211
+ assert input.dim() == 2, f"input must be 2D (S, input_dim), got shape {tuple(input.shape)}"
212
+ assert weight.dim() == 3, (
213
+ f"weight must be 3D (num_experts, input_dim, output_dim), got shape {tuple(weight.shape)}"
214
+ )
215
+ assert offs.dim() == 1, f"offs must be 1D (num_experts,), got shape {tuple(offs.shape)}"
216
+ assert offs.size(0) == weight.size(0), f"offs length {offs.size(0)} must match number of experts {weight.size(0)}"
217
+ assert input.size(1) == weight.size(1), (
218
+ f"input_dim mismatch: input has {input.size(1)}, weight has {weight.size(1)}"
219
+ )
220
+ assert offs.dtype in (torch.int32, torch.int64), f"offs must be an integer tensor, got {offs.dtype}"
221
+ return torch.empty(input.size(0), weight.size(2), device=input.device, dtype=input.dtype)
222
+
223
+
224
+ def _grouped_mm_fallback_setup_context(ctx, inputs, output):
225
+ """Saves input and weight for backward; offs is stored directly as it is a non-differentiable integer tensor."""
226
+ ctx.save_for_backward(inputs[0], inputs[1])
227
+ ctx.offs = inputs[2]
228
+
229
+
230
+ def _grouped_mm_fallback_backward(ctx, grad_output):
231
+ """Backward pass for `_grouped_mm_fallback`. Computes grad_input and grad_weight per expert group; offs has no gradient."""
232
+ input, weight = ctx.saved_tensors
233
+ grad_input = torch.zeros_like(input)
234
+ grad_weight = torch.zeros_like(weight)
235
+
236
+ start = 0
237
+ # single cpu<->gpu sync point here,
238
+ # avoids multiple syncs inside the loop
239
+ for i, end in enumerate(ctx.offs.tolist()):
240
+ if start == end:
241
+ continue
242
+ torch.mm(grad_output[start:end], weight[i].T, out=grad_input[start:end])
243
+ torch.mm(input[start:end].T, grad_output[start:end], out=grad_weight[i])
244
+ start = end
245
+
246
+ return grad_input, grad_weight, None
247
+
248
+
249
+ if is_torch_available():
250
+ torch.library.custom_op(
251
+ "transformers::grouped_mm_fallback",
252
+ _grouped_mm_fallback,
253
+ mutates_args=(),
254
+ schema="(Tensor input, Tensor weight, Tensor offs) -> Tensor",
255
+ )
256
+ torch.library.register_fake("transformers::grouped_mm_fallback", _grouped_mm_fallback_fake)
257
+ torch.library.register_autograd(
258
+ "transformers::grouped_mm_fallback",
259
+ _grouped_mm_fallback_backward,
260
+ setup_context=_grouped_mm_fallback_setup_context,
261
+ )
262
+
263
+
264
+ def _can_use_grouped_mm(input: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> bool:
265
+ """
266
+ Check if torch.nn.functional.grouped_mm or torch._grouped_mm can be used based on availability and compatibility with torch.compile.
267
+
268
+ Args:
269
+ input (`torch.Tensor`):
270
+ Input tensor of shape (S, input_dim).
271
+ weight (`torch.Tensor`):
272
+ Weight tensor of shape (num_experts, input_dim, output_dim).
273
+ offs (`torch.Tensor`):
274
+ Offsets tensor indicating the boundaries of each group in the input tensor.
275
+ Returns:
276
+ `bool`: True if grouped_mm can be used, False otherwise.
277
+ """
278
+ if (is_torchdynamo_compiling() and weight.dtype != torch.bfloat16) or (
279
+ weight.device.type == "cpu"
280
+ # accept_dev=True is necessary for "+cpu"/"+xpu" etc.
281
+ and is_torch_less_or_equal("2.10.0", accept_dev=True)
282
+ and (weight.data_ptr() % 16 != 0 or input.data_ptr() % 16 != 0)
283
+ ):
284
+ # Under the following conditions we cannot use torch.grouped_mm and have to fall back:
285
+ # 1. torch.grouped_mm is not supported in torch.compile / inductor with dtypes other than bf16
286
+ # 2. Before PyTorch 2.11, torch.grouped_mm on CPU required 16 bytes alignment which is not
287
+ # guaranteed for tensors loaded using memmap (e.g. using safetensors lazy tensor loading)
288
+ # and not really necessary because the cpu path uses a fallback for-loop implementation.
289
+ # issue: https://github.com/pytorch/pytorch/issues/172440
290
+ return False
291
+
292
+ # On CUDA, `grouped_mm` availability also depends on GPU compute capability:
293
+ # `torch.nn.functional.grouped_mm` in torch>=2.10 and `torch._grouped_mm` in torch>=2.9 support SM80+
294
+ # but older `torch._grouped_mm` requires SM90+.
295
+ if weight.device.type == "cuda":
296
+ if hasattr(torch.nn.functional, "grouped_mm"):
297
+ return torch.cuda.get_device_capability(weight.device) >= (8, 0)
298
+ if hasattr(torch, "_grouped_mm"):
299
+ if is_torch_greater_or_equal("2.9", accept_dev=True):
300
+ return torch.cuda.get_device_capability(weight.device) >= (8, 0)
301
+ else:
302
+ return torch.cuda.get_device_capability(weight.device) >= (9, 0)
303
+
304
+ return False
305
+
306
+ return hasattr(torch.nn.functional, "grouped_mm") or hasattr(torch, "_grouped_mm")
307
+
308
+
309
+ def _grouped_mm(
310
+ input: torch.Tensor,
311
+ weight: torch.Tensor,
312
+ offs: torch.Tensor,
313
+ ) -> torch.Tensor:
314
+ """Grouped matrix multiplication dispatcher that uses torch.nn.functional.grouped_mm if available, else falls back to torch._grouped_mm.
315
+
316
+ Args:
317
+ input (`torch.Tensor`):
318
+ Input tensor of shape (S, input_dim).
319
+ weight (`torch.Tensor`):
320
+ Weight tensor of shape (num_experts, input_dim, output_dim).
321
+ offs (`torch.Tensor`):
322
+ Offsets tensor indicating the boundaries of each group in the input tensor.
323
+ Returns:
324
+ `torch.Tensor`: Output tensor of shape (S, output_dim).
325
+ """
326
+
327
+ if _can_use_grouped_mm(input, weight, offs):
328
+ # torch.nn.functional.grouped_mm and torch._grouped_mm are not autocast-enabled,
329
+ # when autocast is enabled we can end up with intermediate tensors in fp32 (e.g. LayerNorm output) and weight tensors in bf16
330
+ # In that case we need to cast the input to the weight dtype to avoid dtype mismatch errors.
331
+ # See: https://github.com/pytorch/pytorch/issues/174763
332
+ if hasattr(torch.nn.functional, "grouped_mm"):
333
+ return torch.nn.functional.grouped_mm(input.to(weight.dtype), weight, offs=offs)
334
+ elif hasattr(torch, "_grouped_mm"):
335
+ return torch._grouped_mm(input.to(weight.dtype), weight, offs=offs)
336
+
337
+ return torch.ops.transformers.grouped_mm_fallback(input, weight, offs=offs)
338
+
339
+
340
+ def _grouped_linear(
341
+ input: torch.Tensor,
342
+ weight: torch.Tensor,
343
+ offs: torch.Tensor,
344
+ bias: torch.Tensor | None = None,
345
+ is_transposed: bool = False,
346
+ ) -> torch.Tensor:
347
+ """Grouped linear layer supporting optional bias and transposed weights.
348
+
349
+ Args:
350
+ input (`torch.Tensor`):
351
+ Input tensor of shape (S, input_dim).
352
+ weight (`torch.Tensor`):
353
+ Weight tensor of shape (num_experts, input_dim, output_dim) if `is_transposed`,
354
+ else of shape (num_experts, output_dim, input_dim).
355
+ offs (`torch.Tensor`):
356
+ Offsets tensor indicating the boundaries of each group in the input tensor.
357
+ bias (`torch.Tensor`, *optional*):
358
+ Bias tensor of shape (num_experts, output_dim). Default is `None`.
359
+ is_transposed (`bool`, *optional*, defaults to `False`):
360
+ Whether the weight tensor is transposed.
361
+ Returns:
362
+ `torch.Tensor`: Output tensor of shape (S, output_dim).
363
+ """
364
+ if is_transposed:
365
+ # (S, input_dim) @ grouped (num_experts, input_dim, output_dim) -> (S, output_dim)
366
+ out = _grouped_mm(input, weight, offs=offs)
367
+ else:
368
+ # (S, input_dim) @ grouped (num_experts, output_dim, input_dim).T -> (S, output_dim)
369
+ out = _grouped_mm(input, weight.transpose(-2, -1), offs=offs)
370
+
371
+ if bias is not None:
372
+ # We should be able to pass bias to the grouped_mm call, but it's not yet supported.
373
+ out.add_(bias)
374
+
375
+ return out
376
+
377
+
378
+ def grouped_mm_experts_forward(
379
+ self: torch.nn.Module,
380
+ hidden_states: torch.Tensor,
381
+ top_k_index: torch.Tensor,
382
+ top_k_weights: torch.Tensor,
383
+ ) -> torch.Tensor:
384
+ device = hidden_states.device
385
+ num_top_k = top_k_index.size(-1)
386
+ num_tokens = hidden_states.size(0)
387
+ hidden_dim = hidden_states.size(-1)
388
+
389
+ # S is the number of selected tokens-experts pairs (S = num_tokens * num_top_k)
390
+ sample_weights = top_k_weights.reshape(-1) # (S,)
391
+ expert_ids = top_k_index.reshape(-1) # (S,)
392
+
393
+ # Sort by expert for grouped processing
394
+ expert_ids_g, perm = torch.sort(expert_ids)
395
+ selected_hidden_states_g = hidden_states[perm // num_top_k]
396
+ sample_weights_g = sample_weights[perm]
397
+
398
+ # Compute offsets for grouped_mm
399
+ # using histc instead of bincount to avoid cuda graph issues
400
+ # With deterministic algorithms, CPU only supports float input, CUDA only supports int input.
401
+ # torch.histc() does not support integer dtypes on CPU and MPS.
402
+ histc_input = expert_ids_g.float() if device.type in ("cpu", "mps") else expert_ids_g.int()
403
+ tokens_per_expert = torch.histc(histc_input, bins=self.num_experts, min=0, max=self.num_experts - 1)
404
+ offsets = torch.cumsum(tokens_per_expert, dim=0, dtype=torch.int32)
405
+
406
+ # EP sentinel handling: leave `expert_ids` unclamped so the sort pushes sentinels to the tail,
407
+ # `histc(max=num_experts-1)` drops them from `tokens_per_expert`, and grouped_mm skips rows
408
+ # beyond `offsets[-1]` — sentinels cost no real GEMM compute. The kernel leaves sentinel-tail
409
+ # rows of its output uninit (both fwd output and bwd `d_input`), but ONE pre-mask + ONE
410
+ # post-mask covers the whole forward — no per-grouped_mm masking is needed, because
411
+ # intermediate sentinel-row NaN is only ever consumed by the next grouped_mm, which itself
412
+ # only reads rows `< offsets[-1]`:
413
+ # - fwd post-mask on `weighted_out`: kills `proj_out[sentinel] * 0 = NaN * 0 = NaN`
414
+ # before the per-token reduction sums it.
415
+ # - bwd pre-mask on `selected_hidden_states_g`: its `masked_fill_` backward zeros sentinel
416
+ # rows of `d_selected_hidden_states_g` after the up grouped_mm bwd writes them as
417
+ # uninit, and before the gather's scatter-add pushes them into `d_hidden_states`.
418
+ # In-place clamp on `expert_ids_g` keeps the per-row bias gather in-bounds (bias added at
419
+ # sentinel positions falls in rows the kernel skips, so harmless). Safe to mutate now —
420
+ # nothing downstream needs the sentinel info from `expert_ids_g` itself.
421
+ sentinel_mask = (expert_ids_g >= self.num_experts).unsqueeze(-1)
422
+ expert_ids_g.clamp_(max=self.num_experts - 1)
423
+
424
+ # Select expert weights and biases
425
+ # NOTE: We keep all experts here and rely on offsets to target the active ones.
426
+ # I have already implemented a version that only passes the active experts, but
427
+ # to do so I had to use torch.unique which breaks the graph capture (data-dependent).
428
+ # Also there were no speedup gains from it in my experiments, even in eager mode.
429
+ # NOTE: The grouped_mm kernel only targets the active experts / tokens via the offsets
430
+ if self.has_gate:
431
+ selected_weights = self.gate_up_proj
432
+ selected_biases = self.gate_up_proj_bias[expert_ids_g] if self.has_bias else None
433
+ else:
434
+ selected_weights = self.up_proj
435
+ selected_biases = self.up_proj_bias[expert_ids_g] if self.has_bias else None
436
+
437
+ # Pre-mask (bwd path).
438
+ selected_hidden_states_g.masked_fill_(sentinel_mask, 0.0)
439
+
440
+ # --- Up projection per expert (grouped) ---
441
+ proj_out = _grouped_linear(
442
+ selected_hidden_states_g, selected_weights, offsets, bias=selected_biases, is_transposed=self.is_transposed
443
+ ) # (S, 2 * intermediate_dim) or (S, intermediate_dim) depending on whether we have gating
444
+
445
+ # Apply gating or activation
446
+ if self.has_gate:
447
+ # for gated experts we apply the custom/default gating mechanism
448
+ proj_out = self._apply_gate(proj_out) # (S, intermediate_dim)
449
+ else:
450
+ # for non-gated experts we just apply the activation function
451
+ proj_out = self.act_fn(proj_out) # (S, intermediate_dim)
452
+
453
+ # Select down projection weights and biases
454
+ selected_weights = self.down_proj
455
+ selected_biases = self.down_proj_bias[expert_ids_g] if self.has_bias else None
456
+
457
+ # --- Down projection per expert (grouped) ---
458
+ proj_out = _grouped_linear(
459
+ proj_out, selected_weights, offsets, bias=selected_biases, is_transposed=self.is_transposed
460
+ ) # (S, hidden_dim)
461
+
462
+ # Apply routing weights
463
+ weighted_out = proj_out * sample_weights_g.unsqueeze(-1) # (S, hidden_dim)
464
+
465
+ # Post-mask (fwd path).
466
+ weighted_out.masked_fill_(sentinel_mask, 0.0)
467
+
468
+ # Restore original order
469
+ inv_perm = torch.empty_like(perm)
470
+ inv_perm[perm] = torch.arange(perm.size(0), device=device)
471
+ weighted_out = weighted_out[inv_perm] # (S, hidden_dim)
472
+
473
+ # Accumulate results using deterministic reshape+sum instead of index_add_
474
+ # index_add_ with duplicate indices is non-deterministic on CUDA due to atomicAdd
475
+ # index_add_ accumulates in-place using the dtype of the output tensor (fp16/bf16)
476
+ # reshape+sum accumulates in fp32 which is more stable for low precision training/inference.
477
+ final_hidden_states = weighted_out.view(num_tokens, num_top_k, hidden_dim).sum(dim=1)
478
+
479
+ return final_hidden_states.to(hidden_states.dtype)
480
+
481
+
482
+ class ExpertsInterface(GeneralInterface):
483
+ """Interface for registering custom experts forward functions."""
484
+
485
+ _global_mapping = {
486
+ "batched_mm": batched_mm_experts_forward,
487
+ "grouped_mm": grouped_mm_experts_forward,
488
+ "sonicmoe": sonicmoe_experts_forward,
489
+ }
490
+
491
+ def get_interface(self, experts_implementation: str, default: Callable) -> Callable:
492
+ """Return the requested `experts_implementation`. Also strictly check its validity, and raise if invalid."""
493
+ if experts_implementation is None:
494
+ logger.warning_once(
495
+ "You tried to access the `ExpertsInterface` with a `config._experts_implementation` set to `None`. This "
496
+ "is expected if you use an Expert Module as a standalone Module. If this is not the case, something went "
497
+ "wrong with the dispatch of `config._experts_implementation`"
498
+ )
499
+ elif experts_implementation != "eager" and experts_implementation not in self:
500
+ raise KeyError(
501
+ f"`{experts_implementation}` is not a valid experts implementation registered in the `ExpertsInterface`"
502
+ )
503
+ return super().get(experts_implementation, default)
504
+
505
+
506
+ ALL_EXPERTS_FUNCTIONS = ExpertsInterface()
507
+
508
+
509
+ def _default_apply_gate(self, gate_up_out: torch.Tensor) -> torch.Tensor:
510
+ """
511
+ Default gating mechanism: splits the gate_up_out into gate and up parts,
512
+ applies the activation function to the gate part, and multiplies it with the up part.
513
+ Args:
514
+ gate_up_out (`torch.Tensor`):
515
+ The output tensor from the gate and up projection of shape (S, 2 * intermediate_dim).
516
+ Returns:
517
+ `torch.Tensor`: The gated output tensor of shape (S, intermediate_dim).
518
+ """
519
+ gate, up = gate_up_out.chunk(2, dim=-1) # (S, intermediate_dim)
520
+ return self.act_fn(gate) * up # (S, intermediate_dim)
521
+
522
+
523
+ def use_experts_implementation(
524
+ experts_class: type[torch.nn.Module] | None = None,
525
+ *,
526
+ experts_interface: ExpertsInterface = ALL_EXPERTS_FUNCTIONS,
527
+ is_concatenated: bool = True,
528
+ is_transposed: bool = False,
529
+ has_bias: bool = False,
530
+ has_gate: bool = True,
531
+ ) -> type[torch.nn.Module]:
532
+ """Decorator to modify experts class to support different experts implementations.
533
+
534
+ Args:
535
+ experts_class (`type[torch.nn.Module]`, *optional*):
536
+ The experts class to modify. If not provided, returns a decorator that can be applied to the class.
537
+ experts_interface (`ExpertsInterface`, *optional*, defaults to `ALL_EXPERTS_FUNCTIONS`):
538
+ The experts interface to use for dispatching the forward method.
539
+ is_concatenated (`bool`, *optional*, defaults to `True`):
540
+ Whether the expert weights are stored in concatenated layout [gate;up]
541
+ or interleaved layout [gate0, up0, gate1, up1, ...].
542
+ is_transposed (`bool`, *optional*, defaults to `False`):
543
+ Whether the expert weights are stored in transposed format.
544
+ has_bias (`bool`, *optional*, defaults to `False`):
545
+ Whether the expert layers include bias terms or not.
546
+ has_gate (`bool`, *optional*, defaults to `True`):
547
+ Whether the experts use a gating mechanism or not.
548
+ Whether it has gate_up_proj weights or just up_proj weights.
549
+
550
+ Returns:
551
+ `type[torch.nn.Module]`: The modified experts class.
552
+ """
553
+
554
+ def wrapper(experts_class: type[torch.nn.Module]) -> type[torch.nn.Module]:
555
+ original_init = experts_class.__init__
556
+ original_forward = experts_class.forward
557
+
558
+ @wraps(original_init)
559
+ def __init__(self, config, *args, **kwargs):
560
+ original_init(self, config, *args, **kwargs)
561
+ self.config = config
562
+ self.has_gate = has_gate
563
+ self.has_bias = has_bias
564
+ self.is_transposed = is_transposed
565
+ self.is_concatenated = is_concatenated
566
+
567
+ @wraps(original_forward)
568
+ def forward(self, *args, **kwargs):
569
+ experts_forward = experts_interface.get_interface(self.config._experts_implementation, original_forward)
570
+ return experts_forward(self, *args, **kwargs)
571
+
572
+ if not hasattr(experts_class, "_apply_gate"):
573
+ experts_class._apply_gate = _default_apply_gate
574
+
575
+ experts_class.__init__ = __init__
576
+ experts_class.forward = forward
577
+ return experts_class
578
+
579
+ if experts_class is not None:
580
+ return wrapper(experts_class)
581
+
582
+ return wrapper
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/npu_flash_attention.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ import math
14
+ import os
15
+
16
+ import torch
17
+
18
+ from ..utils.import_utils import is_torch_npu_available
19
+
20
+
21
+ if is_torch_npu_available():
22
+ from torch_npu import npu_fusion_attention
23
+
24
+
25
+ # FlashAttention2 is supported on Ascend NPU with down-right aligned causal mask by default.
26
+ # Set environment variable `NPU_FA2_SPARSE_MODE` to 2 when using top-left aligned causal mask.
27
+ TOP_LEFT_ALIGNED_CAUSAL_MASK_MODE = 2
28
+ DOWN_RIGHT_ALIGNED_CAUSAL_MASK_MODE = 3
29
+
30
+ SPARSE_MODE = int(os.getenv("NPU_FA2_SPARSE_MODE", default=DOWN_RIGHT_ALIGNED_CAUSAL_MASK_MODE))
31
+ if SPARSE_MODE not in [TOP_LEFT_ALIGNED_CAUSAL_MASK_MODE, DOWN_RIGHT_ALIGNED_CAUSAL_MASK_MODE]:
32
+ raise ValueError(
33
+ "Environment variable `NPU_FA2_SPARSE_MODE` can only be set as 2 (top-left aligned causal mask) "
34
+ "or 3 (down-right aligned causal mask)."
35
+ )
36
+
37
+ ATTN_MASK_NPU_CACHE = {}
38
+
39
+
40
+ def get_attn_mask_npu(device):
41
+ """Get or create attention mask for the specified device."""
42
+ if device not in ATTN_MASK_NPU_CACHE:
43
+ ATTN_MASK_NPU_CACHE[device] = torch.triu(torch.ones([2048, 2048], device=device), diagonal=1).bool()
44
+ return ATTN_MASK_NPU_CACHE[device]
45
+
46
+
47
+ def is_npu_fa2_top_left_aligned_causal_mask():
48
+ return SPARSE_MODE == TOP_LEFT_ALIGNED_CAUSAL_MASK_MODE if is_torch_npu_available() else False
49
+
50
+
51
+ def npu_flash_attn_func(
52
+ q,
53
+ k,
54
+ v,
55
+ dropout_p=0.0,
56
+ softmax_scale=None,
57
+ causal=False,
58
+ **kwargs,
59
+ ):
60
+ keep_prob = 1.0 - dropout_p
61
+
62
+ if softmax_scale is None:
63
+ softmax_scale = 1.0 / math.sqrt(q.shape[-1])
64
+
65
+ if not causal:
66
+ head_num = q.shape[2]
67
+ output = npu_fusion_attention(q, k, v, head_num, "BSND", keep_prob=keep_prob, scale=softmax_scale)[0]
68
+ else:
69
+ attn_mask_npu = get_attn_mask_npu(q.device)
70
+ head_num = q.shape[2]
71
+ output = npu_fusion_attention(
72
+ q,
73
+ k,
74
+ v,
75
+ head_num,
76
+ "BSND",
77
+ keep_prob=keep_prob,
78
+ scale=softmax_scale,
79
+ atten_mask=attn_mask_npu,
80
+ sparse_mode=SPARSE_MODE,
81
+ )[0]
82
+
83
+ return output
84
+
85
+
86
+ def npu_flash_attn_varlen_func(
87
+ q,
88
+ k,
89
+ v,
90
+ cu_seqlens_q,
91
+ cu_seqlens_k,
92
+ max_seqlen_q=None, # defined for aligning params order with corresponding function in `flash-attn`
93
+ max_seqlen_k=None, # defined for aligning params order with corresponding function in `flash-attn`
94
+ dropout_p=0.0,
95
+ softmax_scale=None,
96
+ causal=False,
97
+ **kwargs,
98
+ ):
99
+ keep_prob = 1.0 - dropout_p
100
+
101
+ if softmax_scale is None:
102
+ softmax_scale = 1.0 / math.sqrt(q.shape[-1])
103
+
104
+ if not causal:
105
+ head_num = q.shape[1]
106
+ output = npu_fusion_attention(
107
+ q,
108
+ k,
109
+ v,
110
+ head_num,
111
+ pse=None,
112
+ atten_mask=None,
113
+ scale=softmax_scale,
114
+ keep_prob=keep_prob,
115
+ input_layout="TND",
116
+ actual_seq_qlen=tuple(cu_seqlens_q[1:].cpu().numpy().tolist()),
117
+ actual_seq_kvlen=tuple(cu_seqlens_k[1:].cpu().numpy().tolist()),
118
+ )[0]
119
+ else:
120
+ attn_mask_npu = get_attn_mask_npu(q.device)
121
+ head_num = q.shape[1]
122
+ output = npu_fusion_attention(
123
+ q,
124
+ k,
125
+ v,
126
+ head_num,
127
+ pse=None,
128
+ padding_mask=None,
129
+ atten_mask=attn_mask_npu,
130
+ scale=softmax_scale,
131
+ keep_prob=keep_prob,
132
+ input_layout="TND",
133
+ actual_seq_qlen=tuple(cu_seqlens_q[1:].cpu().numpy().tolist()),
134
+ actual_seq_kvlen=tuple(cu_seqlens_k[1:].cpu().numpy().tolist()),
135
+ sparse_mode=SPARSE_MODE,
136
+ )[0]
137
+
138
+ return output
139
+
140
+
141
+ # This function is not implemented but should never be called because block table is not used on NPU
142
+ def npu_flash_attn_with_kvcache():
143
+ raise NotImplementedError("npu_flash_attn_with_kvcache is not implemented")
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/spqr.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ "SpQR (Sparse-Quantized Representation) integration file"
15
+
16
+ from ..quantizers.quantizers_utils import should_convert_module
17
+ from ..utils import is_spqr_available, is_torch_available, logging
18
+
19
+
20
+ if is_torch_available():
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ def replace_with_spqr_linear(model, modules_to_not_convert: list[str] | None = None, quantization_config=None):
28
+ """
29
+ Public method that replaces the Linear layers of the given model with SPQR quantized layers.
30
+
31
+ Args:
32
+ model (`torch.nn.Module`):
33
+ The model to convert, can be any `torch.nn.Module` instance.
34
+ modules_to_not_convert (`list[str]`, *optional*, defaults to `None`):
35
+ A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
36
+ converted.
37
+ quantization_config (`SpQRConfig`):
38
+ The quantization config object that contains the quantization parameters.
39
+ """
40
+ if is_spqr_available():
41
+ from spqr_quant import QuantizedLinear
42
+
43
+ has_been_replaced = False
44
+ # we need this to correctly materialize the weights during quantization
45
+ for module_name, module in model.named_modules():
46
+ if not should_convert_module(module_name, modules_to_not_convert):
47
+ continue
48
+ with torch.device("meta"):
49
+ if isinstance(module, nn.Linear):
50
+ shapes = quantization_config.shapes
51
+
52
+ new_module = QuantizedLinear.create_placehodler(
53
+ rows=module.out_features,
54
+ cols=module.in_features,
55
+ bits=quantization_config.bits,
56
+ beta1=quantization_config.beta1,
57
+ beta2=quantization_config.beta2,
58
+ dense_weights_shape=shapes[f"{module_name}.dense_weights.shape"],
59
+ row_offsets_shape=shapes[f"{module_name}.row_offsets.shape"],
60
+ col_vals_shape=shapes[f"{module_name}.col_vals.shape"],
61
+ in_perm_shape=shapes[f"{module_name}.in_perm.shape"],
62
+ )
63
+ # Force requires grad to False to avoid unexpected errors
64
+ model._modules[module_name].requires_grad_(False)
65
+ model.set_submodule(module_name, new_module)
66
+ has_been_replaced = True
67
+ if not has_been_replaced:
68
+ logger.warning(
69
+ "You are loading your model using eetq but no linear modules were found in your model."
70
+ " Please double check your model architecture, or submit an issue on github if you think this is"
71
+ " a bug."
72
+ )
73
+
74
+ return model
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/integrations/torchao.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ import types
17
+
18
+ import torch
19
+
20
+ from transformers.utils import logging
21
+ from transformers.utils.import_utils import is_torch_available, is_torchao_available
22
+
23
+
24
+ if is_torch_available():
25
+ from ..core_model_loading import ConversionOps
26
+ from ..quantizers.quantizers_utils import get_module_from_name
27
+
28
+
29
+ if is_torchao_available():
30
+ from torchao.prototype.safetensors.safetensors_support import (
31
+ unflatten_tensor_state_dict,
32
+ )
33
+ from torchao.prototype.safetensors.safetensors_utils import is_metadata_torchao
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ def _quantization_type(weight):
39
+ from torchao.dtypes import AffineQuantizedTensor
40
+ from torchao.quantization.linear_activation_quantized_tensor import LinearActivationQuantizedTensor
41
+
42
+ if isinstance(weight, AffineQuantizedTensor):
43
+ return f"{weight.__class__.__name__}({weight._quantization_type()})"
44
+
45
+ if isinstance(weight, LinearActivationQuantizedTensor):
46
+ return f"{weight.__class__.__name__}(activation={weight.input_quant_func}, weight={_quantization_type(weight.original_weight_tensor)})"
47
+
48
+
49
+ def _linear_extra_repr(self):
50
+ weight = _quantization_type(self.weight)
51
+ if weight is None:
52
+ return f"in_features={self.weight.shape[1]}, out_features={self.weight.shape[0]}, weight=None"
53
+ else:
54
+ return f"in_features={self.weight.shape[1]}, out_features={self.weight.shape[0]}, weight={weight}"
55
+
56
+
57
+ class TorchAoQuantize(ConversionOps):
58
+ def __init__(self, hf_quantizer):
59
+ self.hf_quantizer = hf_quantizer
60
+
61
+ def _quantize(self, module, config, *args, **kwargs):
62
+ """Run quantize_, moving to CUDA first if CPU offloading is active.
63
+
64
+ Some torchao quantization ops (e.g. int4 packing) only have CUDA kernels.
65
+ When a layer is destined for CPU (e.g. CPU offloading), we temporarily move
66
+ it to CUDA for quantization, then move the result back to CPU.
67
+ """
68
+ from torchao.quantization import quantize_
69
+
70
+ target_device = next(module.parameters()).device
71
+ if self.hf_quantizer.offload_to_cpu and target_device.type == "cpu":
72
+ module.to("cuda")
73
+ quantize_(module, config, *args, **kwargs)
74
+ module.to("cpu")
75
+ else:
76
+ quantize_(module, config, *args, **kwargs)
77
+
78
+ def convert(
79
+ self,
80
+ input_dict: dict[str, torch.Tensor],
81
+ model: torch.nn.Module | None = None,
82
+ full_layer_name: str | None = None,
83
+ missing_keys=None,
84
+ **kwargs,
85
+ ) -> dict[str, torch.Tensor]:
86
+ _, value = tuple(input_dict.items())[0]
87
+ value = value[0] if isinstance(value, list) else value
88
+
89
+ module, tensor_name = get_module_from_name(model, full_layer_name)
90
+
91
+ module._parameters[tensor_name] = torch.nn.Parameter(value, requires_grad=value.requires_grad)
92
+ # if we are quantizing tied parameters, to avoid tying the quantized weights
93
+ # the correct order to do it is
94
+ # 1. load the weight to model
95
+ # 2. run tie_weights to populate the weights
96
+ # 3. quantize
97
+ input_embed = model.get_input_embeddings()
98
+ is_embedding_param = id(module) == id(input_embed)
99
+ untie_embedding_weights = self.hf_quantizer.quantization_config.untie_embedding_weights
100
+
101
+ if untie_embedding_weights and is_embedding_param:
102
+ setattr(model.config.get_text_config(decoder=True), "tie_word_embeddings", False)
103
+
104
+ from torchao.quantization import FqnToConfig
105
+
106
+ config = self.hf_quantizer.quantization_config.get_apply_tensor_subclass()
107
+ if isinstance(config, FqnToConfig):
108
+ module_fqn, top_level_param_name = full_layer_name.rsplit(".", 1)
109
+ c = None
110
+ if full_layer_name in config.fqn_to_config:
111
+ assert not module_fqn.startswith("re:"), (
112
+ "param fqn should not start with`re:`, which is used for specifying regex"
113
+ )
114
+ c = config.module_fqn_to_config[full_layer_name]
115
+ elif module_fqn in config.fqn_to_config:
116
+ assert not module_fqn.startswith("re:"), (
117
+ "module fqn should not start with`re:`, which is used for specifying regex"
118
+ )
119
+ c = config.module_fqn_to_config[module_fqn]
120
+ # regex match module and param
121
+ else:
122
+ for maybe_module_fqn_pattern in config.fqn_to_config:
123
+ # if key doesn't start with re, it is an exact fqn key, so we don't regex match
124
+ if not maybe_module_fqn_pattern.startswith("re:"):
125
+ continue
126
+ # see if param matches first
127
+ elif re.fullmatch(maybe_module_fqn_pattern[3:], full_layer_name):
128
+ c = config.module_fqn_to_config[maybe_module_fqn_pattern]
129
+ break
130
+ elif re.fullmatch(maybe_module_fqn_pattern[3:], module_fqn):
131
+ # we'll apply the config for first fully matched pattern
132
+ c = config.module_fqn_to_config[maybe_module_fqn_pattern]
133
+ break
134
+ else:
135
+ c = config.module_fqn_to_config.get("_default", None)
136
+
137
+ if c is not None:
138
+ if top_level_param_name == "weight":
139
+ if is_embedding_param and untie_embedding_weights:
140
+ lm_head = module.weight.clone()
141
+ # we can apply the module config directly
142
+ self._quantize(module, c, (lambda x, fqn: True))
143
+ missing_keys.discard(full_layer_name)
144
+ module._is_hf_initialized = True
145
+ # torchao quantizes weights into a module but some models access the weight directly
146
+ # (e.g. module.o_proj.weight). The _is_hf_initialized flag is set at the module
147
+ # level only, so we also set it on each parameter to prevent _init_weights from
148
+ # calling normal_() on already-quantized Float8Tensors.
149
+ for param in module.parameters(recurse=False):
150
+ param._is_hf_initialized = True
151
+ return {"lm_head.weight": lm_head} if is_embedding_param and untie_embedding_weights else {}
152
+ else:
153
+ # need to apply to custom param name
154
+ custom_param_fqn_config = FqnToConfig({top_level_param_name: c})
155
+ self._quantize(module, custom_param_fqn_config, filter_fn=None)
156
+ missing_keys.discard(full_layer_name)
157
+ module._is_hf_initialized = True
158
+ for param in module.parameters(recurse=False):
159
+ param._is_hf_initialized = True
160
+ return {}
161
+ return {full_layer_name: value}
162
+
163
+ if is_embedding_param and untie_embedding_weights:
164
+ lm_head = module.weight.clone()
165
+ self._quantize(module, self.hf_quantizer.quantization_config.get_apply_tensor_subclass())
166
+ missing_keys.discard(full_layer_name)
167
+ module._is_hf_initialized = True
168
+ for param in module.parameters(recurse=False):
169
+ param._is_hf_initialized = True
170
+ return {"lm_head.weight": lm_head} if is_embedding_param and untie_embedding_weights else {}
171
+
172
+
173
+ class TorchAoDeserialize(ConversionOps):
174
+ def __init__(self, hf_quantizer):
175
+ self.hf_quantizer = hf_quantizer
176
+
177
+ def convert(
178
+ self,
179
+ input_dict: dict[str, torch.Tensor],
180
+ source_patterns: list[str] | None = None,
181
+ model: torch.nn.Module | None = None,
182
+ full_layer_name: str | None = None,
183
+ missing_keys=None,
184
+ **kwargs,
185
+ ) -> dict[str, torch.Tensor]:
186
+ """
187
+ Consolidates tensor subclass components before reconstructing the object
188
+
189
+ For example:
190
+ input_dict: {
191
+ "_weight_qdata": torch.Tensor,
192
+ "_weight_scale": torch.Tensor,
193
+ }
194
+ full_layer_name: "model.layers.0.self_attn.k_proj.weight"
195
+
196
+ Given this, we reconstruct a Float8Tensor instance using the qdata and scale
197
+ and return it as a dictionary with the full_layer_name as the key and the recovered
198
+ Float8Tensor instance as the value.
199
+ """
200
+ is_unsafe_serialization = list(input_dict.keys())[0] not in source_patterns
201
+
202
+ param_data = {}
203
+ layer_name = ".".join(full_layer_name.split(".")[:-1])
204
+ if is_unsafe_serialization:
205
+ if isinstance(input_dict["weight"], list):
206
+ weight = input_dict["weight"][0]
207
+ else:
208
+ weight = input_dict["weight"]
209
+ else:
210
+ for suffix in input_dict.keys():
211
+ if len(input_dict[suffix]) != 1:
212
+ raise ValueError(
213
+ f"Expected a single tensor for {suffix} but got {len(input_dict[suffix])} tensors instead"
214
+ )
215
+ param_data[f"{layer_name}.{suffix}"] = input_dict[suffix][0]
216
+
217
+ # If it's unsafe-serialized (i.e. not safetensors), no need for anything
218
+ if is_unsafe_serialization:
219
+ return {full_layer_name: weight}
220
+ elif not is_metadata_torchao(self.hf_quantizer.metadata):
221
+ raise ValueError("Invalid torchao safetensors metadata")
222
+
223
+ unflattened_state_dict, leftover_state_dict = unflatten_tensor_state_dict(
224
+ param_data, self.hf_quantizer.metadata
225
+ )
226
+ assert not leftover_state_dict # there should be no unprocessed tensors
227
+ new_param = unflattened_state_dict[full_layer_name]
228
+
229
+ module, _ = get_module_from_name(model, full_layer_name)
230
+ # Add repr to the module
231
+ if isinstance(module, torch.nn.Linear):
232
+ module.extra_repr = types.MethodType(_linear_extra_repr, module)
233
+
234
+ return {full_layer_name: new_param}
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_owt_llmclean_qwen36_35b_10k_C1to1024sqrt_step013000_gpu_temp1_decode128_quick_n8.log ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ bos=1:</s> eos=1:</s>
2
+ decode steps=128 temp=1.0 mode=dirichlet c_min=1.0 c_max=1024.0 c_schedule=sqrt train_c_min=1.0 train_c_max=1024.0
3
+ ===== sample 0 =====
4
+ head_tokens: ['ing', '▁of', '▁the', '▁conviction', '▁of', '▁the', '▁capital', '▁of', '▁', 'a', 'FS', '▁of', '▁the', '▁returns', '▁of', '▁the']
5
+ tail_tokens: ['▁and', '▁occurred', '▁to', '▁the', '▁the', 's', '▁of', '▁the', '▁understanding', '▁of', '▁the', '▁triumph', '▁of', '▁the', '▁central', '</s>']
6
+ ing of the conviction of the capital of aFS of the returns of the god of the statuees, in the miracle of the capital. From up to pass the understanding of the Spiritss of the shields of the substance of the doors of thewards. Following the background of the initial account of contribution to the expression of the consciousness of the principal portion of their relations. principal collapses the remains in the refusal to ounce the ins of the frequentguide of Treasure. The understanding of the original account of the mind presented on the formation of the part of account the account of the understanding of theinals of the truth of the dis approval of the revolution, and the account of the Conquis of the the account of the cane of the authority. This is the lits of the property and the the narrative of theuring advance of the death the prominents of theigiken in the ambassador of the landlord of close in the age of the141. The noble Eli seeks to the coaces of the70 from the deepens of the authority of the law as the only remains of the gods and question of the actions in the ens of authority of the connection of the Royalativesment of the noises in thees possession of the entireclave of the crown of the Constitution to the relation of the head of the evidence of property in the Brazilian Court of the word created in the current corner of the value of the gate, thee of the power of the dealings of the believers of the the value of the Holyclaver of theors of detail, which that is the sound of the lored out of the Book of the, and the sources of the predicts of the essential of the expected to account the formation of the truth and by the truth of the property. According to hear the account of the commissioner contains as the referredly from the leadership of the battle of the ongoing authority of the expansion, to apply thecane of the battle to the understanding of the concrate, the understanding of the question of the ennics the ease of the truth and the constants of the power, and index the legacy of the law of the concentrations. The organization of the destruction of the fake faithful and the victim of the control of the parishs of theward itself of the site of the Conramas of the 13mination of the intervention, of the sens from the account of the Book of the unit. By the truth of the pastor of ten of the victim of the dus of the correct, ounce the equals of the Church of the theoretical theories of the understanding of spirituals, to thee of the essential eyes. According in the account of the Revolution of the transmission of the Christ of the relations of the gate of the first and account of the end of the occasion and the citizen and scopes on the top of the exhibit of societys and the remains of the truth of that of theclave of the 300-iration of the grand gate of the thro into a constant order. The understanding of the lack of the property, to the efficiency of the crown of thees of the doors to theimposed of the legacy of the property. The superior to the center of the contents of the the hands of the hands of the imposed of the legacy. It is the official explanation70 of the formation of the category and investigations upon theeon of the pen Church of the sum of the State of the epicill Christ. The Crowns a detailly as a particular truth of the constants of explanation. Just in the position of the reporting of the wards in the Vics the representatives of the grandes of the state, without aative of the category of the parishes of the card of the head of the power of the order of the Popes, in the display. Following the understanding of the writer and the hands of the priorly of thecan of the translation and truth of the page. The pre contribution from the extent of consciousness of the translations of the Caesars of the understanding and the count of the date of truth is, as the power of the viative of the truth of the moment of the mind of the wrong truth is a matter of practice in the contribution of the death of the discovery, in the relation of the noble, and the reflection of the dispower. The understanding Ministry of the will of the exchange of the saative of the Churchs of the entertainment. The truth is the understanding of the power of the forces of the situation in. It is the means of the account, and upon the abolishes in the Book of the world of a teacher to present in the remains of the significant understandings of the power. To the control of the Constitution of s the subject of the treatment of the law account and occurred to the thes of the understanding of the triumph of the central</s>
7
+ ===== sample 1 =====
8
+ head_tokens: ['▁Roger', 's', '.', '▁I', '▁was', '▁convinced', '▁that', '▁', 'he', "'", 's', '▁been', '▁as', '▁the', '▁writing', '▁team']
9
+ tail_tokens: ["'", 's', '▁eyes', ',', '▁', 'a', '▁show', '▁or', '▁', 'a', 'head', '▁to', '▁him', '.', '▁I', '</s>']
10
+ Rogers. I was convinced that he's been as the writing team, and he's getting to do him as understand that he's the officer a challenge to his obligations. "What a year, and he's a nice VI, and that's a a a sout conclusion. In some way, the practitioner: staff has call a heart of the weight. "I, it's the ssies, he's thought he has a Defense generation, no person.. I'm preparing a second person, um a hos. But it is a bit of a, the man drawn of the way, he's a bit. So to that, but he's told, he says his wife, a guy, a fit of the film, to raise him, he's it's a great. I'm a bunch. That's a trend on, and he's not to give a utters. But, that? Yeah, is he's, so. 'Some of all his stance, he's, and he's a fan of his eye funny. He's like he's the likes, he's a name, it's a9,' he grandmother's a quick, in the creative. Sometimes he's in a utter guy, he has him, of his life, he, he's like a finds. I a rathere, maybe, he's a guy I tell him to be watching. Sometimes that's him, I don't tell him a teenager call, he's him, that's absolutely tene's quiger.'" In a way that's me, he's a teenager, he's a Obster, he 41, he's very silent. His goence, he's done it, occasion, a app that's a on he's been in a quarter of politics, in a growing state, he still's a lack of doubt, he's a call to a-on, or a importance level of sort of dark and the stene of 40 and, he's getting in a way, he's there. He says a trend he says he's not in. he's got, a personality story from the zform of Fall. That's things he's a case, he's nice, he's a man a really narrow. This is a voicement. A sort of decades in a sea-auist, and he still's a ard in a fair call: and he's if he's he's, yeah. I's. I got a teenagers, 12, Imes. I had decided that shot him, he's a call with a a ant, he talks to that, he's, always see it, he's thoughtful. That is, who he's a goist,' and he's nice to burn, he's like a radio, he's got to him, he's, it's caught up. "He's not right, he's just too.hit, I loved Roger. And he says it, he's got to Anyway, he was a big. He has a central, no public motivation, and he's,'s a couple of getting a shiting. Finally, I feel the words, his son, he's a teenager. Not a man, a dad he says. "I's a king he, ever he's, and he's not a battle in his years. I think it's an extrause, he's he's not he says the needs. All shews, he is the story of the 1980s, includes the game, it's a ally alike. That's what's. But it's part of the universes. It's the Army he seems to him and get ahit. Maybe it's a man that's always a point, he's eyes, a show or ahead to him. I</s>
11
+ ===== sample 2 =====
12
+ head_tokens: ['▁to', '▁pass', '▁the', '▁Blood', '▁in', '▁itself', '▁that', '▁', 'he', '▁has', 'e', 'd', '▁that', '▁the', '▁Church', '▁of']
13
+ tail_tokens: ['▁of', '▁the', '▁law', ',', '▁only', '▁in', '▁', 'a', '▁view', '▁with', '▁', 'a', '▁masterpiece', '.', '▁Let', '</s>']
14
+ to pass the Blood in itself that he hased that the Church of meaning is, he feels in a strong conscience in a confession of a casthood of the Church will tell his ideas that he thinks to see a person he tells that opposition in a hood. It is a meaning that of a Church, and in a part of the orientation that his own and son of his wife, he is with the experience of his Church, and he is entirely utter. It is at the point of view he knows his opposition to forms his own grief, and saying, he sees instead to a particular symbol of the Church suffering and the truth and that is why the name of the Church of the truth, and that spix, this is a partial part of the Church. With the steels of the Church of the Churchs to the Church of the Church's souls, the disciple religions, all of the Church, with the Church that he is from the control of the Church, as if the youth of the law. Only the source of the Emperor, in acas, and the visited champions that has a department of a juice, and become a member of a concern so that the department's head of the lores, and surrounding the Union. Under a singlehood, the member of that law, which is influenced the priest of a habit of normal, that of sins in hisglis, at the height of the founders in a sacred structure. He is aspire that reforms the king of the meaning of the priest, in the case of which the Church understanding of the fulfillment of the nation of a worthy reading to the scope of the Church, and applied with the Church of the owner of a necessary constant, ward as a unit of the wife of the victim. By the night, that he is a popular uttered for sacrifices, and equals the true DNA of the life of the Holy Primes the control of his experience and knowledge, that, on the map of the Catholic and powers of the Pope of servant, the faith, and the law grant a heirs to the Church of the time, through their actions, and the height of the commons of the field of the Church. There is a text from that of the Churchs, a number of the channels and falls in a pre-sance in a special call of the law. Only as a result, by the guilt of a slimes, and a fine understanding of a mans tradition to the account of the Church's foundation's, and the Churchs are in avier of the general Parliament and the Order of the Constitution. Only the mind the pens of the Pope's register to the ill man. There, the priests Gods of a rage and a member of the egos. According to the origin of the evils, the feder of the Church, and the heirs with the 50s of the heavens some of the priests of providing the Church of the priest. The Church is a minister of the confessions and Christ. At the hands of the dictates of the feeling of authority to experience, hands of the knowledge: a ody and a separate sum. The man he ill in the floor of the union. This he is reading of the text reads the experience of affection of the powerounce. The criticism of the priests, he tend to detail a number of the Church of the center of the modern king. This is a astic portion of the priesthood, is a a part of a lack of a church, which it submits to the poor of a priest, with the friendships and the failure of the beings. When a er from the Church of the Church, a significant awareness of a horse of arite a crast of concern: a life of the hol a yield to the Church, he treated in a disappear, and even as a trait of law. Short dunces a destroying the experience of the reform to the members of the law. Sometimes he's a simple speech, having the saads and friendship in the Truths of the the Church of the crown organs. When the priests and the priests of pastors, who is due to battle with the hands of the Church. rupting a position in the end of the Church. Since a punishment, as 13 to represent the center of the Order of the Church, a graphic member of the law, only in a view with a masterpiece. Let</s>
15
+ ===== sample 3 =====
16
+ head_tokens: ['▁the', '▁meaning', '▁of', '▁the', '▁divine', '▁of', '▁classes', '▁of', '▁the', '▁hands', '▁of', '▁Christ', '.', '▁The', '▁view', '▁of']
17
+ tail_tokens: ['▁law', '.', '▁The', '▁best', '▁order', '▁to', '▁the', '▁function', ',', '▁the', '▁experience', '▁is', '▁', 'a', '▁presence', '</s>']
18
+ the meaning of the divine of classes of the hands of Christ. The view of the texts, in a category to the the division of the meanings of the display of understanding upon the existence of the truth and insistic account of the opening of the truth Truth of itself. The the Church's hands of the word because of the extension of communion in the portion of the gate from the collapse of the Church is understood as a to the account of the Assembly and authority, the translationss of a return to the control of the Church. At the eye of pen, it is the understanding of the understanding of theoretical and relation of the approval of the Church, and the understanding of the extension of the doors of the account of the Church of the Church, and the limited actions of the understanding of the voice in the understanding of the ceiling and the view of the provision, and value up to the costs of the answer, spite of the contribution. Some of the mind, a view of the completes of the text, of the truth of the sters of the authority, is the power of the sters of amendment. Some of the part of theration of reforms, the view of the helpfulative understanding of the means of the the understanding of the practice of the text in the perspective of the account and theprien of the presence of the situation of thence in the shadow and provision of favor. Only in the organization of the preene of this figure is a power of the authority to a believers. The whole practice is as a consciousness of the shadow the part of the files, in the battle of the meaning oforthodox the worship of the truth, shadows of the practice of the truths of the Consul. But the referred of the formation of the significant matter of the shadow of a understood and the critics of the attention. The a portion of the understanding of the meaning of the truthes, is an identical to the meaning of the dealings upon theray of the matter that is followed. With the possibility of a agrees of the truth as the experience of the truths of the word and the reaches index, although of the conviction of the Prayers of the sound of the particular victim as a meaning of the constants, a copy of the evils itself and the understanding of the the fines of a formation of the truth, of the truth in the hands, the partial of the mirrors of experience, the understanding of the matter of the means and regardless of the victim, and representing the source of the relations and the youth of the interpretation, and of his experience, and understanding the grace of a common deepen in the eyes of the hands. The word of the gates is to the hereas of the Mention of the God, and a photo of the meaning of night. The symbol from the understanding of the character of exchange of the book is the rhetorics of the statue of the immediate symbol of a portion on the panel of the location of the view is the evening of a word of understanding the necessarys of a sense of a dislike of the conditions, with the movements of light the heavens. At all the truth of a moment to the center of the contents of a pastor of a gate of the neck. Around the sources, and the defenders on the formation of the truth of understanding of the museum, and the pen truth of the sum of abes of the a noble entrance. The experience of the king of the truth remains in the neither view, he described from the text. Any the relation to fighting the end of the view of reality, the passage means of a thefile and ae of the the provision oftinehood. In the central understanding of the main understanding of the prides of the man, a permanent concentration, including a certain view of the Latin, and the force of the truth of the Greek translations and the portion of the ae does, it has to be a deep perspective. It is the horse of the failures of the the meaning of the mind and the truths and actions of a connection of mind and relevant to the understanding of the rhetoric lacks the truth of the truth. For here in the mind of worship is the rhetoric, including the hands of the awareness. Christ, the loss of the commons of the moment of the mind of life. As the practice of the Church as a transmission, as the outcome is a psychological power of height. When the request of the sense of the means of the friendship, relevant to the the covering of the a battery. The explanations the moment of the rule of a deep is imposed as a the Ghost of the evening of Nowadays, a return to the heavens in charge of the law. The best order to the function, the experience is a presence</s>
19
+ ===== sample 4 =====
20
+ head_tokens: [',', '▁but', ',', '▁to', '▁feature', '▁', 'a', '▁portion', '▁of', '▁their', '▁inequality', '.', '▁The', '▁town', '’', 's']
21
+ tail_tokens: ['s', '▁of', '▁the', '▁man', '▁', 'a', '▁writer', '▁of', '▁the', '▁Church', 's', ',', '▁with', '▁the', '▁self', '</s>']
22
+ , but, to feature a portion of their inequality. The town’s decision on this map, as viewed to the vision of the city of the Canadians. The scale of democracy it’s not only the horrors of a commonly property. It is not always, according to a motion of the state of the origins of all in the country of their own legislative. The vast vision of the text is the source of the office of the state population, in the name of the state and the state’s dozens of the significance of the department. One of the integrity of the governor’s value, it’s the evidence of a conflict, fit the lines of the state of citizen, a division that of a method of England by a documentance, the nation’s in the scope of the Bible, in its view. But it’s the understanding of mind is a psychological spite of the es of the defenders of the Constitution. Deaths in the district that’s the reflection of the text. Only the presence of the president’s connections to the center’s question. It’s this is the theGA of the presence of the nation’s visions. That’s explanation, the state’s date entirely, the author of the House of England’s excesss of the independent pleasure and laws. Just the royally to the center of the secret of the provinces. Only as the basis of the state’s construction phase captures the lack of control in the state of the Constitution in a place to the district in the state that’s a principle of the state of reforms in the presence of the state’s initial state. But the a bit of explanation as the contrasts of the heads of the entertainment, of this is not a problem. With a woman’s dream and a steep vision of a larger Lord. While objective of the classics, it’s not a patient in the coming convention. In the hand of the’s in the pres, there’s a collision of a mentes the tradition of thenian Republic. It’s a little tool that in a copy of the historians, neither of the truths of the left-casts on the top of the argument. It’s a management of this, it’s the view of a one’ history of the one’s point, and one that’s rank of the dies in the fact, it’s only a point of view, if it’s upon a rule of one’s grand critics and he learns a state of evils. s the reputation markedly to the end, he’s drawn of the citizens of the one that’s the book. In the70s, a stretch of the two truth, has been in the history of a description of a class-ad of life in the future, and a twist on the narrative’s relief of the truth. It’s corresponded to the truths of Oz, he’s masses, as the 1960s of meaning the Catholics and a possibility to the truth of style. By then, there is a spite of the workings of the universe, and there is a moment of their story. In all, the father’s a book with the falls of the core of the truth of truth as a result of the expansion of the particular story. He’s seen a piece of the full specvers of the universes on the truth of the power and his god. In the end, the lack of the Catholics in the hands of the system, who’s as a matter today, and a significant element of the uttersly. It’s the rages of the tortures a page of comparison, in a sound of Catholics and the end of the author. Some of the Bible’s quite ayed, of the Church of the mind in a different understanding of the aspects of being the truth of the Lord. It’s the misunderstandings. It’s the clear in the book that the slaves are drawn to the ens of the enquisical presence of ancient rituals in the Greeks. One of the universe of the Greeks as again, and it appears to keep the simultaneously and discipline of the reads. But the heart of the Church of the height of the Queens. It’s the idea of it’s the DNA as the eyes of the planet, and the authentic. It is decided to be in the beginning of chaos, the discipline of the power of the Christ. With a position of the fan, a judgment of the one’s of the man a writer of the Churchs, with the self</s>
23
+ ===== sample 5 =====
24
+ head_tokens: ['▁all', '▁of', '▁the', '▁wishes', '▁of', '▁the', '▁state', '▁of', '▁affection', '▁unit', 'e', 'd', '▁the', '▁metaphor', '▁of', '▁']
25
+ tail_tokens: ['s', '▁listen', '▁to', '▁the', '▁city', '.', '▁', 'Historically', '▁', 'he', '’', 's', '▁', 'a', '▁', '</s>']
26
+ all of the wishes of the state of affection united the metaphor of a village that’s the finalacy in the manner of the head of the state. It is a unit of the system and the purpose of the state. The rest of the state is classified in the conditions of the Agman’s democracy. In the date of the state is driven, and figures on the Bible’s of the places and the top of a the nation’s national society. In the contrast, the national classes in the era the Church’s the touch of choice of the Resolution itself, on the other part of the initials: the top of the punishment, and the depths of the interior and the size of the citizen’s functions of the author’ss. One of the provinces contained covered on a platform, and one of the Words of the seats. The poverty of tradition is a source’s a few more. Suddenly, this is a cross-factorant, and on the affection’s a method, in the entire state, as the expansion of all the poor and the pensions of a strategy the lack of the objective of the pictures is, adding to the role of the failures of a bit, but it is out to the ages of the law. Because of the inquiry of the debatehead, the total lack of a type of document, drassed in a state, as a reformer of law, and a crew of the legislaturemens of the powers of the priest’s works, and on the margins of the state. It’s never doubt that this is meaning, that that a sla’s covered, worthy from a state council in the courts. On the Bills of the law begins, the first elections, the boy recorded a large raid of the state a lot of the MPs. As a result, he’s not still a popular conviction of a father’s of the Weeks along the area. Now it’s easy, but in a meaning of a character’s the mouth of a state tool’s body bones, while fares in the state of one of the councils that he’s involved in a Biblical war. In the dream, a whole out of the city’s eightes the chiefs of the rebel’s homeland of the nation, the part of the nation’ssts. But that’s the capital of a planet. Unlike the neighborhood is, mourn, however, a monsterprimarily, in some of the tales, it’s a lack of anger, in the personality of the sath of the rays of the stands. Yet, he’s tell about, as a man at the top of the window. One of a fellow, some of him on a moment of the life, regardless, he’s a democracy, he sees the real emerges, highlightings the sides of the earthquakes and informing the streets. The sight of his vision is in a hy of the masses. It’s also looks to be expanded in the shadow of the Waters, he that’s the matters of the case. Not he’s to become the vision of the system’s homes, running on the figure of the army in adams of the Bostons. It’s not it’s a fruit a piece of ass nash, the mythation of the state’s view. But the she’s appeared to a labs. On a long-term, a metric he is a big top-ched shadow, and the regarded. pleasure is a bit of a car, as a part of his fellow dictt. But so, in the rest of this, it’s a nice reaction. Now to develop a quick off of the corner, it’s a loss to a thing in the’s ship, but it’s a real thing to imagine, but as a sort of an n, and that’s a rock. He’s going to have a guy who’s just in control of the underground writer’s view, he’s been a bit in a child’s the tail of the car, as by a pivotal box, a foots out the city’s car and the heads of the sport. He’s the pleasure of the movie in mind as a cigarette of the city. It’s the way that he is accused of him. Some of the cases, he’s listen to the city. Historically he’s a </s>
27
+ ===== sample 6 =====
28
+ head_tokens: ['▁experience', '▁of', '▁the', '▁same', '▁divine', '▁of', '▁classes', '▁or', '▁', 'he', 'e', 'd', '▁by', '▁the', '▁Church', '▁of']
29
+ tail_tokens: ['▁the', '▁function', '▁of', '▁the', '▁world', '▁of', '▁the', '▁', 've', 's', '▁of', '▁the', '▁gate', '▁in', '▁the', '</s>']
30
+ experience of the same divine of classes or heed by the Church of the narrative, he in the Church as a sense, and a source of a anotes to the truth of the Church of itself under the Church of the writings of repeat, and as a motion of the illries, the ongoing expression of the portion of the gates principal collapses from the account of the beings of the spirit of the Orthoggs, and then the particular acknowledges of a particular constant translation truth of the text of the constant account of the transmission, a legacy of thecans and meanings. By the law of a the account of account of the operation of power, by the admiss of the Church of the current understanding of the Constitution of the Bishop, and the understanding of the law, in the view of the spite of theative valley of the complete statutenets ster. It is apparentconstituted the convictions of the Elis of the truth of the center of the destruction of theed of the general authority of the present scope of the constants in the village of the achievement of his interest to the experience of a century. The more aspect of the guidance of understanding of the background of theacts of the ts of the eye, eventually compared to the hands of dynamic and the situation of thence of the elect, is a widespread support of the current master of the dozenes, and a removal of theclaving to the representation of the dus of the card. detail is a detail of the account of the ned upon the ned of the system of the auction model of the poor and the main account of the means of meaning in the merely a member of the subject to the situation of the property. Conion as a factor of conviction of the removing the entry of the human translations, in the collision of the diversity, along with the power of the ens of the truth, and the awaits of the understanding of the association, and the text of the derivatives of the es of the powers of the Church and state of the Museum of the tents of thetes of the bread the victim of the faithful of the connection of the forces with the powers of the village of the three territories. The the unprecedented battles, with the operation of the Catholicfall of the forced forces of the damnes of the Book of the offense. By theture of the pastors of the fact of the tender in the end of the virtue of the portion of the youths, in Church, by the battle of the church and scope of the representatives of the forces of the impulses, because of the pastor and description of the attention of the writings of truth of the object of the account of relations of the Constitution. This in the understanding of the scopes of the inner of the houses of the darks, due to the truth of those in the truths of the the forces of the cause of the forces, upon of the legacy of the number of property, and the partials of the Christs is to receiving in the crown of the hands of the night of the similarities of the moment of the truth of the conviction of the formations of the contents of the heaven. As its apparently explanation, ... in the legacy of the evidence of the explanations of the formation of the no masters of a deviation of presence is a clear relation of the explicit alphabets in Christ with the the Crown of the more truthly as a portion of the center of the present expression of the time of the text. The correct understanding of the state of the competitors of the the conditions of the explanations, as a reflection of the hands of the inens and the understanding of the explosion of bones of the regimes and the absence of the Saens of the authority. Following the designer of the preenatives of the operation, drawn to the Church of translation. On the background of servants of the inds of the partiales of the authority of authority of the truth’s count understanding of the Book of life. On the combination of the vi of the convictions of the state of the mind of thedox ritual is a matter of practice as a significant appearance of the exchange of the house of the Holy writer of text andclams to the extension of the wards of the letter of the experience of order and the meaning of the evidence, in the undict. Through the extension of the power of the myths and excludes the save of the function of the Battle realization of the abolishs of the cess, and tohers the property of the top of all the deep squares and from the hands of the battle of the awareness of truth as a part of the truth. The extension of the function of the world of the ves of the gate in the</s>
31
+ ===== sample 7 =====
32
+ head_tokens: ['▁overlook', '▁of', '▁the', '▁original', '▁death', '▁of', '▁control', '▁of', '▁the', '▁immediate', '▁detail', ',', '▁and', '▁the', '▁questions', '▁of']
33
+ tail_tokens: ['.', '▁Yet', '▁the', '▁function', '▁of', '▁the', '▁truth', '▁of', '▁the', '▁an', 'arch', 's', '▁in', '▁the', '▁final', '</s>']
34
+ overlook of the original death of control of the immediate detail, and the questions of penalties of that, in the hands of the present manner. There are part of a significant understanding of the Parts in the preparation of the understanding of Christ and the part of the forgotten in the errors of the ongoing truths in the finals. The order is a display of view, and in the principality of the original understanding of the control of view of the meaning of reading up the current Treasure of failures, with the forces of the constant consciousness of the formation. By in the account the account of the understanding of the demands of testament to the meaning of the approval of the capital of the apparent truthnotes in the teacher of the ortreated of the account of the Church of the s in the Popes of the voice in the understanding of the account as a notes of the prominents of the las. The answer, a confidence in the next account of the state of the Elield of in the letter of view, and the constant sum of the Church of the general authority of the law. The Holyity of the shadow of the realm of those in the evidence of the beings of the connection of the truth of the human size of the extraordinary details of the system. The date of the theories of the account of the Constitution of the teacher of dynamic, up to the nce of the Contention of the representatives of the sources of the master of theie of the property, and the contributions Questioning to the official account of the thetion of the Though detail, in the eyes of the account of Mormon, the immediate number of the priester of the edition of the led to the forces of the sources of the sources and the end of the morning in relation to the friendship of the constituents, and the cause of the property believers of the system contrasts the evidence of the Constitution of addressing the formation of service. addition, in control the result of the interior of understanding the remains of the provision in the Book of the pleasure of forgotten of the forces of the possibility of ounce upon the attention of the meanings of the truth and support of the Royal part of a index and the account of the marked tents to the truth of the Church of the tapes of the extension of the idea with the death of the concerned Christward, and without the understanding of the control, the electative of the extension of thefessions of the freedom. The the owner of the Church is not of the rhetoric of the attention of the authoritys and the 1920s. But on the thee of the dus of the youth of the spectrum of the crime in the size of the question of the gravitation of the forces of thekovs, because of the counteative of the representatives of the Christ of the divisions of the fault of God the relations, and the leadership of God of the system is organisationd as the evidence of parallel, and in the hands of the exchanges of the matters of the exchange to apply of the limits of the panel of the gate, which of the ease of speaking to the source of the theoretical whistles of protecting the truth to the receiving of the requiredes of the Church, from the ongoingimposed of the the concentration of the Book of the justices, with the contents of the account of the completes upon, as due to the legacy of the evidence of the truths view of the situation of the masters upon: with the constructions of the Orthodoxe in the disordinations., with the Constitution understanding of the regime of the authoritys of the truth of property of the royal of the unmonitice of the Hil correct, in the range of the Vicdox forces, in the grands of the bishops of the imposed in the request of the Crown, the understandings the means of the sums the power of the account of the Greek Christs of the actual issue, and in the absence of the officialation of the force of the wins of the the translation, on the background of the account of the receiving of the Constitution of the actuals of the authority of the realm of the ens of the Eastern enemy, as the as 21s of the viative. While the intense fras of the backgrounds of the remains, of the courts of the Church. Through the original death of thedom of the Book of the forward of the popular translation, as the extension of the feature of the referrede of the consciousness of the forces of the preward within the gate of the transmission. Note the extension of the description of the Eldersters of the entire law of the law, the hands of the gate, and thever the injustices of the extension and to the formation of the canen in the background of the Greek understandings of the hands of the conditions of the Constitution of the death in the Book of the awareness of the 13 question. Yet the function of the truth of the anarchs in the final</s>
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/noise_geometry_fixed_selfcond_ce_main_pow3.log ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [ckpt] runs/owt_t5_llmclean_qwen36_35b_articlefull_10k_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_40k_elfopt_t5embed_fixed_selfcond_ce_20260529_235541/step_002000.pt
2
+ [row] step_002000 pow3 t=0.000 c=1.00 ce=6.9830 acc=0.0409
3
+ [row] step_002000 pow3 t=0.020 c=1.00 ce=6.9808 acc=0.0413
4
+ [row] step_002000 pow3 t=0.040 c=1.00 ce=6.9726 acc=0.0424
5
+ [row] step_002000 pow3 t=0.060 c=1.00 ce=6.9525 acc=0.0454
6
+ [row] step_002000 pow3 t=0.080 c=1.00 ce=6.9219 acc=0.0494
7
+ [row] step_002000 pow3 t=0.100 c=1.01 ce=6.8708 acc=0.0555
8
+ [row] step_002000 pow3 t=0.120 c=1.01 ce=6.8077 acc=0.0633
9
+ [row] step_002000 pow3 t=0.140 c=1.02 ce=6.7267 acc=0.0727
10
+ [row] step_002000 pow3 t=0.160 c=1.03 ce=6.6298 acc=0.0836
11
+ [row] step_002000 pow3 t=0.180 c=1.04 ce=6.5191 acc=0.0967
12
+ [row] step_002000 pow3 t=0.200 c=1.06 ce=6.3882 acc=0.1112
13
+ [row] step_002000 pow3 t=0.220 c=1.08 ce=6.2493 acc=0.1268
14
+ [row] step_002000 pow3 t=0.240 c=1.10 ce=6.0975 acc=0.1438
15
+ [row] step_002000 pow3 t=0.260 c=1.13 ce=5.9212 acc=0.1626
16
+ [row] step_002000 pow3 t=0.280 c=1.16 ce=5.7472 acc=0.1821
17
+ [row] step_002000 pow3 t=0.300 c=1.21 ce=5.5434 acc=0.2045
18
+ [row] step_002000 pow3 t=0.320 c=1.25 ce=5.3278 acc=0.2278
19
+ [row] step_002000 pow3 t=0.340 c=1.31 ce=5.0961 acc=0.2531
20
+ [row] step_002000 pow3 t=0.360 c=1.38 ce=4.8456 acc=0.2806
21
+ [row] step_002000 pow3 t=0.380 c=1.46 ce=4.5896 acc=0.3103
22
+ [row] step_002000 pow3 t=0.400 c=1.56 ce=4.3180 acc=0.3416
23
+ [row] step_002000 pow3 t=0.420 c=1.67 ce=4.0419 acc=0.3752
24
+ [row] step_002000 pow3 t=0.440 c=1.80 ce=3.7634 acc=0.4093
25
+ [row] step_002000 pow3 t=0.460 c=1.96 ce=3.4769 acc=0.4456
26
+ [row] step_002000 pow3 t=0.480 c=2.15 ce=3.1880 acc=0.4835
27
+ [row] step_002000 pow3 t=0.500 c=2.38 ce=2.9057 acc=0.5217
28
+ [row] step_002000 pow3 t=0.520 c=2.65 ce=2.6252 acc=0.5607
29
+ [row] step_002000 pow3 t=0.540 c=2.98 ce=2.3657 acc=0.5983
30
+ [row] step_002000 pow3 t=0.560 c=3.38 ce=2.1193 acc=0.6350
31
+ [row] step_002000 pow3 t=0.580 c=3.87 ce=1.8865 acc=0.6706
32
+ [row] step_002000 pow3 t=0.600 c=4.47 ce=1.6771 acc=0.7030
33
+ [row] step_002000 pow3 t=0.620 c=5.22 ce=1.4909 acc=0.7328
34
+ [row] step_002000 pow3 t=0.640 c=6.15 ce=1.3287 acc=0.7591
35
+ [row] step_002000 pow3 t=0.660 c=7.34 ce=1.1882 acc=0.7821
36
+ [row] step_002000 pow3 t=0.680 c=8.84 ce=1.0618 acc=0.8031
37
+ [row] step_002000 pow3 t=0.700 c=10.78 ce=0.9542 acc=0.8210
38
+ [row] step_002000 pow3 t=0.720 c=13.29 ce=0.8599 acc=0.8375
39
+ [row] step_002000 pow3 t=0.740 c=16.59 ce=0.7687 acc=0.8534
40
+ [row] step_002000 pow3 t=0.760 c=20.96 ce=0.6859 acc=0.8682
41
+ [row] step_002000 pow3 t=0.780 c=26.83 ce=0.6099 acc=0.8818
42
+ [row] step_002000 pow3 t=0.800 c=34.78 ce=0.5381 acc=0.8949
43
+ [row] step_002000 pow3 t=0.820 c=45.69 ce=0.4667 acc=0.9080
44
+ [row] step_002000 pow3 t=0.840 c=60.84 ce=0.4026 acc=0.9202
45
+ [row] step_002000 pow3 t=0.860 c=82.17 ce=0.3422 acc=0.9316
46
+ [row] step_002000 pow3 t=0.880 c=112.57 ce=0.2860 acc=0.9426
47
+ [row] step_002000 pow3 t=0.900 c=156.50 ce=0.2301 acc=0.9534
48
+ [row] step_002000 pow3 t=0.920 c=220.84 ce=0.1787 acc=0.9637
49
+ [row] step_002000 pow3 t=0.940 c=316.45 ce=0.1303 acc=0.9734
50
+ [row] step_002000 pow3 t=0.960 c=460.60 ce=0.0851 acc=0.9826
51
+ [row] step_002000 pow3 t=0.980 c=681.19 ce=0.0422 acc=0.9914
52
+ [row] step_002000 pow3 t=1.000 c=1024.00 ce=0.0012 acc=0.9999
53
+ [ckpt] runs/owt_t5_llmclean_qwen36_35b_articlefull_10k_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_40k_elfopt_t5embed_fixed_selfcond_ce_20260529_235541/step_005000.pt
54
+ [row] step_005000 pow3 t=0.000 c=1.00 ce=6.8106 acc=0.0409
55
+ [row] step_005000 pow3 t=0.020 c=1.00 ce=6.8092 acc=0.0412
56
+ [row] step_005000 pow3 t=0.040 c=1.00 ce=6.8022 acc=0.0425
57
+ [row] step_005000 pow3 t=0.060 c=1.00 ce=6.7813 acc=0.0455
58
+ [row] step_005000 pow3 t=0.080 c=1.00 ce=6.7479 acc=0.0500
59
+ [row] step_005000 pow3 t=0.100 c=1.01 ce=6.6997 acc=0.0559
60
+ [row] step_005000 pow3 t=0.120 c=1.01 ce=6.6279 acc=0.0642
61
+ [row] step_005000 pow3 t=0.140 c=1.02 ce=6.5366 acc=0.0745
62
+ [row] step_005000 pow3 t=0.160 c=1.03 ce=6.4279 acc=0.0867
63
+ [row] step_005000 pow3 t=0.180 c=1.04 ce=6.2985 acc=0.1006
64
+ [row] step_005000 pow3 t=0.200 c=1.06 ce=6.1569 acc=0.1157
65
+ [row] step_005000 pow3 t=0.220 c=1.08 ce=5.9878 acc=0.1331
66
+ [row] step_005000 pow3 t=0.240 c=1.10 ce=5.7966 acc=0.1524
67
+ [row] step_005000 pow3 t=0.260 c=1.13 ce=5.5957 acc=0.1726
68
+ [row] step_005000 pow3 t=0.280 c=1.16 ce=5.3803 acc=0.1946
69
+ [row] step_005000 pow3 t=0.300 c=1.21 ce=5.1542 acc=0.2183
70
+ [row] step_005000 pow3 t=0.320 c=1.25 ce=4.9148 acc=0.2432
71
+ [row] step_005000 pow3 t=0.340 c=1.31 ce=4.6641 acc=0.2706
72
+ [row] step_005000 pow3 t=0.360 c=1.38 ce=4.3992 acc=0.3003
73
+ [row] step_005000 pow3 t=0.380 c=1.46 ce=4.1299 acc=0.3316
74
+ [row] step_005000 pow3 t=0.400 c=1.56 ce=3.8557 acc=0.3647
75
+ [row] step_005000 pow3 t=0.420 c=1.67 ce=3.5640 acc=0.4020
76
+ [row] step_005000 pow3 t=0.440 c=1.80 ce=3.2685 acc=0.4404
77
+ [row] step_005000 pow3 t=0.460 c=1.96 ce=2.9732 acc=0.4805
78
+ [row] step_005000 pow3 t=0.480 c=2.15 ce=2.6841 acc=0.5216
79
+ [row] step_005000 pow3 t=0.500 c=2.38 ce=2.3960 acc=0.5636
80
+ [row] step_005000 pow3 t=0.520 c=2.65 ce=2.1296 acc=0.6044
81
+ [row] step_005000 pow3 t=0.540 c=2.98 ce=1.8707 acc=0.6451
82
+ [row] step_005000 pow3 t=0.560 c=3.38 ce=1.6278 acc=0.6850
83
+ [row] step_005000 pow3 t=0.580 c=3.87 ce=1.4151 acc=0.7206
84
+ [row] step_005000 pow3 t=0.600 c=4.47 ce=1.2261 acc=0.7534
85
+ [row] step_005000 pow3 t=0.620 c=5.22 ce=1.0634 acc=0.7826
86
+ [row] step_005000 pow3 t=0.640 c=6.15 ce=0.9214 acc=0.8086
87
+ [row] step_005000 pow3 t=0.660 c=7.34 ce=0.8065 acc=0.8301
88
+ [row] step_005000 pow3 t=0.680 c=8.84 ce=0.7069 acc=0.8492
89
+ [row] step_005000 pow3 t=0.700 c=10.78 ce=0.6216 acc=0.8656
90
+ [row] step_005000 pow3 t=0.720 c=13.29 ce=0.5485 acc=0.8800
91
+ [row] step_005000 pow3 t=0.740 c=16.59 ce=0.4830 acc=0.8935
92
+ [row] step_005000 pow3 t=0.760 c=20.96 ce=0.4241 acc=0.9056
93
+ [row] step_005000 pow3 t=0.780 c=26.83 ce=0.3679 acc=0.9171
94
+ [row] step_005000 pow3 t=0.800 c=34.78 ce=0.3196 acc=0.9274
95
+ [row] step_005000 pow3 t=0.820 c=45.69 ce=0.2727 acc=0.9377
96
+ [row] step_005000 pow3 t=0.840 c=60.84 ce=0.2275 acc=0.9472
97
+ [row] step_005000 pow3 t=0.860 c=82.17 ce=0.1908 acc=0.9554
98
+ [row] step_005000 pow3 t=0.880 c=112.57 ce=0.1554 acc=0.9634
99
+ [row] step_005000 pow3 t=0.900 c=156.50 ce=0.1220 acc=0.9709
100
+ [row] step_005000 pow3 t=0.920 c=220.84 ce=0.0924 acc=0.9778
101
+ [row] step_005000 pow3 t=0.940 c=316.45 ce=0.0662 acc=0.9840
102
+ [row] step_005000 pow3 t=0.960 c=460.60 ce=0.0421 acc=0.9898
103
+ [row] step_005000 pow3 t=0.980 c=681.19 ce=0.0201 acc=0.9951
104
+ [row] step_005000 pow3 t=1.000 c=1024.00 ce=0.0005 acc=1.0000
105
+ [ckpt] runs/owt_t5_llmclean_qwen36_35b_articlefull_10k_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_40k_elfopt_t5embed_fixed_selfcond_ce_20260529_235541/step_010000.pt
106
+ [row] step_010000 pow3 t=0.000 c=1.00 ce=6.7841 acc=0.0420
107
+ [row] step_010000 pow3 t=0.020 c=1.00 ce=6.7828 acc=0.0423
108
+ [row] step_010000 pow3 t=0.040 c=1.00 ce=6.7756 acc=0.0435
109
+ [row] step_010000 pow3 t=0.060 c=1.00 ce=6.7527 acc=0.0463
110
+ [row] step_010000 pow3 t=0.080 c=1.00 ce=6.7135 acc=0.0508
111
+ [row] step_010000 pow3 t=0.100 c=1.01 ce=6.6565 acc=0.0565
112
+ [row] step_010000 pow3 t=0.120 c=1.01 ce=6.5759 acc=0.0650
113
+ [row] step_010000 pow3 t=0.140 c=1.02 ce=6.4787 acc=0.0745
114
+ [row] step_010000 pow3 t=0.160 c=1.03 ce=6.3468 acc=0.0870
115
+ [row] step_010000 pow3 t=0.180 c=1.04 ce=6.2007 acc=0.1007
116
+ [row] step_010000 pow3 t=0.200 c=1.06 ce=6.0199 acc=0.1174
117
+ [row] step_010000 pow3 t=0.220 c=1.08 ce=5.8302 acc=0.1353
118
+ [row] step_010000 pow3 t=0.240 c=1.10 ce=5.6117 acc=0.1552
119
+ [row] step_010000 pow3 t=0.260 c=1.13 ce=5.3787 acc=0.1773
120
+ [row] step_010000 pow3 t=0.280 c=1.16 ce=5.1484 acc=0.1998
121
+ [row] step_010000 pow3 t=0.300 c=1.21 ce=4.8939 acc=0.2251
122
+ [row] step_010000 pow3 t=0.320 c=1.25 ce=4.6310 acc=0.2525
123
+ [row] step_010000 pow3 t=0.340 c=1.31 ce=4.3488 acc=0.2830
124
+ [row] step_010000 pow3 t=0.360 c=1.38 ce=4.0653 acc=0.3156
125
+ [row] step_010000 pow3 t=0.380 c=1.46 ce=3.7645 acc=0.3510
126
+ [row] step_010000 pow3 t=0.400 c=1.56 ce=3.4676 acc=0.3891
127
+ [row] step_010000 pow3 t=0.420 c=1.67 ce=3.1695 acc=0.4283
128
+ [row] step_010000 pow3 t=0.440 c=1.80 ce=2.8589 acc=0.4718
129
+ [row] step_010000 pow3 t=0.460 c=1.96 ce=2.5643 acc=0.5148
130
+ [row] step_010000 pow3 t=0.480 c=2.15 ce=2.2657 acc=0.5610
131
+ [row] step_010000 pow3 t=0.500 c=2.38 ce=1.9896 acc=0.6051
132
+ [row] step_010000 pow3 t=0.520 c=2.65 ce=1.7254 acc=0.6489
133
+ [row] step_010000 pow3 t=0.540 c=2.98 ce=1.4856 acc=0.6903
134
+ [row] step_010000 pow3 t=0.560 c=3.38 ce=1.2707 acc=0.7294
135
+ [row] step_010000 pow3 t=0.580 c=3.87 ce=1.0751 acc=0.7660
136
+ [row] step_010000 pow3 t=0.600 c=4.47 ce=0.9078 acc=0.7983
137
+ [row] step_010000 pow3 t=0.620 c=5.22 ce=0.7666 acc=0.8264
138
+ [row] step_010000 pow3 t=0.640 c=6.15 ce=0.6524 acc=0.8498
139
+ [row] step_010000 pow3 t=0.660 c=7.34 ce=0.5580 acc=0.8698
140
+ [row] step_010000 pow3 t=0.680 c=8.84 ce=0.4788 acc=0.8866
141
+ [row] step_010000 pow3 t=0.700 c=10.78 ce=0.4129 acc=0.9010
142
+ [row] step_010000 pow3 t=0.720 c=13.29 ce=0.3604 acc=0.9129
143
+ [row] step_010000 pow3 t=0.740 c=16.59 ce=0.3099 acc=0.9242
144
+ [row] step_010000 pow3 t=0.760 c=20.96 ce=0.2657 acc=0.9343
145
+ [row] step_010000 pow3 t=0.780 c=26.83 ce=0.2259 acc=0.9438
146
+ [row] step_010000 pow3 t=0.800 c=34.78 ce=0.1936 acc=0.9512
147
+ [row] step_010000 pow3 t=0.820 c=45.69 ce=0.1609 acc=0.9592
148
+ [row] step_010000 pow3 t=0.840 c=60.84 ce=0.1330 acc=0.9659
149
+ [row] step_010000 pow3 t=0.860 c=82.17 ce=0.1085 acc=0.9720
150
+ [row] step_010000 pow3 t=0.880 c=112.57 ce=0.0869 acc=0.9773
151
+ [row] step_010000 pow3 t=0.900 c=156.50 ce=0.0661 acc=0.9827
152
+ [row] step_010000 pow3 t=0.920 c=220.84 ce=0.0489 acc=0.9871
153
+ [row] step_010000 pow3 t=0.940 c=316.45 ce=0.0339 acc=0.9910
154
+ [row] step_010000 pow3 t=0.960 c=460.60 ce=0.0206 acc=0.9945
155
+ [row] step_010000 pow3 t=0.980 c=681.19 ce=0.0097 acc=0.9974
156
+ [row] step_010000 pow3 t=1.000 c=1024.00 ce=0.0003 acc=1.0000
157
+ [ckpt] runs/owt_t5_llmclean_qwen36_35b_articlefull_10k_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_40k_elfopt_t5embed_fixed_selfcond_ce_20260529_235541/step_020000.pt
158
+ [row] step_020000 pow3 t=0.000 c=1.00 ce=6.7813 acc=0.0420
159
+ [row] step_020000 pow3 t=0.020 c=1.00 ce=6.7806 acc=0.0423
160
+ [row] step_020000 pow3 t=0.040 c=1.00 ce=6.7729 acc=0.0437
161
+ [row] step_020000 pow3 t=0.060 c=1.00 ce=6.7502 acc=0.0467
162
+ [row] step_020000 pow3 t=0.080 c=1.00 ce=6.7082 acc=0.0513
163
+ [row] step_020000 pow3 t=0.100 c=1.01 ce=6.6470 acc=0.0574
164
+ [row] step_020000 pow3 t=0.120 c=1.01 ce=6.5622 acc=0.0661
165
+ [row] step_020000 pow3 t=0.140 c=1.02 ce=6.4473 acc=0.0765
166
+ [row] step_020000 pow3 t=0.160 c=1.03 ce=6.3089 acc=0.0881
167
+ [row] step_020000 pow3 t=0.180 c=1.04 ce=6.1278 acc=0.1032
168
+ [row] step_020000 pow3 t=0.200 c=1.06 ce=5.9404 acc=0.1189
169
+ [row] step_020000 pow3 t=0.220 c=1.08 ce=5.6683 acc=0.1397
170
+ [row] step_020000 pow3 t=0.240 c=1.10 ce=5.4254 acc=0.1607
171
+ [row] step_020000 pow3 t=0.260 c=1.13 ce=5.1573 acc=0.1839
172
+ [row] step_020000 pow3 t=0.280 c=1.16 ce=4.8531 acc=0.2113
173
+ [row] step_020000 pow3 t=0.300 c=1.21 ce=4.5496 acc=0.2407
174
+ [row] step_020000 pow3 t=0.320 c=1.25 ce=4.2452 acc=0.2716
175
+ [row] step_020000 pow3 t=0.340 c=1.31 ce=3.8911 acc=0.3099
176
+ [row] step_020000 pow3 t=0.360 c=1.38 ce=3.5783 acc=0.3473
177
+ [row] step_020000 pow3 t=0.380 c=1.46 ce=3.2466 acc=0.3903
178
+ [row] step_020000 pow3 t=0.400 c=1.56 ce=2.9136 acc=0.4359
179
+ [row] step_020000 pow3 t=0.420 c=1.67 ce=2.6019 acc=0.4822
180
+ [row] step_020000 pow3 t=0.440 c=1.80 ce=2.2779 acc=0.5320
181
+ [row] step_020000 pow3 t=0.460 c=1.96 ce=1.9928 acc=0.5790
182
+ [row] step_020000 pow3 t=0.480 c=2.15 ce=1.7190 acc=0.6269
183
+ [row] step_020000 pow3 t=0.500 c=2.38 ce=1.4724 acc=0.6720
184
+ [row] step_020000 pow3 t=0.520 c=2.65 ce=1.2387 acc=0.7166
185
+ [row] step_020000 pow3 t=0.540 c=2.98 ce=1.0377 acc=0.7569
186
+ [row] step_020000 pow3 t=0.560 c=3.38 ce=0.8661 acc=0.7923
187
+ [row] step_020000 pow3 t=0.580 c=3.87 ce=0.7139 acc=0.8251
188
+ [row] step_020000 pow3 t=0.600 c=4.47 ce=0.5924 acc=0.8524
189
+ [row] step_020000 pow3 t=0.620 c=5.22 ce=0.4892 acc=0.8760
190
+ [row] step_020000 pow3 t=0.640 c=6.15 ce=0.4044 acc=0.8957
191
+ [row] step_020000 pow3 t=0.660 c=7.34 ce=0.3401 acc=0.9113
192
+ [row] step_020000 pow3 t=0.680 c=8.84 ce=0.2875 acc=0.9243
193
+ [row] step_020000 pow3 t=0.700 c=10.78 ce=0.2449 acc=0.9347
194
+ [row] step_020000 pow3 t=0.720 c=13.29 ce=0.2071 acc=0.9443
195
+ [row] step_020000 pow3 t=0.740 c=16.59 ce=0.1761 acc=0.9522
196
+ [row] step_020000 pow3 t=0.760 c=20.96 ce=0.1496 acc=0.9590
197
+ [row] step_020000 pow3 t=0.780 c=26.83 ce=0.1264 acc=0.9653
198
+ [row] step_020000 pow3 t=0.800 c=34.78 ce=0.1043 acc=0.9712
199
+ [row] step_020000 pow3 t=0.820 c=45.69 ce=0.0858 acc=0.9760
200
+ [row] step_020000 pow3 t=0.840 c=60.84 ce=0.0695 acc=0.9804
201
+ [row] step_020000 pow3 t=0.860 c=82.17 ce=0.0552 acc=0.9844
202
+ [row] step_020000 pow3 t=0.880 c=112.57 ce=0.0433 acc=0.9877
203
+ [row] step_020000 pow3 t=0.900 c=156.50 ce=0.0324 acc=0.9908
204
+ [row] step_020000 pow3 t=0.920 c=220.84 ce=0.0234 acc=0.9933
205
+ [row] step_020000 pow3 t=0.940 c=316.45 ce=0.0157 acc=0.9955
206
+ [row] step_020000 pow3 t=0.960 c=460.60 ce=0.0095 acc=0.9973
207
+ [row] step_020000 pow3 t=0.980 c=681.19 ce=0.0044 acc=0.9987
208
+ [row] step_020000 pow3 t=1.000 c=1024.00 ce=0.0002 acc=1.0000
209
+ [ckpt] runs/owt_t5_llmclean_qwen36_35b_articlefull_10k_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_40k_elfopt_t5embed_fixed_selfcond_ce_20260529_235541/step_040000.pt
210
+ [row] step_040000 pow3 t=0.000 c=1.00 ce=6.7724 acc=0.0417
211
+ [row] step_040000 pow3 t=0.020 c=1.00 ce=6.7711 acc=0.0419
212
+ [row] step_040000 pow3 t=0.040 c=1.00 ce=6.7627 acc=0.0432
213
+ [row] step_040000 pow3 t=0.060 c=1.00 ce=6.7389 acc=0.0464
214
+ [row] step_040000 pow3 t=0.080 c=1.00 ce=6.7019 acc=0.0507
215
+ [row] step_040000 pow3 t=0.100 c=1.01 ce=6.6330 acc=0.0572
216
+ [row] step_040000 pow3 t=0.120 c=1.01 ce=6.5428 acc=0.0654
217
+ [row] step_040000 pow3 t=0.140 c=1.02 ce=6.4288 acc=0.0760
218
+ [row] step_040000 pow3 t=0.160 c=1.03 ce=6.2732 acc=0.0888
219
+ [row] step_040000 pow3 t=0.180 c=1.04 ce=6.0878 acc=0.1034
220
+ [row] step_040000 pow3 t=0.200 c=1.06 ce=5.8291 acc=0.1224
221
+ [row] step_040000 pow3 t=0.220 c=1.08 ce=5.6040 acc=0.1413
222
+ [row] step_040000 pow3 t=0.240 c=1.10 ce=5.2579 acc=0.1667
223
+ [row] step_040000 pow3 t=0.260 c=1.13 ce=4.9081 acc=0.1966
224
+ [row] step_040000 pow3 t=0.280 c=1.16 ce=4.5561 acc=0.2279
225
+ [row] step_040000 pow3 t=0.300 c=1.21 ce=4.2154 acc=0.2628
226
+ [row] step_040000 pow3 t=0.320 c=1.25 ce=3.7887 acc=0.3072
227
+ [row] step_040000 pow3 t=0.340 c=1.31 ce=3.4414 acc=0.3486
228
+ [row] step_040000 pow3 t=0.360 c=1.38 ce=3.0283 acc=0.4014
229
+ [row] step_040000 pow3 t=0.380 c=1.46 ce=2.6739 acc=0.4517
230
+ [row] step_040000 pow3 t=0.400 c=1.56 ce=2.2996 acc=0.5093
231
+ [row] step_040000 pow3 t=0.420 c=1.67 ce=1.9696 acc=0.5642
232
+ [row] step_040000 pow3 t=0.440 c=1.80 ce=1.6642 acc=0.6187
233
+ [row] step_040000 pow3 t=0.460 c=1.96 ce=1.4070 acc=0.6681
234
+ [row] step_040000 pow3 t=0.480 c=2.15 ce=1.1724 acc=0.7152
235
+ [row] step_040000 pow3 t=0.500 c=2.38 ce=0.9526 acc=0.7613
236
+ [row] step_040000 pow3 t=0.520 c=2.65 ce=0.7835 acc=0.7992
237
+ [row] step_040000 pow3 t=0.540 c=2.98 ce=0.6332 acc=0.8340
238
+ [row] step_040000 pow3 t=0.560 c=3.38 ce=0.5082 acc=0.8642
239
+ [row] step_040000 pow3 t=0.580 c=3.87 ce=0.4092 acc=0.8885
240
+ [row] step_040000 pow3 t=0.600 c=4.47 ce=0.3269 acc=0.9096
241
+ [row] step_040000 pow3 t=0.620 c=5.22 ce=0.2643 acc=0.9259
242
+ [row] step_040000 pow3 t=0.640 c=6.15 ce=0.2158 acc=0.9389
243
+ [row] step_040000 pow3 t=0.660 c=7.34 ce=0.1787 acc=0.9490
244
+ [row] step_040000 pow3 t=0.680 c=8.84 ce=0.1470 acc=0.9575
245
+ [row] step_040000 pow3 t=0.700 c=10.78 ce=0.1231 acc=0.9643
246
+ [row] step_040000 pow3 t=0.720 c=13.29 ce=0.1030 acc=0.9699
247
+ [row] step_040000 pow3 t=0.740 c=16.59 ce=0.0865 acc=0.9747
248
+ [row] step_040000 pow3 t=0.760 c=20.96 ce=0.0721 acc=0.9788
249
+ [row] step_040000 pow3 t=0.780 c=26.83 ce=0.0596 acc=0.9825
250
+ [row] step_040000 pow3 t=0.800 c=34.78 ce=0.0499 acc=0.9853
251
+ [row] step_040000 pow3 t=0.820 c=45.69 ce=0.0401 acc=0.9880
252
+ [row] step_040000 pow3 t=0.840 c=60.84 ce=0.0317 acc=0.9906
253
+ [row] step_040000 pow3 t=0.860 c=82.17 ce=0.0253 acc=0.9924
254
+ [row] step_040000 pow3 t=0.880 c=112.57 ce=0.0192 acc=0.9943
255
+ [row] step_040000 pow3 t=0.900 c=156.50 ce=0.0149 acc=0.9956
256
+ [row] step_040000 pow3 t=0.920 c=220.84 ce=0.0104 acc=0.9969
257
+ [row] step_040000 pow3 t=0.940 c=316.45 ce=0.0070 acc=0.9979
258
+ [row] step_040000 pow3 t=0.960 c=460.60 ce=0.0043 acc=0.9987
259
+ [row] step_040000 pow3 t=0.980 c=681.19 ce=0.0020 acc=0.9994
260
+ [row] step_040000 pow3 t=1.000 c=1024.00 ce=0.0002 acc=1.0000
261
+ wrote ../docs/lta_samples/metrics_20260531/noise_geometry_fixed_selfcond_ce_main/pow3/noise_geometry.tsv