ZTWHHH commited on
Commit
db5a53b
·
verified ·
1 Parent(s): b57b437

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/__init__.cpython-310.pyc +0 -0
  2. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/_bsdf.cpython-310.pyc +0 -0
  3. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/_freeimage.cpython-310.pyc +0 -0
  4. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/dicom.cpython-310.pyc +0 -0
  5. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/example.cpython-310.pyc +0 -0
  6. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/ffmpeg.cpython-310.pyc +0 -0
  7. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/freeimage.cpython-310.pyc +0 -0
  8. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/freeimagemulti.cpython-310.pyc +0 -0
  9. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/gdal.cpython-310.pyc +0 -0
  10. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/lytro.cpython-310.pyc +0 -0
  11. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/opencv.cpython-310.pyc +0 -0
  12. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow.cpython-310.pyc +0 -0
  13. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_info.cpython-310.pyc +0 -0
  14. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_legacy.cpython-310.pyc +0 -0
  15. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillowmulti.cpython-310.pyc +0 -0
  16. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/rawpy.cpython-310.pyc +0 -0
  17. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc +0 -0
  18. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/spe.cpython-310.pyc +0 -0
  19. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile.cpython-310.pyc +0 -0
  20. minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile_v3.cpython-310.pyc +0 -0
  21. minigpt2/lib/python3.10/site-packages/imageio/plugins/_swf.py +897 -0
  22. minigpt2/lib/python3.10/site-packages/imageio/plugins/example.py +145 -0
  23. minigpt2/lib/python3.10/site-packages/imageio/plugins/lytro.py +714 -0
  24. minigpt2/lib/python3.10/site-packages/imageio/plugins/tifffile.py +561 -0
  25. minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/__init__.cpython-310.pyc +0 -0
  26. minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/base_collective_group.cpython-310.pyc +0 -0
  27. minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/cuda_stream.cpython-310.pyc +0 -0
  28. minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/gloo_collective_group.cpython-310.pyc +0 -0
  29. minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/gloo_util.cpython-310.pyc +0 -0
  30. minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/nccl_util.cpython-310.pyc +0 -0
  31. minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/__init__.py +5 -0
  32. minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/__pycache__/__init__.cpython-310.pyc +0 -0
  33. minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/__pycache__/pool.cpython-310.pyc +0 -0
  34. minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/pool.py +995 -0
  35. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_ops.h +50 -0
  36. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half_compositeimplicitautograd_dispatch.h +23 -0
  37. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Int_native.h +21 -0
  38. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_conj_physical.h +39 -0
  39. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_convolution_double_backward_native.h +21 -0
  40. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_affine_quantized_cpu_dispatch.h +26 -0
  41. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_add.h +101 -0
  42. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_softmax_backward_cpu_dispatch.h +23 -0
  43. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_native_multi_head_attention_compositeexplicitautograd_dispatch.h +24 -0
  44. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_mask_ops.h +39 -0
  45. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward_ops.h +28 -0
  46. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_broadcast_to_copy_ops.h +39 -0
  47. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_compressed_tensor_with_dims_compositeexplicitautograd_dispatch.h +24 -0
  48. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact2d_cuda_dispatch.h +28 -0
  49. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/ccol_indices_ops.h +28 -0
  50. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/fft_ifft2.h +91 -0
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.29 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/_bsdf.cpython-310.pyc ADDED
Binary file (25.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/_freeimage.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/dicom.cpython-310.pyc ADDED
Binary file (7.99 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/example.cpython-310.pyc ADDED
Binary file (3.42 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/ffmpeg.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/freeimage.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/freeimagemulti.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/gdal.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/lytro.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/opencv.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow.cpython-310.pyc ADDED
Binary file (18.5 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_info.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillow_legacy.cpython-310.pyc ADDED
Binary file (23.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/pillowmulti.cpython-310.pyc ADDED
Binary file (9.27 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/rawpy.cpython-310.pyc ADDED
Binary file (5.14 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/spe.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/tifffile_v3.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/_swf.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+ # This code was taken from https://github.com/almarklein/visvis/blob/master/vvmovie/images2swf.py
4
+
5
+ # styletest: ignore E261
6
+
7
+ """
8
+ Provides a function (write_swf) to store a series of numpy arrays in an
9
+ SWF movie, that can be played on a wide range of OS's.
10
+
11
+ In desperation of wanting to share animated images, and then lacking a good
12
+ writer for animated gif or .avi, I decided to look into SWF. This format
13
+ is very well documented.
14
+
15
+ This is a pure python module to create an SWF file that shows a series
16
+ of images. The images are stored using the DEFLATE algorithm (same as
17
+ PNG and ZIP and which is included in the standard Python distribution).
18
+ As this compression algorithm is much more effective than that used in
19
+ GIF images, we obtain better quality (24 bit colors + alpha channel)
20
+ while still producesing smaller files (a test showed ~75%). Although
21
+ SWF also allows for JPEG compression, doing so would probably require
22
+ a third party library for the JPEG encoding/decoding, we could
23
+ perhaps do this via Pillow or freeimage.
24
+
25
+ sources and tools:
26
+
27
+ - SWF on wikipedia
28
+ - Adobes "SWF File Format Specification" version 10
29
+ (http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf)
30
+ - swftools (swfdump in specific) for debugging
31
+ - iwisoft swf2avi can be used to convert swf to avi/mpg/flv with really
32
+ good quality, while file size is reduced with factors 20-100.
33
+ A good program in my opinion. The free version has the limitation
34
+ of a watermark in the upper left corner.
35
+
36
+ """
37
+
38
+ import os
39
+ import zlib
40
+ import time # noqa
41
+ import logging
42
+
43
+ import numpy as np
44
+
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ # todo: use Pillow to support reading JPEG images from SWF?
49
+
50
+
51
+ # Base functions and classes
52
+
53
+
54
+ class BitArray:
55
+ """Dynamic array of bits that automatically resizes
56
+ with factors of two.
57
+ Append bits using .append() or +=
58
+ You can reverse bits using .reverse()
59
+ """
60
+
61
+ def __init__(self, initvalue=None):
62
+ self.data = np.zeros((16,), dtype=np.uint8)
63
+ self._len = 0
64
+ if initvalue is not None:
65
+ self.append(initvalue)
66
+
67
+ def __len__(self):
68
+ return self._len # self.data.shape[0]
69
+
70
+ def __repr__(self):
71
+ return self.data[: self._len].tobytes().decode("ascii")
72
+
73
+ def _checkSize(self):
74
+ # check length... grow if necessary
75
+ arraylen = self.data.shape[0]
76
+ if self._len >= arraylen:
77
+ tmp = np.zeros((arraylen * 2,), dtype=np.uint8)
78
+ tmp[: self._len] = self.data[: self._len]
79
+ self.data = tmp
80
+
81
+ def __add__(self, value):
82
+ self.append(value)
83
+ return self
84
+
85
+ def append(self, bits):
86
+ # check input
87
+ if isinstance(bits, BitArray):
88
+ bits = str(bits)
89
+ if isinstance(bits, int): # pragma: no cover - we dont use it
90
+ bits = str(bits)
91
+ if not isinstance(bits, str): # pragma: no cover
92
+ raise ValueError("Append bits as strings or integers!")
93
+
94
+ # add bits
95
+ for bit in bits:
96
+ self.data[self._len] = ord(bit)
97
+ self._len += 1
98
+ self._checkSize()
99
+
100
+ def reverse(self):
101
+ """In-place reverse."""
102
+ tmp = self.data[: self._len].copy()
103
+ self.data[: self._len] = tmp[::-1]
104
+
105
+ def tobytes(self):
106
+ """Convert to bytes. If necessary,
107
+ zeros are padded to the end (right side).
108
+ """
109
+ bits = str(self)
110
+
111
+ # determine number of bytes
112
+ nbytes = 0
113
+ while nbytes * 8 < len(bits):
114
+ nbytes += 1
115
+ # pad
116
+ bits = bits.ljust(nbytes * 8, "0")
117
+
118
+ # go from bits to bytes
119
+ bb = bytes()
120
+ for i in range(nbytes):
121
+ tmp = int(bits[i * 8 : (i + 1) * 8], 2)
122
+ bb += int2uint8(tmp)
123
+
124
+ # done
125
+ return bb
126
+
127
+
128
+ def int2uint32(i):
129
+ return int(i).to_bytes(4, "little")
130
+
131
+
132
+ def int2uint16(i):
133
+ return int(i).to_bytes(2, "little")
134
+
135
+
136
+ def int2uint8(i):
137
+ return int(i).to_bytes(1, "little")
138
+
139
+
140
+ def int2bits(i, n=None):
141
+ """convert int to a string of bits (0's and 1's in a string),
142
+ pad to n elements. Convert back using int(ss,2)."""
143
+ ii = i
144
+
145
+ # make bits
146
+ bb = BitArray()
147
+ while ii > 0:
148
+ bb += str(ii % 2)
149
+ ii = ii >> 1
150
+ bb.reverse()
151
+
152
+ # justify
153
+ if n is not None:
154
+ if len(bb) > n: # pragma: no cover
155
+ raise ValueError("int2bits fail: len larger than padlength.")
156
+ bb = str(bb).rjust(n, "0")
157
+
158
+ # done
159
+ return BitArray(bb)
160
+
161
+
162
+ def bits2int(bb, n=8):
163
+ # Init
164
+ value = ""
165
+
166
+ # Get value in bits
167
+ for i in range(len(bb)):
168
+ b = bb[i : i + 1]
169
+ tmp = bin(ord(b))[2:]
170
+ # value += tmp.rjust(8,'0')
171
+ value = tmp.rjust(8, "0") + value
172
+
173
+ # Make decimal
174
+ return int(value[:n], 2)
175
+
176
+
177
+ def get_type_and_len(bb):
178
+ """bb should be 6 bytes at least
179
+ Return (type, length, length_of_full_tag)
180
+ """
181
+ # Init
182
+ value = ""
183
+
184
+ # Get first 16 bits
185
+ for i in range(2):
186
+ b = bb[i : i + 1]
187
+ tmp = bin(ord(b))[2:]
188
+ # value += tmp.rjust(8,'0')
189
+ value = tmp.rjust(8, "0") + value
190
+
191
+ # Get type and length
192
+ type = int(value[:10], 2)
193
+ L = int(value[10:], 2)
194
+ L2 = L + 2
195
+
196
+ # Long tag header?
197
+ if L == 63: # '111111'
198
+ value = ""
199
+ for i in range(2, 6):
200
+ b = bb[i : i + 1] # becomes a single-byte bytes()
201
+ tmp = bin(ord(b))[2:]
202
+ # value += tmp.rjust(8,'0')
203
+ value = tmp.rjust(8, "0") + value
204
+ L = int(value, 2)
205
+ L2 = L + 6
206
+
207
+ # Done
208
+ return type, L, L2
209
+
210
+
211
+ def signedint2bits(i, n=None):
212
+ """convert signed int to a string of bits (0's and 1's in a string),
213
+ pad to n elements. Negative numbers are stored in 2's complement bit
214
+ patterns, thus positive numbers always start with a 0.
215
+ """
216
+
217
+ # negative number?
218
+ ii = i
219
+ if i < 0:
220
+ # A negative number, -n, is represented as the bitwise opposite of
221
+ ii = abs(ii) - 1 # the positive-zero number n-1.
222
+
223
+ # make bits
224
+ bb = BitArray()
225
+ while ii > 0:
226
+ bb += str(ii % 2)
227
+ ii = ii >> 1
228
+ bb.reverse()
229
+
230
+ # justify
231
+ bb = "0" + str(bb) # always need the sign bit in front
232
+ if n is not None:
233
+ if len(bb) > n: # pragma: no cover
234
+ raise ValueError("signedint2bits fail: len larger than padlength.")
235
+ bb = bb.rjust(n, "0")
236
+
237
+ # was it negative? (then opposite bits)
238
+ if i < 0:
239
+ bb = bb.replace("0", "x").replace("1", "0").replace("x", "1")
240
+
241
+ # done
242
+ return BitArray(bb)
243
+
244
+
245
+ def twits2bits(arr):
246
+ """Given a few (signed) numbers, store them
247
+ as compactly as possible in the wat specifief by the swf format.
248
+ The numbers are multiplied by 20, assuming they
249
+ are twits.
250
+ Can be used to make the RECT record.
251
+ """
252
+
253
+ # first determine length using non justified bit strings
254
+ maxlen = 1
255
+ for i in arr:
256
+ tmp = len(signedint2bits(i * 20))
257
+ if tmp > maxlen:
258
+ maxlen = tmp
259
+
260
+ # build array
261
+ bits = int2bits(maxlen, 5)
262
+ for i in arr:
263
+ bits += signedint2bits(i * 20, maxlen)
264
+
265
+ return bits
266
+
267
+
268
+ def floats2bits(arr):
269
+ """Given a few (signed) numbers, convert them to bits,
270
+ stored as FB (float bit values). We always use 16.16.
271
+ Negative numbers are not (yet) possible, because I don't
272
+ know how the're implemented (ambiguity).
273
+ """
274
+ bits = int2bits(31, 5) # 32 does not fit in 5 bits!
275
+ for i in arr:
276
+ if i < 0: # pragma: no cover
277
+ raise ValueError("Dit not implement negative floats!")
278
+ i1 = int(i)
279
+ i2 = i - i1
280
+ bits += int2bits(i1, 15)
281
+ bits += int2bits(i2 * 2**16, 16)
282
+ return bits
283
+
284
+
285
+ # Base Tag
286
+
287
+
288
+ class Tag:
289
+ def __init__(self):
290
+ self.bytes = bytes()
291
+ self.tagtype = -1
292
+
293
+ def process_tag(self):
294
+ """Implement this to create the tag."""
295
+ raise NotImplementedError()
296
+
297
+ def get_tag(self):
298
+ """Calls processTag and attaches the header."""
299
+ self.process_tag()
300
+
301
+ # tag to binary
302
+ bits = int2bits(self.tagtype, 10)
303
+
304
+ # complete header uint16 thing
305
+ bits += "1" * 6 # = 63 = 0x3f
306
+ # make uint16
307
+ bb = int2uint16(int(str(bits), 2))
308
+
309
+ # now add 32bit length descriptor
310
+ bb += int2uint32(len(self.bytes))
311
+
312
+ # done, attach and return
313
+ bb += self.bytes
314
+ return bb
315
+
316
+ def make_rect_record(self, xmin, xmax, ymin, ymax):
317
+ """Simply uses makeCompactArray to produce
318
+ a RECT Record."""
319
+ return twits2bits([xmin, xmax, ymin, ymax])
320
+
321
+ def make_matrix_record(self, scale_xy=None, rot_xy=None, trans_xy=None):
322
+ # empty matrix?
323
+ if scale_xy is None and rot_xy is None and trans_xy is None:
324
+ return "0" * 8
325
+
326
+ # init
327
+ bits = BitArray()
328
+
329
+ # scale
330
+ if scale_xy:
331
+ bits += "1"
332
+ bits += floats2bits([scale_xy[0], scale_xy[1]])
333
+ else:
334
+ bits += "0"
335
+
336
+ # rotation
337
+ if rot_xy:
338
+ bits += "1"
339
+ bits += floats2bits([rot_xy[0], rot_xy[1]])
340
+ else:
341
+ bits += "0"
342
+
343
+ # translation (no flag here)
344
+ if trans_xy:
345
+ bits += twits2bits([trans_xy[0], trans_xy[1]])
346
+ else:
347
+ bits += twits2bits([0, 0])
348
+
349
+ # done
350
+ return bits
351
+
352
+
353
+ # Control tags
354
+
355
+
356
+ class ControlTag(Tag):
357
+ def __init__(self):
358
+ Tag.__init__(self)
359
+
360
+
361
+ class FileAttributesTag(ControlTag):
362
+ def __init__(self):
363
+ ControlTag.__init__(self)
364
+ self.tagtype = 69
365
+
366
+ def process_tag(self):
367
+ self.bytes = "\x00".encode("ascii") * (1 + 3)
368
+
369
+
370
+ class ShowFrameTag(ControlTag):
371
+ def __init__(self):
372
+ ControlTag.__init__(self)
373
+ self.tagtype = 1
374
+
375
+ def process_tag(self):
376
+ self.bytes = bytes()
377
+
378
+
379
+ class SetBackgroundTag(ControlTag):
380
+ """Set the color in 0-255, or 0-1 (if floats given)."""
381
+
382
+ def __init__(self, *rgb):
383
+ self.tagtype = 9
384
+ if len(rgb) == 1:
385
+ rgb = rgb[0]
386
+ self.rgb = rgb
387
+
388
+ def process_tag(self):
389
+ bb = bytes()
390
+ for i in range(3):
391
+ clr = self.rgb[i]
392
+ if isinstance(clr, float): # pragma: no cover - not used
393
+ clr = clr * 255
394
+ bb += int2uint8(clr)
395
+ self.bytes = bb
396
+
397
+
398
+ class DoActionTag(Tag):
399
+ def __init__(self, action="stop"):
400
+ Tag.__init__(self)
401
+ self.tagtype = 12
402
+ self.actions = [action]
403
+
404
+ def append(self, action): # pragma: no cover - not used
405
+ self.actions.append(action)
406
+
407
+ def process_tag(self):
408
+ bb = bytes()
409
+
410
+ for action in self.actions:
411
+ action = action.lower()
412
+ if action == "stop":
413
+ bb += "\x07".encode("ascii")
414
+ elif action == "play": # pragma: no cover - not used
415
+ bb += "\x06".encode("ascii")
416
+ else: # pragma: no cover
417
+ logger.warning("unknown action: %s" % action)
418
+
419
+ bb += int2uint8(0)
420
+ self.bytes = bb
421
+
422
+
423
+ # Definition tags
424
+ class DefinitionTag(Tag):
425
+ counter = 0 # to give automatically id's
426
+
427
+ def __init__(self):
428
+ Tag.__init__(self)
429
+ DefinitionTag.counter += 1
430
+ self.id = DefinitionTag.counter # id in dictionary
431
+
432
+
433
+ class BitmapTag(DefinitionTag):
434
+ def __init__(self, im):
435
+ DefinitionTag.__init__(self)
436
+ self.tagtype = 36 # DefineBitsLossless2
437
+
438
+ # convert image (note that format is ARGB)
439
+ # even a grayscale image is stored in ARGB, nevertheless,
440
+ # the fabilous deflate compression will make it that not much
441
+ # more data is required for storing (25% or so, and less than 10%
442
+ # when storing RGB as ARGB).
443
+
444
+ if len(im.shape) == 3:
445
+ if im.shape[2] in [3, 4]:
446
+ tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
447
+ for i in range(3):
448
+ tmp[:, :, i + 1] = im[:, :, i]
449
+ if im.shape[2] == 4:
450
+ tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is
451
+ else: # pragma: no cover
452
+ raise ValueError("Invalid shape to be an image.")
453
+
454
+ elif len(im.shape) == 2:
455
+ tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
456
+ for i in range(3):
457
+ tmp[:, :, i + 1] = im[:, :]
458
+ else: # pragma: no cover
459
+ raise ValueError("Invalid shape to be an image.")
460
+
461
+ # we changed the image to uint8 4 channels.
462
+ # now compress!
463
+ self._data = zlib.compress(tmp.tobytes(), zlib.DEFLATED)
464
+ self.imshape = im.shape
465
+
466
+ def process_tag(self):
467
+ # build tag
468
+ bb = bytes()
469
+ bb += int2uint16(self.id) # CharacterID
470
+ bb += int2uint8(5) # BitmapFormat
471
+ bb += int2uint16(self.imshape[1]) # BitmapWidth
472
+ bb += int2uint16(self.imshape[0]) # BitmapHeight
473
+ bb += self._data # ZlibBitmapData
474
+
475
+ self.bytes = bb
476
+
477
+
478
+ class PlaceObjectTag(ControlTag):
479
+ def __init__(self, depth, idToPlace=None, xy=(0, 0), move=False):
480
+ ControlTag.__init__(self)
481
+ self.tagtype = 26
482
+ self.depth = depth
483
+ self.idToPlace = idToPlace
484
+ self.xy = xy
485
+ self.move = move
486
+
487
+ def process_tag(self):
488
+ # retrieve stuff
489
+ depth = self.depth
490
+ xy = self.xy
491
+ id = self.idToPlace
492
+
493
+ # build PlaceObject2
494
+ bb = bytes()
495
+ if self.move:
496
+ bb += "\x07".encode("ascii")
497
+ else:
498
+ # (8 bit flags): 4:matrix, 2:character, 1:move
499
+ bb += "\x06".encode("ascii")
500
+ bb += int2uint16(depth) # Depth
501
+ bb += int2uint16(id) # character id
502
+ bb += self.make_matrix_record(trans_xy=xy).tobytes() # MATRIX record
503
+ self.bytes = bb
504
+
505
+
506
+ class ShapeTag(DefinitionTag):
507
+ def __init__(self, bitmapId, xy, wh):
508
+ DefinitionTag.__init__(self)
509
+ self.tagtype = 2
510
+ self.bitmapId = bitmapId
511
+ self.xy = xy
512
+ self.wh = wh
513
+
514
+ def process_tag(self):
515
+ """Returns a defineshape tag. with a bitmap fill"""
516
+
517
+ bb = bytes()
518
+ bb += int2uint16(self.id)
519
+ xy, wh = self.xy, self.wh
520
+ tmp = self.make_rect_record(xy[0], wh[0], xy[1], wh[1]) # ShapeBounds
521
+ bb += tmp.tobytes()
522
+
523
+ # make SHAPEWITHSTYLE structure
524
+
525
+ # first entry: FILLSTYLEARRAY with in it a single fill style
526
+ bb += int2uint8(1) # FillStyleCount
527
+ bb += "\x41".encode("ascii") # FillStyleType (0x41 or 0x43 unsmoothed)
528
+ bb += int2uint16(self.bitmapId) # BitmapId
529
+ # bb += '\x00' # BitmapMatrix (empty matrix with leftover bits filled)
530
+ bb += self.make_matrix_record(scale_xy=(20, 20)).tobytes()
531
+
532
+ # # first entry: FILLSTYLEARRAY with in it a single fill style
533
+ # bb += int2uint8(1) # FillStyleCount
534
+ # bb += '\x00' # solid fill
535
+ # bb += '\x00\x00\xff' # color
536
+
537
+ # second entry: LINESTYLEARRAY with a single line style
538
+ bb += int2uint8(0) # LineStyleCount
539
+ # bb += int2uint16(0*20) # Width
540
+ # bb += '\x00\xff\x00' # Color
541
+
542
+ # third and fourth entry: NumFillBits and NumLineBits (4 bits each)
543
+ # I each give them four bits, so 16 styles possible.
544
+ bb += "\x44".encode("ascii")
545
+
546
+ self.bytes = bb
547
+
548
+ # last entries: SHAPERECORDs ... (individual shape records not aligned)
549
+ # STYLECHANGERECORD
550
+ bits = BitArray()
551
+ bits += self.make_style_change_record(0, 1, moveTo=(self.wh[0], self.wh[1]))
552
+ # STRAIGHTEDGERECORD 4x
553
+ bits += self.make_straight_edge_record(-self.wh[0], 0)
554
+ bits += self.make_straight_edge_record(0, -self.wh[1])
555
+ bits += self.make_straight_edge_record(self.wh[0], 0)
556
+ bits += self.make_straight_edge_record(0, self.wh[1])
557
+
558
+ # ENDSHAPRECORD
559
+ bits += self.make_end_shape_record()
560
+
561
+ self.bytes += bits.tobytes()
562
+
563
+ # done
564
+ # self.bytes = bb
565
+
566
+ def make_style_change_record(self, lineStyle=None, fillStyle=None, moveTo=None):
567
+ # first 6 flags
568
+ # Note that we use FillStyle1. If we don't flash (at least 8) does not
569
+ # recognize the frames properly when importing to library.
570
+
571
+ bits = BitArray()
572
+ bits += "0" # TypeFlag (not an edge record)
573
+ bits += "0" # StateNewStyles (only for DefineShape2 and Defineshape3)
574
+ if lineStyle:
575
+ bits += "1" # StateLineStyle
576
+ else:
577
+ bits += "0"
578
+ if fillStyle:
579
+ bits += "1" # StateFillStyle1
580
+ else:
581
+ bits += "0"
582
+ bits += "0" # StateFillStyle0
583
+ if moveTo:
584
+ bits += "1" # StateMoveTo
585
+ else:
586
+ bits += "0"
587
+
588
+ # give information
589
+ # todo: nbits for fillStyle and lineStyle is hard coded.
590
+
591
+ if moveTo:
592
+ bits += twits2bits([moveTo[0], moveTo[1]])
593
+ if fillStyle:
594
+ bits += int2bits(fillStyle, 4)
595
+ if lineStyle:
596
+ bits += int2bits(lineStyle, 4)
597
+
598
+ return bits
599
+
600
+ def make_straight_edge_record(self, *dxdy):
601
+ if len(dxdy) == 1:
602
+ dxdy = dxdy[0]
603
+
604
+ # determine required number of bits
605
+ xbits = signedint2bits(dxdy[0] * 20)
606
+ ybits = signedint2bits(dxdy[1] * 20)
607
+ nbits = max([len(xbits), len(ybits)])
608
+
609
+ bits = BitArray()
610
+ bits += "11" # TypeFlag and StraightFlag
611
+ bits += int2bits(nbits - 2, 4)
612
+ bits += "1" # GeneralLineFlag
613
+ bits += signedint2bits(dxdy[0] * 20, nbits)
614
+ bits += signedint2bits(dxdy[1] * 20, nbits)
615
+
616
+ # note: I do not make use of vertical/horizontal only lines...
617
+
618
+ return bits
619
+
620
+ def make_end_shape_record(self):
621
+ bits = BitArray()
622
+ bits += "0" # TypeFlag: no edge
623
+ bits += "0" * 5 # EndOfShape
624
+ return bits
625
+
626
+
627
+ def read_pixels(bb, i, tagType, L1):
628
+ """With pf's seed after the recordheader, reads the pixeldata."""
629
+
630
+ # Get info
631
+ charId = bb[i : i + 2] # noqa
632
+ i += 2
633
+ format = ord(bb[i : i + 1])
634
+ i += 1
635
+ width = bits2int(bb[i : i + 2], 16)
636
+ i += 2
637
+ height = bits2int(bb[i : i + 2], 16)
638
+ i += 2
639
+
640
+ # If we can, get pixeldata and make numpy array
641
+ if format != 5:
642
+ logger.warning("Can only read 24bit or 32bit RGB(A) lossless images.")
643
+ else:
644
+ # Read byte data
645
+ offset = 2 + 1 + 2 + 2 # all the info bits
646
+ bb2 = bb[i : i + (L1 - offset)]
647
+
648
+ # Decompress and make numpy array
649
+ data = zlib.decompress(bb2)
650
+ a = np.frombuffer(data, dtype=np.uint8)
651
+
652
+ # Set shape
653
+ if tagType == 20:
654
+ # DefineBitsLossless - RGB data
655
+ try:
656
+ a.shape = height, width, 3
657
+ except Exception:
658
+ # Byte align stuff might cause troubles
659
+ logger.warning("Cannot read image due to byte alignment")
660
+ if tagType == 36:
661
+ # DefineBitsLossless2 - ARGB data
662
+ a.shape = height, width, 4
663
+ # Swap alpha channel to make RGBA
664
+ b = a
665
+ a = np.zeros_like(a)
666
+ a[:, :, 0] = b[:, :, 1]
667
+ a[:, :, 1] = b[:, :, 2]
668
+ a[:, :, 2] = b[:, :, 3]
669
+ a[:, :, 3] = b[:, :, 0]
670
+
671
+ return a
672
+
673
+
674
+ # Last few functions
675
+
676
+
677
+ # These are the original public functions, we don't use them, but we
678
+ # keep it so that in principle this module can be used stand-alone.
679
+
680
+
681
+ def checkImages(images): # pragma: no cover
682
+ """checkImages(images)
683
+ Check numpy images and correct intensity range etc.
684
+ The same for all movie formats.
685
+ """
686
+ # Init results
687
+ images2 = []
688
+
689
+ for im in images:
690
+ if isinstance(im, np.ndarray):
691
+ # Check and convert dtype
692
+ if im.dtype == np.uint8:
693
+ images2.append(im) # Ok
694
+ elif im.dtype in [np.float32, np.float64]:
695
+ theMax = im.max()
696
+ if 128 < theMax < 300:
697
+ pass # assume 0:255
698
+ else:
699
+ im = im.copy()
700
+ im[im < 0] = 0
701
+ im[im > 1] = 1
702
+ im *= 255
703
+ images2.append(im.astype(np.uint8))
704
+ else:
705
+ im = im.astype(np.uint8)
706
+ images2.append(im)
707
+ # Check size
708
+ if im.ndim == 2:
709
+ pass # ok
710
+ elif im.ndim == 3:
711
+ if im.shape[2] not in [3, 4]:
712
+ raise ValueError("This array can not represent an image.")
713
+ else:
714
+ raise ValueError("This array can not represent an image.")
715
+ else:
716
+ raise ValueError("Invalid image type: " + str(type(im)))
717
+
718
+ # Done
719
+ return images2
720
+
721
+
722
+ def build_file(
723
+ fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8
724
+ ): # pragma: no cover
725
+ """Give the given file (as bytes) a header."""
726
+
727
+ # compose header
728
+ bb = bytes()
729
+ bb += "F".encode("ascii") # uncompressed
730
+ bb += "WS".encode("ascii") # signature bytes
731
+ bb += int2uint8(version) # version
732
+ bb += "0000".encode("ascii") # FileLength (leave open for now)
733
+ bb += Tag().make_rect_record(0, framesize[0], 0, framesize[1]).tobytes()
734
+ bb += int2uint8(0) + int2uint8(fps) # FrameRate
735
+ bb += int2uint16(nframes)
736
+ fp.write(bb)
737
+
738
+ # produce all tags
739
+ for tag in taglist:
740
+ fp.write(tag.get_tag())
741
+
742
+ # finish with end tag
743
+ fp.write("\x00\x00".encode("ascii"))
744
+
745
+ # set size
746
+ sze = fp.tell()
747
+ fp.seek(4)
748
+ fp.write(int2uint32(sze))
749
+
750
+
751
+ def write_swf(filename, images, duration=0.1, repeat=True): # pragma: no cover
752
+ """Write an swf-file from the specified images. If repeat is False,
753
+ the movie is finished with a stop action. Duration may also
754
+ be a list with durations for each frame (note that the duration
755
+ for each frame is always an integer amount of the minimum duration.)
756
+
757
+ Images should be a list consisting numpy arrays with values between
758
+ 0 and 255 for integer types, and between 0 and 1 for float types.
759
+
760
+ """
761
+
762
+ # Check images
763
+ images2 = checkImages(images)
764
+
765
+ # Init
766
+ taglist = [FileAttributesTag(), SetBackgroundTag(0, 0, 0)]
767
+
768
+ # Check duration
769
+ if hasattr(duration, "__len__"):
770
+ if len(duration) == len(images2):
771
+ duration = [d for d in duration]
772
+ else:
773
+ raise ValueError("len(duration) doesn't match amount of images.")
774
+ else:
775
+ duration = [duration for im in images2]
776
+
777
+ # Build delays list
778
+ minDuration = float(min(duration))
779
+ delays = [round(d / minDuration) for d in duration]
780
+ delays = [max(1, int(d)) for d in delays]
781
+
782
+ # Get FPS
783
+ fps = 1.0 / minDuration
784
+
785
+ # Produce series of tags for each image
786
+ # t0 = time.time()
787
+ nframes = 0
788
+ for im in images2:
789
+ bm = BitmapTag(im)
790
+ wh = (im.shape[1], im.shape[0])
791
+ sh = ShapeTag(bm.id, (0, 0), wh)
792
+ po = PlaceObjectTag(1, sh.id, move=nframes > 0)
793
+ taglist.extend([bm, sh, po])
794
+ for i in range(delays[nframes]):
795
+ taglist.append(ShowFrameTag())
796
+ nframes += 1
797
+
798
+ if not repeat:
799
+ taglist.append(DoActionTag("stop"))
800
+
801
+ # Build file
802
+ # t1 = time.time()
803
+ fp = open(filename, "wb")
804
+ try:
805
+ build_file(fp, taglist, nframes=nframes, framesize=wh, fps=fps)
806
+ except Exception:
807
+ raise
808
+ finally:
809
+ fp.close()
810
+ # t2 = time.time()
811
+
812
+ # logger.warning("Writing SWF took %1.2f and %1.2f seconds" % (t1-t0, t2-t1) )
813
+
814
+
815
+ def read_swf(filename): # pragma: no cover
816
+ """Read all images from an SWF (shockwave flash) file. Returns a list
817
+ of numpy arrays.
818
+
819
+ Limitation: only read the PNG encoded images (not the JPG encoded ones).
820
+ """
821
+
822
+ # Check whether it exists
823
+ if not os.path.isfile(filename):
824
+ raise IOError("File not found: " + str(filename))
825
+
826
+ # Init images
827
+ images = []
828
+
829
+ # Open file and read all
830
+ fp = open(filename, "rb")
831
+ bb = fp.read()
832
+
833
+ try:
834
+ # Check opening tag
835
+ tmp = bb[0:3].decode("ascii", "ignore")
836
+ if tmp.upper() == "FWS":
837
+ pass # ok
838
+ elif tmp.upper() == "CWS":
839
+ # Decompress movie
840
+ bb = bb[:8] + zlib.decompress(bb[8:])
841
+ else:
842
+ raise IOError("Not a valid SWF file: " + str(filename))
843
+
844
+ # Set filepointer at first tag (skipping framesize RECT and two uin16's
845
+ i = 8
846
+ nbits = bits2int(bb[i : i + 1], 5) # skip FrameSize
847
+ nbits = 5 + nbits * 4
848
+ Lrect = nbits / 8.0
849
+ if Lrect % 1:
850
+ Lrect += 1
851
+ Lrect = int(Lrect)
852
+ i += Lrect + 4
853
+
854
+ # Iterate over the tags
855
+ counter = 0
856
+ while True:
857
+ counter += 1
858
+
859
+ # Get tag header
860
+ head = bb[i : i + 6]
861
+ if not head:
862
+ break # Done (we missed end tag)
863
+
864
+ # Determine type and length
865
+ T, L1, L2 = get_type_and_len(head)
866
+ if not L2:
867
+ logger.warning("Invalid tag length, could not proceed")
868
+ break
869
+ # logger.warning(T, L2)
870
+
871
+ # Read image if we can
872
+ if T in [20, 36]:
873
+ im = read_pixels(bb, i + 6, T, L1)
874
+ if im is not None:
875
+ images.append(im)
876
+ elif T in [6, 21, 35, 90]:
877
+ logger.warning("Ignoring JPEG image: cannot read JPEG.")
878
+ else:
879
+ pass # Not an image tag
880
+
881
+ # Detect end tag
882
+ if T == 0:
883
+ break
884
+
885
+ # Next tag!
886
+ i += L2
887
+
888
+ finally:
889
+ fp.close()
890
+
891
+ # Done
892
+ return images
893
+
894
+
895
+ # Backward compatibility; same public names as when this was images2swf.
896
+ writeSwf = write_swf
897
+ readSwf = read_swf
minigpt2/lib/python3.10/site-packages/imageio/plugins/example.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Example plugin. You can use this as a template for your own plugin.
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ from .. import formats
10
+ from ..core import Format
11
+
12
+
13
+ class DummyFormat(Format):
14
+ """The dummy format is an example format that does nothing.
15
+ It will never indicate that it can read or write a file. When
16
+ explicitly asked to read, it will simply read the bytes. When
17
+ explicitly asked to write, it will raise an error.
18
+
19
+ This documentation is shown when the user does ``help('thisformat')``.
20
+
21
+ Parameters for reading
22
+ ----------------------
23
+ Specify arguments in numpy doc style here.
24
+
25
+ Parameters for saving
26
+ ---------------------
27
+ Specify arguments in numpy doc style here.
28
+
29
+ """
30
+
31
+ def _can_read(self, request):
32
+ # This method is called when the format manager is searching
33
+ # for a format to read a certain image. Return True if this format
34
+ # can do it.
35
+ #
36
+ # The format manager is aware of the extensions and the modes
37
+ # that each format can handle. It will first ask all formats
38
+ # that *seem* to be able to read it whether they can. If none
39
+ # can, it will ask the remaining formats if they can: the
40
+ # extension might be missing, and this allows formats to provide
41
+ # functionality for certain extensions, while giving preference
42
+ # to other plugins.
43
+ #
44
+ # If a format says it can, it should live up to it. The format
45
+ # would ideally check the request.firstbytes and look for a
46
+ # header of some kind.
47
+ #
48
+ # The request object has:
49
+ # request.filename: a representation of the source (only for reporting)
50
+ # request.firstbytes: the first 256 bytes of the file.
51
+ # request.mode[0]: read or write mode
52
+
53
+ if request.extension in self.extensions:
54
+ return True
55
+
56
+ def _can_write(self, request):
57
+ # This method is called when the format manager is searching
58
+ # for a format to write a certain image. It will first ask all
59
+ # formats that *seem* to be able to write it whether they can.
60
+ # If none can, it will ask the remaining formats if they can.
61
+ #
62
+ # Return True if the format can do it.
63
+
64
+ # In most cases, this code does suffice:
65
+ if request.extension in self.extensions:
66
+ return True
67
+
68
+ # -- reader
69
+
70
+ class Reader(Format.Reader):
71
+ def _open(self, some_option=False, length=1):
72
+ # Specify kwargs here. Optionally, the user-specified kwargs
73
+ # can also be accessed via the request.kwargs object.
74
+ #
75
+ # The request object provides two ways to get access to the
76
+ # data. Use just one:
77
+ # - Use request.get_file() for a file object (preferred)
78
+ # - Use request.get_local_filename() for a file on the system
79
+ self._fp = self.request.get_file()
80
+ self._length = length # passed as an arg in this case for testing
81
+ self._data = None
82
+
83
+ def _close(self):
84
+ # Close the reader.
85
+ # Note that the request object will close self._fp
86
+ pass
87
+
88
+ def _get_length(self):
89
+ # Return the number of images. Can be np.inf
90
+ return self._length
91
+
92
+ def _get_data(self, index):
93
+ # Return the data and meta data for the given index
94
+ if index >= self._length:
95
+ raise IndexError("Image index %i > %i" % (index, self._length))
96
+ # Read all bytes
97
+ if self._data is None:
98
+ self._data = self._fp.read()
99
+ # Put in a numpy array
100
+ im = np.frombuffer(self._data, "uint8")
101
+ im.shape = len(im), 1
102
+ # Return array and dummy meta data
103
+ return im, {}
104
+
105
+ def _get_meta_data(self, index):
106
+ # Get the meta data for the given index. If index is None, it
107
+ # should return the global meta data.
108
+ return {} # This format does not support meta data
109
+
110
+ # -- writer
111
+
112
+ class Writer(Format.Writer):
113
+ def _open(self, flags=0):
114
+ # Specify kwargs here. Optionally, the user-specified kwargs
115
+ # can also be accessed via the request.kwargs object.
116
+ #
117
+ # The request object provides two ways to write the data.
118
+ # Use just one:
119
+ # - Use request.get_file() for a file object (preferred)
120
+ # - Use request.get_local_filename() for a file on the system
121
+ self._fp = self.request.get_file()
122
+
123
+ def _close(self):
124
+ # Close the reader.
125
+ # Note that the request object will close self._fp
126
+ pass
127
+
128
+ def _append_data(self, im, meta):
129
+ # Process the given data and meta data.
130
+ raise RuntimeError("The dummy format cannot write image data.")
131
+
132
+ def set_meta_data(self, meta):
133
+ # Process the given meta data (global for all images)
134
+ # It is not mandatory to support this.
135
+ raise RuntimeError("The dummy format cannot write meta data.")
136
+
137
+
138
+ # Register. You register an *instance* of a Format class. Here specify:
139
+ format = DummyFormat(
140
+ "dummy", # short name
141
+ "An example format that does nothing.", # one line descr.
142
+ ".foobar .nonexistentext", # list of extensions
143
+ "iI", # modes, characters in iIvV
144
+ )
145
+ formats.add_format(format)
minigpt2/lib/python3.10/site-packages/imageio/plugins/lytro.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2018, imageio contributors
3
+ # imageio is distributed under the terms of the (new) BSD License.
4
+ #
5
+
6
+ """ Read LFR files (Lytro Illum).
7
+
8
+ Backend: internal
9
+
10
+ Plugin to read Lytro Illum .lfr and .raw files as produced
11
+ by the Lytro Illum light field camera. It is actually a collection
12
+ of plugins, each supporting slightly different keyword arguments
13
+
14
+ Parameters
15
+ ----------
16
+ meta_only : bool
17
+ Whether to only read the metadata.
18
+ include_thumbnail : bool
19
+ (only for lytro-lfr and lytro-lfp)
20
+ Whether to include an image thumbnail in the metadata.
21
+
22
+ """
23
+ #
24
+ #
25
+ # This code is based on work by
26
+ # David Uhlig and his lfr_reader
27
+ # (https://www.iiit.kit.edu/uhlig.php)
28
+ # Donald Dansereau and his Matlab LF Toolbox
29
+ # (http://dgd.vision/Tools/LFToolbox/)
30
+ # and Behnam Esfahbod and his Python LFP-Reader
31
+ # (https://github.com/behnam/python-lfp-reader/)
32
+
33
+
34
+ import os
35
+ import json
36
+ import struct
37
+ import logging
38
+
39
+
40
+ import numpy as np
41
+
42
+ from ..core import Format
43
+ from ..v2 import imread
44
+
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+
49
+ # Sensor size of Lytro Illum resp. Lytro F01 light field camera sensor
50
+ LYTRO_ILLUM_IMAGE_SIZE = (5368, 7728)
51
+ LYTRO_F01_IMAGE_SIZE = (3280, 3280)
52
+
53
+ # Parameter of lfr file format
54
+ HEADER_LENGTH = 12
55
+ SIZE_LENGTH = 4 # = 16 - header_length
56
+ SHA1_LENGTH = 45 # = len("sha1-") + (160 / 4)
57
+ PADDING_LENGTH = 35 # = (4*16) - header_length - size_length - sha1_length
58
+ DATA_CHUNKS_ILLUM = 11
59
+ DATA_CHUNKS_F01 = 3
60
+
61
+
62
+ class LytroFormat(Format):
63
+ """Base class for Lytro format.
64
+ The subclasses LytroLfrFormat, LytroLfpFormat, LytroIllumRawFormat and
65
+ LytroF01RawFormat implement the Lytro-LFR, Lytro-LFP and Lytro-RAW format
66
+ for the Illum and original F01 camera respectively.
67
+ Writing is not supported.
68
+ """
69
+
70
+ # Only single images are supported.
71
+ _modes = "i"
72
+
73
+ def _can_write(self, request):
74
+ # Writing of Lytro files is not supported
75
+ return False
76
+
77
+ # -- writer
78
+
79
+ class Writer(Format.Writer):
80
+ def _open(self, flags=0):
81
+ self._fp = self.request.get_file()
82
+
83
+ def _close(self):
84
+ # Close the reader.
85
+ # Note that the request object will close self._fp
86
+ pass
87
+
88
+ def _append_data(self, im, meta):
89
+ # Process the given data and meta data.
90
+ raise RuntimeError("The lytro format cannot write image data.")
91
+
92
+ def _set_meta_data(self, meta):
93
+ # Process the given meta data (global for all images)
94
+ # It is not mandatory to support this.
95
+ raise RuntimeError("The lytro format cannot write meta data.")
96
+
97
+
98
+ class LytroIllumRawFormat(LytroFormat):
99
+ """This is the Lytro Illum RAW format.
100
+ The raw format is a 10bit image format as used by the Lytro Illum
101
+ light field camera. The format will read the specified raw file and will
102
+ try to load a .txt or .json file with the associated meta data.
103
+ This format does not support writing.
104
+
105
+
106
+ Parameters for reading
107
+ ----------------------
108
+ meta_only : bool
109
+ Whether to only read the metadata.
110
+ """
111
+
112
+ def _can_read(self, request):
113
+ # Check if mode and extensions are supported by the format
114
+ if request.extension in (".raw",):
115
+ return True
116
+
117
+ @staticmethod
118
+ def rearrange_bits(array):
119
+ # Do bit rearrangement for the 10-bit lytro raw format
120
+ # Normalize output to 1.0 as float64
121
+ t0 = array[0::5]
122
+ t1 = array[1::5]
123
+ t2 = array[2::5]
124
+ t3 = array[3::5]
125
+ lsb = array[4::5]
126
+
127
+ t0 = np.left_shift(t0, 2) + np.bitwise_and(lsb, 3)
128
+ t1 = np.left_shift(t1, 2) + np.right_shift(np.bitwise_and(lsb, 12), 2)
129
+ t2 = np.left_shift(t2, 2) + np.right_shift(np.bitwise_and(lsb, 48), 4)
130
+ t3 = np.left_shift(t3, 2) + np.right_shift(np.bitwise_and(lsb, 192), 6)
131
+
132
+ image = np.zeros(LYTRO_ILLUM_IMAGE_SIZE, dtype=np.uint16)
133
+ image[:, 0::4] = t0.reshape(
134
+ (LYTRO_ILLUM_IMAGE_SIZE[0], LYTRO_ILLUM_IMAGE_SIZE[1] // 4)
135
+ )
136
+ image[:, 1::4] = t1.reshape(
137
+ (LYTRO_ILLUM_IMAGE_SIZE[0], LYTRO_ILLUM_IMAGE_SIZE[1] // 4)
138
+ )
139
+ image[:, 2::4] = t2.reshape(
140
+ (LYTRO_ILLUM_IMAGE_SIZE[0], LYTRO_ILLUM_IMAGE_SIZE[1] // 4)
141
+ )
142
+ image[:, 3::4] = t3.reshape(
143
+ (LYTRO_ILLUM_IMAGE_SIZE[0], LYTRO_ILLUM_IMAGE_SIZE[1] // 4)
144
+ )
145
+
146
+ # Normalize data to 1.0 as 64-bit float.
147
+ # Division is by 1023 as the Lytro Illum saves 10-bit raw data.
148
+ return np.divide(image, 1023.0).astype(np.float64)
149
+
150
+ # -- reader
151
+
152
+ class Reader(Format.Reader):
153
+ def _open(self, meta_only=False):
154
+ self._file = self.request.get_file()
155
+ self._data = None
156
+ self._meta_only = meta_only
157
+
158
+ def _close(self):
159
+ # Close the reader.
160
+ # Note that the request object will close self._file
161
+ del self._data
162
+
163
+ def _get_length(self):
164
+ # Return the number of images.
165
+ return 1
166
+
167
+ def _get_data(self, index):
168
+ # Return the data and meta data for the given index
169
+
170
+ if index not in [0, "None"]:
171
+ raise IndexError("Lytro file contains only one dataset")
172
+
173
+ if not self._meta_only:
174
+ # Read all bytes
175
+ if self._data is None:
176
+ self._data = self._file.read()
177
+
178
+ # Read bytes from string and convert to uint16
179
+ raw = np.frombuffer(self._data, dtype=np.uint8).astype(np.uint16)
180
+
181
+ # Rearrange bits
182
+ img = LytroIllumRawFormat.rearrange_bits(raw)
183
+
184
+ else:
185
+ # Return empty image
186
+ img = np.array([])
187
+
188
+ # Return image and meta data
189
+ return img, self._get_meta_data(index=0)
190
+
191
+ def _get_meta_data(self, index):
192
+ # Get the meta data for the given index. If index is None, it
193
+ # should return the global meta data.
194
+
195
+ if index not in [0, None]:
196
+ raise IndexError("Lytro meta data file contains only one dataset")
197
+
198
+ # Try to read meta data from meta data file corresponding
199
+ # to the raw data file, extension in [.txt, .TXT, .json, .JSON]
200
+ filename_base = os.path.splitext(self.request.get_local_filename())[0]
201
+
202
+ meta_data = None
203
+
204
+ for ext in [".txt", ".TXT", ".json", ".JSON"]:
205
+ if os.path.isfile(filename_base + ext):
206
+ meta_data = json.load(open(filename_base + ext))
207
+
208
+ if meta_data is not None:
209
+ return meta_data
210
+
211
+ else:
212
+ logger.warning("No metadata file found for provided raw file.")
213
+ return {}
214
+
215
+
216
+ class LytroLfrFormat(LytroFormat):
217
+ """This is the Lytro Illum LFR format.
218
+ The lfr is a image and meta data container format as used by the
219
+ Lytro Illum light field camera.
220
+ The format will read the specified lfr file.
221
+ This format does not support writing.
222
+
223
+ Parameters for reading
224
+ ----------------------
225
+ meta_only : bool
226
+ Whether to only read the metadata.
227
+ include_thumbnail : bool
228
+ Whether to include an image thumbnail in the metadata.
229
+ """
230
+
231
+ def _can_read(self, request):
232
+ # Check if mode and extensions are supported by the format
233
+ if request.extension in (".lfr",):
234
+ return True
235
+
236
+ # -- reader
237
+
238
+ class Reader(Format.Reader):
239
+ def _open(self, meta_only=False, include_thumbnail=True):
240
+ self._file = self.request.get_file()
241
+ self._data = None
242
+ self._chunks = {}
243
+ self.metadata = {}
244
+ self._content = None
245
+ self._meta_only = meta_only
246
+ self._include_thumbnail = include_thumbnail
247
+
248
+ self._find_header()
249
+ self._find_chunks()
250
+ self._find_meta()
251
+
252
+ try:
253
+ # Get sha1 dict and check if it is in dictionary of data chunks
254
+ chunk_dict = self._content["frames"][0]["frame"]
255
+ if (
256
+ chunk_dict["metadataRef"] in self._chunks
257
+ and chunk_dict["imageRef"] in self._chunks
258
+ and chunk_dict["privateMetadataRef"] in self._chunks
259
+ ):
260
+ if not self._meta_only:
261
+ # Read raw image data byte buffer
262
+ data_pos, size = self._chunks[chunk_dict["imageRef"]]
263
+ self._file.seek(data_pos, 0)
264
+ self.raw_image_data = self._file.read(size)
265
+
266
+ # Read meta data
267
+ data_pos, size = self._chunks[chunk_dict["metadataRef"]]
268
+ self._file.seek(data_pos, 0)
269
+ metadata = self._file.read(size)
270
+ # Add metadata to meta data dict
271
+ self.metadata["metadata"] = json.loads(metadata.decode("ASCII"))
272
+
273
+ # Read private metadata
274
+ data_pos, size = self._chunks[chunk_dict["privateMetadataRef"]]
275
+ self._file.seek(data_pos, 0)
276
+ serial_numbers = self._file.read(size)
277
+ self.serial_numbers = json.loads(serial_numbers.decode("ASCII"))
278
+ # Add private metadata to meta data dict
279
+ self.metadata["privateMetadata"] = self.serial_numbers
280
+
281
+ # Read image preview thumbnail
282
+ if self._include_thumbnail:
283
+ chunk_dict = self._content["thumbnails"][0]
284
+ if chunk_dict["imageRef"] in self._chunks:
285
+ # Read thumbnail image from thumbnail chunk
286
+ data_pos, size = self._chunks[chunk_dict["imageRef"]]
287
+ self._file.seek(data_pos, 0)
288
+ # Read binary data, read image as jpeg
289
+ thumbnail_data = self._file.read(size)
290
+ thumbnail_img = imread(thumbnail_data, format="jpeg")
291
+
292
+ thumbnail_height = chunk_dict["height"]
293
+ thumbnail_width = chunk_dict["width"]
294
+
295
+ # Add thumbnail to metadata
296
+ self.metadata["thumbnail"] = {
297
+ "image": thumbnail_img,
298
+ "height": thumbnail_height,
299
+ "width": thumbnail_width,
300
+ }
301
+
302
+ except KeyError:
303
+ raise RuntimeError("The specified file is not a valid LFR file.")
304
+
305
+ def _close(self):
306
+ # Close the reader.
307
+ # Note that the request object will close self._file
308
+ del self._data
309
+
310
+ def _get_length(self):
311
+ # Return the number of images. Can be np.inf
312
+ return 1
313
+
314
+ def _find_header(self):
315
+ """
316
+ Checks if file has correct header and skip it.
317
+ """
318
+ file_header = b"\x89LFP\x0D\x0A\x1A\x0A\x00\x00\x00\x01"
319
+ # Read and check header of file
320
+ header = self._file.read(HEADER_LENGTH)
321
+ if header != file_header:
322
+ raise RuntimeError("The LFR file header is invalid.")
323
+
324
+ # Read first bytes to skip header
325
+ self._file.read(SIZE_LENGTH)
326
+
327
+ def _find_chunks(self):
328
+ """
329
+ Gets start position and size of data chunks in file.
330
+ """
331
+ chunk_header = b"\x89LFC\x0D\x0A\x1A\x0A\x00\x00\x00\x00"
332
+
333
+ for i in range(0, DATA_CHUNKS_ILLUM):
334
+ data_pos, size, sha1 = self._get_chunk(chunk_header)
335
+ self._chunks[sha1] = (data_pos, size)
336
+
337
+ def _find_meta(self):
338
+ """
339
+ Gets a data chunk that contains information over content
340
+ of other data chunks.
341
+ """
342
+ meta_header = b"\x89LFM\x0D\x0A\x1A\x0A\x00\x00\x00\x00"
343
+ data_pos, size, sha1 = self._get_chunk(meta_header)
344
+
345
+ # Get content
346
+ self._file.seek(data_pos, 0)
347
+ data = self._file.read(size)
348
+ self._content = json.loads(data.decode("ASCII"))
349
+
350
+ def _get_chunk(self, header):
351
+ """
352
+ Checks if chunk has correct header and skips it.
353
+ Finds start position and length of next chunk and reads
354
+ sha1-string that identifies the following data chunk.
355
+
356
+ Parameters
357
+ ----------
358
+ header : bytes
359
+ Byte string that identifies start of chunk.
360
+
361
+ Returns
362
+ -------
363
+ data_pos : int
364
+ Start position of data chunk in file.
365
+ size : int
366
+ Size of data chunk.
367
+ sha1 : str
368
+ Sha1 value of chunk.
369
+ """
370
+ # Read and check header of chunk
371
+ header_chunk = self._file.read(HEADER_LENGTH)
372
+ if header_chunk != header:
373
+ raise RuntimeError("The LFR chunk header is invalid.")
374
+
375
+ data_pos = None
376
+ sha1 = None
377
+
378
+ # Read size
379
+ size = struct.unpack(">i", self._file.read(SIZE_LENGTH))[0]
380
+ if size > 0:
381
+ # Read sha1
382
+ sha1 = str(self._file.read(SHA1_LENGTH).decode("ASCII"))
383
+ # Skip fixed null chars
384
+ self._file.read(PADDING_LENGTH)
385
+ # Find start of data and skip data
386
+ data_pos = self._file.tell()
387
+ self._file.seek(size, 1)
388
+ # Skip extra null chars
389
+ ch = self._file.read(1)
390
+ while ch == b"\0":
391
+ ch = self._file.read(1)
392
+ self._file.seek(-1, 1)
393
+
394
+ return data_pos, size, sha1
395
+
396
+ def _get_data(self, index):
397
+ # Return the data and meta data for the given index
398
+ if index not in [0, None]:
399
+ raise IndexError("Lytro lfr file contains only one dataset")
400
+
401
+ if not self._meta_only:
402
+ # Read bytes from string and convert to uint16
403
+ raw = np.frombuffer(self.raw_image_data, dtype=np.uint8).astype(
404
+ np.uint16
405
+ )
406
+ im = LytroIllumRawFormat.rearrange_bits(raw)
407
+ else:
408
+ im = np.array([])
409
+
410
+ # Return array and dummy meta data
411
+ return im, self.metadata
412
+
413
+ def _get_meta_data(self, index):
414
+ # Get the meta data for the given index. If index is None,
415
+ # it returns the global meta data.
416
+ if index not in [0, None]:
417
+ raise IndexError("Lytro meta data file contains only one dataset")
418
+
419
+ return self.metadata
420
+
421
+
422
+ class LytroF01RawFormat(LytroFormat):
423
+ """This is the Lytro RAW format for the original F01 Lytro camera.
424
+ The raw format is a 12bit image format as used by the Lytro F01
425
+ light field camera. The format will read the specified raw file and will
426
+ try to load a .txt or .json file with the associated meta data.
427
+ This format does not support writing.
428
+
429
+
430
+ Parameters for reading
431
+ ----------------------
432
+ meta_only : bool
433
+ Whether to only read the metadata.
434
+
435
+ """
436
+
437
+ def _can_read(self, request):
438
+ # Check if mode and extensions are supported by the format
439
+ if request.extension in (".raw",):
440
+ return True
441
+
442
+ @staticmethod
443
+ def rearrange_bits(array):
444
+ # Do bit rearrangement for the 12-bit lytro raw format
445
+ # Normalize output to 1.0 as float64
446
+ t0 = array[0::3]
447
+ t1 = array[1::3]
448
+ t2 = array[2::3]
449
+
450
+ a0 = np.left_shift(t0, 4) + np.right_shift(np.bitwise_and(t1, 240), 4)
451
+ a1 = np.left_shift(np.bitwise_and(t1, 15), 8) + t2
452
+
453
+ image = np.zeros(LYTRO_F01_IMAGE_SIZE, dtype=np.uint16)
454
+ image[:, 0::2] = a0.reshape(
455
+ (LYTRO_F01_IMAGE_SIZE[0], LYTRO_F01_IMAGE_SIZE[1] // 2)
456
+ )
457
+ image[:, 1::2] = a1.reshape(
458
+ (LYTRO_F01_IMAGE_SIZE[0], LYTRO_F01_IMAGE_SIZE[1] // 2)
459
+ )
460
+
461
+ # Normalize data to 1.0 as 64-bit float.
462
+ # Division is by 4095 as the Lytro F01 saves 12-bit raw data.
463
+ return np.divide(image, 4095.0).astype(np.float64)
464
+
465
+ # -- reader
466
+
467
+ class Reader(Format.Reader):
468
+ def _open(self, meta_only=False):
469
+ self._file = self.request.get_file()
470
+ self._data = None
471
+ self._meta_only = meta_only
472
+
473
+ def _close(self):
474
+ # Close the reader.
475
+ # Note that the request object will close self._file
476
+ del self._data
477
+
478
+ def _get_length(self):
479
+ # Return the number of images.
480
+ return 1
481
+
482
+ def _get_data(self, index):
483
+ # Return the data and meta data for the given index
484
+
485
+ if index not in [0, "None"]:
486
+ raise IndexError("Lytro file contains only one dataset")
487
+
488
+ if not self._meta_only:
489
+ # Read all bytes
490
+ if self._data is None:
491
+ self._data = self._file.read()
492
+
493
+ # Read bytes from string and convert to uint16
494
+ raw = np.frombuffer(self._data, dtype=np.uint8).astype(np.uint16)
495
+
496
+ # Rearrange bits
497
+ img = LytroF01RawFormat.rearrange_bits(raw)
498
+
499
+ else:
500
+ img = np.array([])
501
+
502
+ # Return image and meta data
503
+ return img, self._get_meta_data(index=0)
504
+
505
+ def _get_meta_data(self, index):
506
+ # Get the meta data for the given index. If index is None, it
507
+ # should return the global meta data.
508
+
509
+ if index not in [0, None]:
510
+ raise IndexError("Lytro meta data file contains only one dataset")
511
+
512
+ # Try to read meta data from meta data file corresponding
513
+ # to the raw data file, extension in [.txt, .TXT, .json, .JSON]
514
+ filename_base = os.path.splitext(self.request.get_local_filename())[0]
515
+
516
+ meta_data = None
517
+
518
+ for ext in [".txt", ".TXT", ".json", ".JSON"]:
519
+ if os.path.isfile(filename_base + ext):
520
+ meta_data = json.load(open(filename_base + ext))
521
+
522
+ if meta_data is not None:
523
+ return meta_data
524
+
525
+ else:
526
+ logger.warning("No metadata file found for provided raw file.")
527
+ return {}
528
+
529
+
530
+ class LytroLfpFormat(LytroFormat):
531
+ """This is the Lytro Illum LFP format.
532
+ The lfp is a image and meta data container format as used by the
533
+ Lytro F01 light field camera.
534
+ The format will read the specified lfp file.
535
+ This format does not support writing.
536
+
537
+ Parameters for reading
538
+ ----------------------
539
+ meta_only : bool
540
+ Whether to only read the metadata.
541
+ include_thumbnail : bool
542
+ Whether to include an image thumbnail in the metadata.
543
+ """
544
+
545
+ def _can_read(self, request):
546
+ # Check if mode and extensions are supported by the format
547
+ if request.extension in (".lfp",):
548
+ return True
549
+
550
+ # -- reader
551
+
552
+ class Reader(Format.Reader):
553
+ def _open(self, meta_only=False):
554
+ self._file = self.request.get_file()
555
+ self._data = None
556
+ self._chunks = {}
557
+ self.metadata = {}
558
+ self._content = None
559
+ self._meta_only = meta_only
560
+
561
+ self._find_header()
562
+ self._find_meta()
563
+ self._find_chunks()
564
+
565
+ try:
566
+ # Get sha1 dict and check if it is in dictionary of data chunks
567
+ chunk_dict = self._content["picture"]["frameArray"][0]["frame"]
568
+ if (
569
+ chunk_dict["metadataRef"] in self._chunks
570
+ and chunk_dict["imageRef"] in self._chunks
571
+ and chunk_dict["privateMetadataRef"] in self._chunks
572
+ ):
573
+ if not self._meta_only:
574
+ # Read raw image data byte buffer
575
+ data_pos, size = self._chunks[chunk_dict["imageRef"]]
576
+ self._file.seek(data_pos, 0)
577
+ self.raw_image_data = self._file.read(size)
578
+
579
+ # Read meta data
580
+ data_pos, size = self._chunks[chunk_dict["metadataRef"]]
581
+ self._file.seek(data_pos, 0)
582
+ metadata = self._file.read(size)
583
+ # Add metadata to meta data dict
584
+ self.metadata["metadata"] = json.loads(metadata.decode("ASCII"))
585
+
586
+ # Read private metadata
587
+ data_pos, size = self._chunks[chunk_dict["privateMetadataRef"]]
588
+ self._file.seek(data_pos, 0)
589
+ serial_numbers = self._file.read(size)
590
+ self.serial_numbers = json.loads(serial_numbers.decode("ASCII"))
591
+ # Add private metadata to meta data dict
592
+ self.metadata["privateMetadata"] = self.serial_numbers
593
+
594
+ except KeyError:
595
+ raise RuntimeError("The specified file is not a valid LFP file.")
596
+
597
+ def _close(self):
598
+ # Close the reader.
599
+ # Note that the request object will close self._file
600
+ del self._data
601
+
602
+ def _get_length(self):
603
+ # Return the number of images. Can be np.inf
604
+ return 1
605
+
606
+ def _find_header(self):
607
+ """
608
+ Checks if file has correct header and skip it.
609
+ """
610
+ file_header = b"\x89LFP\x0D\x0A\x1A\x0A\x00\x00\x00\x01"
611
+
612
+ # Read and check header of file
613
+ header = self._file.read(HEADER_LENGTH)
614
+ if header != file_header:
615
+ raise RuntimeError("The LFP file header is invalid.")
616
+
617
+ # Read first bytes to skip header
618
+ self._file.read(SIZE_LENGTH)
619
+
620
+ def _find_chunks(self):
621
+ """
622
+ Gets start position and size of data chunks in file.
623
+ """
624
+ chunk_header = b"\x89LFC\x0D\x0A\x1A\x0A\x00\x00\x00\x00"
625
+
626
+ for i in range(0, DATA_CHUNKS_F01):
627
+ data_pos, size, sha1 = self._get_chunk(chunk_header)
628
+ self._chunks[sha1] = (data_pos, size)
629
+
630
+ def _find_meta(self):
631
+ """
632
+ Gets a data chunk that contains information over content
633
+ of other data chunks.
634
+ """
635
+ meta_header = b"\x89LFM\x0D\x0A\x1A\x0A\x00\x00\x00\x00"
636
+
637
+ data_pos, size, sha1 = self._get_chunk(meta_header)
638
+
639
+ # Get content
640
+ self._file.seek(data_pos, 0)
641
+ data = self._file.read(size)
642
+ self._content = json.loads(data.decode("ASCII"))
643
+ data = self._file.read(5) # Skip 5
644
+
645
+ def _get_chunk(self, header):
646
+ """
647
+ Checks if chunk has correct header and skips it.
648
+ Finds start position and length of next chunk and reads
649
+ sha1-string that identifies the following data chunk.
650
+
651
+ Parameters
652
+ ----------
653
+ header : bytes
654
+ Byte string that identifies start of chunk.
655
+
656
+ Returns
657
+ -------
658
+ data_pos : int
659
+ Start position of data chunk in file.
660
+ size : int
661
+ Size of data chunk.
662
+ sha1 : str
663
+ Sha1 value of chunk.
664
+ """
665
+ # Read and check header of chunk
666
+ header_chunk = self._file.read(HEADER_LENGTH)
667
+ if header_chunk != header:
668
+ raise RuntimeError("The LFP chunk header is invalid.")
669
+
670
+ data_pos = None
671
+ sha1 = None
672
+
673
+ # Read size
674
+ size = struct.unpack(">i", self._file.read(SIZE_LENGTH))[0]
675
+ if size > 0:
676
+ # Read sha1
677
+ sha1 = str(self._file.read(SHA1_LENGTH).decode("ASCII"))
678
+ # Skip fixed null chars
679
+ self._file.read(PADDING_LENGTH)
680
+ # Find start of data and skip data
681
+ data_pos = self._file.tell()
682
+ self._file.seek(size, 1)
683
+ # Skip extra null chars
684
+ ch = self._file.read(1)
685
+ while ch == b"\0":
686
+ ch = self._file.read(1)
687
+ self._file.seek(-1, 1)
688
+
689
+ return data_pos, size, sha1
690
+
691
+ def _get_data(self, index):
692
+ # Return the data and meta data for the given index
693
+ if index not in [0, None]:
694
+ raise IndexError("Lytro lfp file contains only one dataset")
695
+
696
+ if not self._meta_only:
697
+ # Read bytes from string and convert to uint16
698
+ raw = np.frombuffer(self.raw_image_data, dtype=np.uint8).astype(
699
+ np.uint16
700
+ )
701
+ im = LytroF01RawFormat.rearrange_bits(raw)
702
+ else:
703
+ im = np.array([])
704
+
705
+ # Return array and dummy meta data
706
+ return im, self.metadata
707
+
708
+ def _get_meta_data(self, index):
709
+ # Get the meta data for the given index. If index is None,
710
+ # it returns the global meta data.
711
+ if index not in [0, None]:
712
+ raise IndexError("Lytro meta data file contains only one dataset")
713
+
714
+ return self.metadata
minigpt2/lib/python3.10/site-packages/imageio/plugins/tifffile.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write TIFF files.
5
+
6
+ Backend: internal
7
+
8
+ Provides support for a wide range of Tiff images using the tifffile
9
+ backend.
10
+
11
+ Parameters for reading
12
+ ----------------------
13
+ offset : int
14
+ Optional start position of embedded file. By default this is
15
+ the current file position.
16
+ size : int
17
+ Optional size of embedded file. By default this is the number
18
+ of bytes from the 'offset' to the end of the file.
19
+ multifile : bool
20
+ If True (default), series may include pages from multiple files.
21
+ Currently applies to OME-TIFF only.
22
+ multifile_close : bool
23
+ If True (default), keep the handles of other files in multifile
24
+ series closed. This is inefficient when few files refer to
25
+ many pages. If False, the C runtime may run out of resources.
26
+
27
+ Parameters for saving
28
+ ---------------------
29
+ bigtiff : bool
30
+ If True, the BigTIFF format is used.
31
+ byteorder : {'<', '>'}
32
+ The endianness of the data in the file.
33
+ By default this is the system's native byte order.
34
+ software : str
35
+ Name of the software used to create the image.
36
+ Saved with the first page only.
37
+
38
+ Metadata for reading
39
+ --------------------
40
+ planar_configuration : {'contig', 'planar'}
41
+ Specifies if samples are stored contiguous or in separate planes.
42
+ By default this setting is inferred from the data shape.
43
+ 'contig': last dimension contains samples.
44
+ 'planar': third last dimension contains samples.
45
+ resolution_unit : int
46
+ The resolution unit stored in the TIFF tag. Usually 1 means no/unknown unit,
47
+ 2 means dpi (inch), 3 means dpc (centimeter).
48
+ resolution : (float, float, str)
49
+ A tuple formatted as (X_resolution, Y_resolution, unit). The unit is a
50
+ string representing one of the following units::
51
+
52
+ NONE # No unit or unit unknown
53
+ INCH # dpi
54
+ CENTIMETER # cpi
55
+ MILLIMETER
56
+ MICROMETER
57
+
58
+ compression : int
59
+ Value indicating the compression algorithm used, e.g. 5 is LZW,
60
+ 7 is JPEG, 8 is deflate.
61
+ If 1, data are uncompressed.
62
+ predictor : int
63
+ Value 2 indicates horizontal differencing was used before compression,
64
+ while 3 indicates floating point horizontal differencing.
65
+ If 1, no prediction scheme was used before compression.
66
+ orientation : {'top_left', 'bottom_right', ...}
67
+ Oriented of image array.
68
+ is_rgb : bool
69
+ True if page contains a RGB image.
70
+ is_contig : bool
71
+ True if page contains a contiguous image.
72
+ is_tiled : bool
73
+ True if page contains tiled image.
74
+ is_palette : bool
75
+ True if page contains a palette-colored image and not OME or STK.
76
+ is_reduced : bool
77
+ True if page is a reduced image of another image.
78
+ is_shaped : bool
79
+ True if page contains shape in image_description tag.
80
+ is_fluoview : bool
81
+ True if page contains FluoView MM_STAMP tag.
82
+ is_nih : bool
83
+ True if page contains NIH image header.
84
+ is_micromanager : bool
85
+ True if page contains Micro-Manager metadata.
86
+ is_ome : bool
87
+ True if page contains OME-XML in image_description tag.
88
+ is_sgi : bool
89
+ True if page contains SGI image and tile depth tags.
90
+ is_mdgel : bool
91
+ True if page contains md_file_tag tag.
92
+ is_mediacy : bool
93
+ True if page contains Media Cybernetics Id tag.
94
+ is_stk : bool
95
+ True if page contains UIC2Tag tag.
96
+ is_lsm : bool
97
+ True if page contains LSM CZ_LSM_INFO tag.
98
+ description : str
99
+ Image description
100
+ description1 : str
101
+ Additional description
102
+ is_imagej : None or str
103
+ ImageJ metadata
104
+ software : str
105
+ Software used to create the TIFF file
106
+ datetime : datetime.datetime
107
+ Creation date and time
108
+
109
+ Metadata for writing
110
+ --------------------
111
+ photometric : {'minisblack', 'miniswhite', 'rgb'}
112
+ The color space of the image data.
113
+ By default this setting is inferred from the data shape.
114
+ planarconfig : {'contig', 'planar'}
115
+ Specifies if samples are stored contiguous or in separate planes.
116
+ By default this setting is inferred from the data shape.
117
+ 'contig': last dimension contains samples.
118
+ 'planar': third last dimension contains samples.
119
+ resolution : (float, float) or ((int, int), (int, int))
120
+ X and Y resolution in dots per inch as float or rational numbers.
121
+ description : str
122
+ The subject of the image. Saved with the first page only.
123
+ compress : int
124
+ Values from 0 to 9 controlling the level of zlib (deflate) compression.
125
+ If 0, data are written uncompressed (default).
126
+ compression : str, (int, int)
127
+ Compression scheme used while writing the image. If omitted (default) the
128
+ image is not uncompressed. Compression cannot be used to write contiguous
129
+ series. Compressors may require certain data shapes, types or value ranges.
130
+ For example, JPEG compression requires grayscale or RGB(A), uint8 or 12-bit
131
+ uint16. JPEG compression is experimental. JPEG markers and TIFF tags may not
132
+ match. Only a limited set of compression schemes are implemented. 'ZLIB' is
133
+ short for ADOBE_DEFLATE. The value is written to the Compression tag.
134
+ compressionargs:
135
+ Extra arguments passed to compression codec, e.g., compression level. Refer
136
+ to the Imagecodecs implementation for supported arguments.
137
+ predictor : bool
138
+ If True, horizontal differencing is applied before compression.
139
+ Note that using an int literal 1 actually means no prediction scheme
140
+ will be used.
141
+ volume : bool
142
+ If True, volume data are stored in one tile (if applicable) using
143
+ the SGI image_depth and tile_depth tags.
144
+ Image width and depth must be multiple of 16.
145
+ Few software can read this format, e.g. MeVisLab.
146
+ writeshape : bool
147
+ If True, write the data shape to the image_description tag
148
+ if necessary and no other description is given.
149
+ extratags: sequence of tuples
150
+ Additional tags as [(code, dtype, count, value, writeonce)].
151
+
152
+ code : int
153
+ The TIFF tag Id.
154
+ dtype : str
155
+ Data type of items in 'value' in Python struct format.
156
+ One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
157
+ count : int
158
+ Number of data values. Not used for string values.
159
+ value : sequence
160
+ 'Count' values compatible with 'dtype'.
161
+ writeonce : bool
162
+ If True, the tag is written to the first page only.
163
+
164
+ Notes
165
+ -----
166
+ Global metadata is stored with the first frame in a TIFF file.
167
+ Thus calling :py:meth:`Format.Writer.set_meta_data` after the first frame
168
+ was written has no effect. Also, global metadata is ignored if metadata is
169
+ provided via the `meta` argument of :py:meth:`Format.Writer.append_data`.
170
+
171
+ If you have installed tifffile as a Python package, imageio will attempt
172
+ to use that as backend instead of the bundled backend. Doing so can
173
+ provide access to new performance improvements and bug fixes.
174
+
175
+ """
176
+
177
+ import datetime
178
+
179
+ from ..core import Format
180
+ from ..core.request import URI_BYTES, URI_FILE
181
+
182
+ import numpy as np
183
+ import warnings
184
+
185
+
186
+ try:
187
+ import tifffile as _tifffile
188
+ except ImportError:
189
+ warnings.warn(
190
+ "ImageIO's vendored tifffile backend is deprecated and will be"
191
+ " removed in ImageIO v3. Install the tifffile directly:"
192
+ " `pip install imageio[tifffile]`",
193
+ DeprecationWarning,
194
+ )
195
+ from . import _tifffile
196
+
197
+
198
+ TIFF_FORMATS = (".tif", ".tiff", ".stk", ".lsm")
199
+ WRITE_METADATA_KEYS = (
200
+ "photometric",
201
+ "planarconfig",
202
+ "resolution",
203
+ "description",
204
+ "compress",
205
+ "compression",
206
+ "compressionargs",
207
+ "predictor",
208
+ "volume",
209
+ "writeshape",
210
+ "extratags",
211
+ "datetime",
212
+ )
213
+ READ_METADATA_KEYS = (
214
+ "planar_configuration",
215
+ "is_fluoview",
216
+ "is_nih",
217
+ "is_contig",
218
+ "is_micromanager",
219
+ "is_ome",
220
+ "is_lsm",
221
+ "is_palette",
222
+ "is_reduced",
223
+ "is_rgb",
224
+ "is_sgi",
225
+ "is_shaped",
226
+ "is_stk",
227
+ "is_tiled",
228
+ "is_mdgel",
229
+ "resolution_unit",
230
+ "compression",
231
+ "predictor",
232
+ "is_mediacy",
233
+ "orientation",
234
+ "description",
235
+ "description1",
236
+ "is_imagej",
237
+ "software",
238
+ )
239
+
240
+
241
+ class TiffFormat(Format):
242
+ """Provides support for a wide range of Tiff images using the tifffile
243
+ backend.
244
+
245
+ Images that contain multiple pages can be read using ``imageio.mimread()``
246
+ to read the individual pages, or ``imageio.volread()`` to obtain a
247
+ single (higher dimensional) array.
248
+
249
+ Note that global metadata is stored with the first frame in a TIFF file.
250
+ Thus calling :py:meth:`Format.Writer.set_meta_data` after the first frame
251
+ was written has no effect. Also, global metadata is ignored if metadata is
252
+ provided via the `meta` argument of :py:meth:`Format.Writer.append_data`.
253
+
254
+ If you have installed tifffile as a Python package, imageio will attempt
255
+ to use that as backend instead of the bundled backend. Doing so can
256
+ provide access to new performance improvements and bug fixes.
257
+
258
+ Parameters for reading
259
+ ----------------------
260
+ offset : int
261
+ Optional start position of embedded file. By default this is
262
+ the current file position.
263
+ size : int
264
+ Optional size of embedded file. By default this is the number
265
+ of bytes from the 'offset' to the end of the file.
266
+ multifile : bool
267
+ If True (default), series may include pages from multiple files.
268
+ Currently applies to OME-TIFF only.
269
+ multifile_close : bool
270
+ If True (default), keep the handles of other files in multifile
271
+ series closed. This is inefficient when few files refer to
272
+ many pages. If False, the C runtime may run out of resources.
273
+
274
+ Parameters for saving
275
+ ---------------------
276
+ bigtiff : bool
277
+ If True, the BigTIFF format is used.
278
+ byteorder : {'<', '>'}
279
+ The endianness of the data in the file.
280
+ By default this is the system's native byte order.
281
+ software : str
282
+ Name of the software used to create the image.
283
+ Saved with the first page only.
284
+
285
+ Metadata for reading
286
+ --------------------
287
+ planar_configuration : {'contig', 'planar'}
288
+ Specifies if samples are stored contiguous or in separate planes.
289
+ By default this setting is inferred from the data shape.
290
+ 'contig': last dimension contains samples.
291
+ 'planar': third last dimension contains samples.
292
+ resolution_unit : (float, float) or ((int, int), (int, int))
293
+ X and Y resolution in dots per inch as float or rational numbers.
294
+ compression : int
295
+ Value indicating the compression algorithm used, e.g. 5 is LZW,
296
+ 7 is JPEG, 8 is deflate.
297
+ If 1, data are uncompressed.
298
+ predictor : int
299
+ Value 2 indicates horizontal differencing was used before compression,
300
+ while 3 indicates floating point horizontal differencing.
301
+ If 1, no prediction scheme was used before compression.
302
+ orientation : {'top_left', 'bottom_right', ...}
303
+ Oriented of image array.
304
+ is_rgb : bool
305
+ True if page contains a RGB image.
306
+ is_contig : bool
307
+ True if page contains a contiguous image.
308
+ is_tiled : bool
309
+ True if page contains tiled image.
310
+ is_palette : bool
311
+ True if page contains a palette-colored image and not OME or STK.
312
+ is_reduced : bool
313
+ True if page is a reduced image of another image.
314
+ is_shaped : bool
315
+ True if page contains shape in image_description tag.
316
+ is_fluoview : bool
317
+ True if page contains FluoView MM_STAMP tag.
318
+ is_nih : bool
319
+ True if page contains NIH image header.
320
+ is_micromanager : bool
321
+ True if page contains Micro-Manager metadata.
322
+ is_ome : bool
323
+ True if page contains OME-XML in image_description tag.
324
+ is_sgi : bool
325
+ True if page contains SGI image and tile depth tags.
326
+ is_stk : bool
327
+ True if page contains UIC2Tag tag.
328
+ is_mdgel : bool
329
+ True if page contains md_file_tag tag.
330
+ is_mediacy : bool
331
+ True if page contains Media Cybernetics Id tag.
332
+ is_stk : bool
333
+ True if page contains UIC2Tag tag.
334
+ is_lsm : bool
335
+ True if page contains LSM CZ_LSM_INFO tag.
336
+ description : str
337
+ Image description
338
+ description1 : str
339
+ Additional description
340
+ is_imagej : None or str
341
+ ImageJ metadata
342
+ software : str
343
+ Software used to create the TIFF file
344
+ datetime : datetime.datetime
345
+ Creation date and time
346
+
347
+ Metadata for writing
348
+ --------------------
349
+ photometric : {'minisblack', 'miniswhite', 'rgb'}
350
+ The color space of the image data.
351
+ By default this setting is inferred from the data shape.
352
+ planarconfig : {'contig', 'planar'}
353
+ Specifies if samples are stored contiguous or in separate planes.
354
+ By default this setting is inferred from the data shape.
355
+ 'contig': last dimension contains samples.
356
+ 'planar': third last dimension contains samples.
357
+ resolution : (float, float) or ((int, int), (int, int))
358
+ X and Y resolution in dots per inch as float or rational numbers.
359
+ description : str
360
+ The subject of the image. Saved with the first page only.
361
+ compress : int
362
+ Values from 0 to 9 controlling the level of zlib (deflate) compression.
363
+ If 0, data are written uncompressed (default).
364
+ predictor : bool
365
+ If True, horizontal differencing is applied before compression.
366
+ Note that using an int literal 1 actually means no prediction scheme
367
+ will be used.
368
+ volume : bool
369
+ If True, volume data are stored in one tile (if applicable) using
370
+ the SGI image_depth and tile_depth tags.
371
+ Image width and depth must be multiple of 16.
372
+ Few software can read this format, e.g. MeVisLab.
373
+ writeshape : bool
374
+ If True, write the data shape to the image_description tag
375
+ if necessary and no other description is given.
376
+ extratags: sequence of tuples
377
+ Additional tags as [(code, dtype, count, value, writeonce)].
378
+
379
+ code : int
380
+ The TIFF tag Id.
381
+ dtype : str
382
+ Data type of items in 'value' in Python struct format.
383
+ One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
384
+ count : int
385
+ Number of data values. Not used for string values.
386
+ value : sequence
387
+ 'Count' values compatible with 'dtype'.
388
+ writeonce : bool
389
+ If True, the tag is written to the first page only.
390
+ """
391
+
392
+ def _can_read(self, request):
393
+ try:
394
+ _tifffile.TiffFile(request.get_file(), **request.kwargs)
395
+ except ValueError:
396
+ # vendored backend raises value exception
397
+ return False
398
+ except _tifffile.TiffFileError: # pragma: no-cover
399
+ # current version raises custom exception
400
+ return False
401
+ finally:
402
+ request.get_file().seek(0)
403
+
404
+ return True
405
+
406
+ def _can_write(self, request):
407
+ if request._uri_type in [URI_FILE, URI_BYTES]:
408
+ pass # special URI
409
+ elif request.extension not in self.extensions:
410
+ return False
411
+
412
+ try:
413
+ _tifffile.TiffWriter(request.get_file(), **request.kwargs)
414
+ except ValueError:
415
+ # vendored backend raises value exception
416
+ return False
417
+ except _tifffile.TiffFileError: # pragma: no-cover
418
+ # current version raises custom exception
419
+ return False
420
+ finally:
421
+ request.get_file().seek(0)
422
+ return True
423
+
424
+ # -- reader
425
+
426
+ class Reader(Format.Reader):
427
+ def _open(self, **kwargs):
428
+ # Allow loading from http; tifffile uses seek, so download first
429
+ if self.request.filename.startswith(("http://", "https://")):
430
+ self._f = f = open(self.request.get_local_filename(), "rb")
431
+ else:
432
+ self._f = None
433
+ f = self.request.get_file()
434
+ self._tf = _tifffile.TiffFile(f, **kwargs)
435
+
436
+ def _close(self):
437
+ self._tf.close()
438
+ if self._f is not None:
439
+ self._f.close()
440
+
441
+ def _get_length(self):
442
+ return len(self._tf.series)
443
+
444
+ def _get_data(self, index):
445
+ if index < 0 or index >= self._get_length():
446
+ raise IndexError("Index out of range while reading from tiff file")
447
+
448
+ im = self._tf.asarray(series=index)
449
+ meta = self._get_meta_data(index)
450
+
451
+ return im, meta
452
+
453
+ def _get_meta_data(self, index):
454
+ meta = {}
455
+ page = self._tf.pages[index or 0]
456
+ for key in READ_METADATA_KEYS:
457
+ try:
458
+ meta[key] = getattr(page, key)
459
+ except Exception:
460
+ pass
461
+
462
+ # tifffile <= 0.12.1 use datetime, newer use DateTime
463
+ for key in ("datetime", "DateTime"):
464
+ try:
465
+ meta["datetime"] = datetime.datetime.strptime(
466
+ page.tags[key].value, "%Y:%m:%d %H:%M:%S"
467
+ )
468
+ break
469
+ except Exception:
470
+ pass
471
+
472
+ if 296 in page.tags:
473
+ meta["resolution_unit"] = page.tags[296].value.value
474
+
475
+ if 282 in page.tags and 283 in page.tags and 296 in page.tags:
476
+ resolution_x = page.tags[282].value
477
+ resolution_y = page.tags[283].value
478
+ if resolution_x[1] == 0 or resolution_y[1] == 0:
479
+ warnings.warn(
480
+ "Ignoring resolution metadata, "
481
+ "because at least one direction has a 0 denominator.",
482
+ RuntimeWarning,
483
+ )
484
+ else:
485
+ meta["resolution"] = (
486
+ resolution_x[0] / resolution_x[1],
487
+ resolution_y[0] / resolution_y[1],
488
+ page.tags[296].value.name,
489
+ )
490
+
491
+ return meta
492
+
493
+ # -- writer
494
+ class Writer(Format.Writer):
495
+ def _open(self, bigtiff=None, byteorder=None, software=None):
496
+ try:
497
+ self._tf = _tifffile.TiffWriter(
498
+ self.request.get_file(),
499
+ bigtiff=bigtiff,
500
+ byteorder=byteorder,
501
+ software=software,
502
+ )
503
+ self._software = None
504
+ except TypeError:
505
+ # In tifffile >= 0.15, the `software` arg is passed to
506
+ # TiffWriter.save
507
+ self._tf = _tifffile.TiffWriter(
508
+ self.request.get_file(), bigtiff=bigtiff, byteorder=byteorder
509
+ )
510
+ self._software = software
511
+
512
+ self._meta = {}
513
+ self._frames_written = 0
514
+
515
+ def _close(self):
516
+ self._tf.close()
517
+
518
+ def _append_data(self, im, meta):
519
+ if meta is not None:
520
+ meta = self._sanitize_meta(meta)
521
+ else:
522
+ # Use global metadata for first frame
523
+ meta = self._meta if self._frames_written == 0 else {}
524
+ if self._software is not None and self._frames_written == 0:
525
+ meta["software"] = self._software
526
+ # No need to check self.request.mode; tifffile figures out whether
527
+ # this is a single page, or all page data at once.
528
+ try:
529
+ # TiffWriter.save has been deprecated in version 2020.9.30
530
+ write_meth = self._tf.write
531
+ except AttributeError:
532
+ write_meth = self._tf.save
533
+ write_meth(np.asanyarray(im), contiguous=False, **meta)
534
+ self._frames_written += 1
535
+
536
+ @staticmethod
537
+ def _sanitize_meta(meta):
538
+ ret = {}
539
+ for key, value in meta.items():
540
+ if key in WRITE_METADATA_KEYS:
541
+ # Special case of previously read `predictor` int value
542
+ # 1(=NONE) translation to False expected by TiffWriter.save
543
+ if key == "predictor" and not isinstance(value, bool):
544
+ ret[key] = value > 1
545
+ elif key == "compress" and value != 0:
546
+ warnings.warn(
547
+ "The use of `compress` is deprecated. Use `compression` and `compressionargs` instead.",
548
+ DeprecationWarning,
549
+ )
550
+
551
+ if _tifffile.__version__ < "2022":
552
+ ret["compression"] = (8, value)
553
+ else:
554
+ ret["compression"] = "zlib"
555
+ ret["compressionargs"] = {"level": value}
556
+ else:
557
+ ret[key] = value
558
+ return ret
559
+
560
+ def set_meta_data(self, meta):
561
+ self._meta = self._sanitize_meta(meta)
minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/base_collective_group.cpython-310.pyc ADDED
Binary file (3.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/cuda_stream.cpython-310.pyc ADDED
Binary file (2.88 kB). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/gloo_collective_group.cpython-310.pyc ADDED
Binary file (17 kB). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/gloo_util.cpython-310.pyc ADDED
Binary file (8.77 kB). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/collective/collective_group/__pycache__/nccl_util.cpython-310.pyc ADDED
Binary file (7.29 kB). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from multiprocessing import TimeoutError, JoinableQueue
2
+
3
+ from .pool import Pool
4
+
5
+ __all__ = ["Pool", "TimeoutError", "JoinableQueue"]
minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (328 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/__pycache__/pool.cpython-310.pyc ADDED
Binary file (30.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/ray/util/multiprocessing/pool.py ADDED
@@ -0,0 +1,995 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import copy
3
+ import gc
4
+ import itertools
5
+ import logging
6
+ import os
7
+ import queue
8
+ import sys
9
+ import threading
10
+ import time
11
+ from multiprocessing import TimeoutError
12
+ from typing import Any, Callable, Dict, Hashable, Iterable, List, Optional, Tuple
13
+
14
+ import ray
15
+ from ray._private.usage import usage_lib
16
+ from ray.util import log_once
17
+
18
+ try:
19
+ from joblib._parallel_backends import SafeFunction
20
+ from joblib.parallel import BatchedCalls, parallel_backend
21
+ except ImportError:
22
+ BatchedCalls = None
23
+ parallel_backend = None
24
+ SafeFunction = None
25
+
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ RAY_ADDRESS_ENV = "RAY_ADDRESS"
30
+
31
+
32
+ def _put_in_dict_registry(
33
+ obj: Any, registry_hashable: Dict[Hashable, ray.ObjectRef]
34
+ ) -> ray.ObjectRef:
35
+ if obj not in registry_hashable:
36
+ ret = ray.put(obj)
37
+ registry_hashable[obj] = ret
38
+ else:
39
+ ret = registry_hashable[obj]
40
+ return ret
41
+
42
+
43
+ def _put_in_list_registry(
44
+ obj: Any, registry: List[Tuple[Any, ray.ObjectRef]]
45
+ ) -> ray.ObjectRef:
46
+ try:
47
+ ret = next((ref for o, ref in registry if o is obj))
48
+ except StopIteration:
49
+ ret = ray.put(obj)
50
+ registry.append((obj, ret))
51
+ return ret
52
+
53
+
54
+ def ray_put_if_needed(
55
+ obj: Any,
56
+ registry: Optional[List[Tuple[Any, ray.ObjectRef]]] = None,
57
+ registry_hashable: Optional[Dict[Hashable, ray.ObjectRef]] = None,
58
+ ) -> ray.ObjectRef:
59
+ """ray.put obj in object store if it's not an ObjRef and bigger than 100 bytes,
60
+ with support for list and dict registries"""
61
+ if isinstance(obj, ray.ObjectRef) or sys.getsizeof(obj) < 100:
62
+ return obj
63
+ ret = obj
64
+ if registry_hashable is not None:
65
+ try:
66
+ ret = _put_in_dict_registry(obj, registry_hashable)
67
+ except TypeError:
68
+ if registry is not None:
69
+ ret = _put_in_list_registry(obj, registry)
70
+ elif registry is not None:
71
+ ret = _put_in_list_registry(obj, registry)
72
+ return ret
73
+
74
+
75
+ def ray_get_if_needed(obj: Any) -> Any:
76
+ """If obj is an ObjectRef, do ray.get, otherwise return obj"""
77
+ if isinstance(obj, ray.ObjectRef):
78
+ return ray.get(obj)
79
+ return obj
80
+
81
+
82
+ if BatchedCalls is not None:
83
+
84
+ class RayBatchedCalls(BatchedCalls):
85
+ """Joblib's BatchedCalls with basic Ray object store management
86
+
87
+ This functionality is provided through the put_items_in_object_store,
88
+ which uses external registries (list and dict) containing objects
89
+ and their ObjectRefs."""
90
+
91
+ def put_items_in_object_store(
92
+ self,
93
+ registry: Optional[List[Tuple[Any, ray.ObjectRef]]] = None,
94
+ registry_hashable: Optional[Dict[Hashable, ray.ObjectRef]] = None,
95
+ ):
96
+ """Puts all applicable (kw)args in self.items in object store
97
+
98
+ Takes two registries - list for unhashable objects and dict
99
+ for hashable objects. The registries are a part of a Pool object.
100
+ The method iterates through all entries in items list (usually,
101
+ there will be only one, but the number depends on joblib Parallel
102
+ settings) and puts all of the args and kwargs into the object
103
+ store, updating the registries.
104
+ If an arg or kwarg is already in a registry, it will not be
105
+ put again, and instead, the cached object ref will be used."""
106
+ new_items = []
107
+ for func, args, kwargs in self.items:
108
+ args = [
109
+ ray_put_if_needed(arg, registry, registry_hashable) for arg in args
110
+ ]
111
+ kwargs = {
112
+ k: ray_put_if_needed(v, registry, registry_hashable)
113
+ for k, v in kwargs.items()
114
+ }
115
+ new_items.append((func, args, kwargs))
116
+ self.items = new_items
117
+
118
+ def __call__(self):
119
+ # Exactly the same as in BatchedCalls, with the
120
+ # difference being that it gets args and kwargs from
121
+ # object store (which have been put in there by
122
+ # put_items_in_object_store)
123
+
124
+ # Set the default nested backend to self._backend but do
125
+ # not set the change the default number of processes to -1
126
+ with parallel_backend(self._backend, n_jobs=self._n_jobs):
127
+ return [
128
+ func(
129
+ *[ray_get_if_needed(arg) for arg in args],
130
+ **{k: ray_get_if_needed(v) for k, v in kwargs.items()},
131
+ )
132
+ for func, args, kwargs in self.items
133
+ ]
134
+
135
+ def __reduce__(self):
136
+ # Exactly the same as in BatchedCalls, with the
137
+ # difference being that it returns RayBatchedCalls
138
+ # instead
139
+ if self._reducer_callback is not None:
140
+ self._reducer_callback()
141
+ # no need pickle the callback.
142
+ return (
143
+ RayBatchedCalls,
144
+ (self.items, (self._backend, self._n_jobs), None, self._pickle_cache),
145
+ )
146
+
147
+ else:
148
+ RayBatchedCalls = None
149
+
150
+
151
+ # Helper function to divide a by b and round the result up.
152
+ def div_round_up(a, b):
153
+ return -(-a // b)
154
+
155
+
156
+ class PoolTaskError(Exception):
157
+ def __init__(self, underlying):
158
+ self.underlying = underlying
159
+
160
+
161
+ class ResultThread(threading.Thread):
162
+ """Thread that collects results from distributed actors.
163
+
164
+ It winds down when either:
165
+ - A pre-specified number of objects has been processed
166
+ - When the END_SENTINEL (submitted through self.add_object_ref())
167
+ has been received and all objects received before that have been
168
+ processed.
169
+
170
+ Initialize the thread with total_object_refs = float('inf') to wait for the
171
+ END_SENTINEL.
172
+
173
+ Args:
174
+ object_refs (List[RayActorObjectRefs]): ObjectRefs to Ray Actor calls.
175
+ Thread tracks whether they are ready. More ObjectRefs may be added
176
+ with add_object_ref (or _add_object_ref internally) until the object
177
+ count reaches total_object_refs.
178
+ single_result: Should be True if the thread is managing function
179
+ with a single result (like apply_async). False if the thread is managing
180
+ a function with a List of results.
181
+ callback: called only once at the end of the thread
182
+ if no results were errors. If single_result=True, and result is
183
+ not an error, callback is invoked with the result as the only
184
+ argument. If single_result=False, callback is invoked with
185
+ a list of all the results as the only argument.
186
+ error_callback: called only once on the first result
187
+ that errors. Should take an Exception as the only argument.
188
+ If no result errors, this callback is not called.
189
+ total_object_refs: Number of ObjectRefs that this thread
190
+ expects to be ready. May be more than len(object_refs) since
191
+ more ObjectRefs can be submitted after the thread starts.
192
+ If None, defaults to len(object_refs). If float("inf"), thread runs
193
+ until END_SENTINEL (submitted through self.add_object_ref())
194
+ has been received and all objects received before that have
195
+ been processed.
196
+ """
197
+
198
+ END_SENTINEL = None
199
+
200
+ def __init__(
201
+ self,
202
+ object_refs: list,
203
+ single_result: bool = False,
204
+ callback: callable = None,
205
+ error_callback: callable = None,
206
+ total_object_refs: Optional[int] = None,
207
+ ):
208
+ threading.Thread.__init__(self, daemon=True)
209
+ self._got_error = False
210
+ self._object_refs = []
211
+ self._num_ready = 0
212
+ self._results = []
213
+ self._ready_index_queue = queue.Queue()
214
+ self._single_result = single_result
215
+ self._callback = callback
216
+ self._error_callback = error_callback
217
+ self._total_object_refs = total_object_refs or len(object_refs)
218
+ self._indices = {}
219
+ # Thread-safe queue used to add ObjectRefs to fetch after creating
220
+ # this thread (used to lazily submit for imap and imap_unordered).
221
+ self._new_object_refs = queue.Queue()
222
+ for object_ref in object_refs:
223
+ self._add_object_ref(object_ref)
224
+
225
+ def _add_object_ref(self, object_ref):
226
+ self._indices[object_ref] = len(self._object_refs)
227
+ self._object_refs.append(object_ref)
228
+ self._results.append(None)
229
+
230
+ def add_object_ref(self, object_ref):
231
+ self._new_object_refs.put(object_ref)
232
+
233
+ def run(self):
234
+ unready = copy.copy(self._object_refs)
235
+ aggregated_batch_results = []
236
+
237
+ # Run for a specific number of objects if self._total_object_refs is finite.
238
+ # Otherwise, process all objects received prior to the stop signal, given by
239
+ # self.add_object(END_SENTINEL).
240
+ while self._num_ready < self._total_object_refs:
241
+ # Get as many new IDs from the queue as possible without blocking,
242
+ # unless we have no IDs to wait on, in which case we block.
243
+ while True:
244
+ try:
245
+ block = len(unready) == 0
246
+ new_object_ref = self._new_object_refs.get(block=block)
247
+ if new_object_ref is self.END_SENTINEL:
248
+ # Receiving the END_SENTINEL object is the signal to stop.
249
+ # Store the total number of objects.
250
+ self._total_object_refs = len(self._object_refs)
251
+ else:
252
+ self._add_object_ref(new_object_ref)
253
+ unready.append(new_object_ref)
254
+ except queue.Empty:
255
+ # queue.Empty means no result was retrieved if block=False.
256
+ break
257
+
258
+ [ready_id], unready = ray.wait(unready, num_returns=1)
259
+ try:
260
+ batch = ray.get(ready_id)
261
+ except ray.exceptions.RayError as e:
262
+ batch = [e]
263
+
264
+ # The exception callback is called only once on the first result
265
+ # that errors. If no result errors, it is never called.
266
+ if not self._got_error:
267
+ for result in batch:
268
+ if isinstance(result, Exception):
269
+ self._got_error = True
270
+ if self._error_callback is not None:
271
+ self._error_callback(result)
272
+ break
273
+ else:
274
+ aggregated_batch_results.append(result)
275
+
276
+ self._num_ready += 1
277
+ self._results[self._indices[ready_id]] = batch
278
+ self._ready_index_queue.put(self._indices[ready_id])
279
+
280
+ # The regular callback is called only once on the entire List of
281
+ # results as long as none of the results were errors. If any results
282
+ # were errors, the regular callback is never called; instead, the
283
+ # exception callback is called on the first erroring result.
284
+ #
285
+ # This callback is called outside the while loop to ensure that it's
286
+ # called on the entire list of results– not just a single batch.
287
+ if not self._got_error and self._callback is not None:
288
+ if not self._single_result:
289
+ self._callback(aggregated_batch_results)
290
+ else:
291
+ # On a thread handling a function with a single result
292
+ # (e.g. apply_async), we call the callback on just that result
293
+ # instead of on a list encaspulating that result
294
+ self._callback(aggregated_batch_results[0])
295
+
296
+ def got_error(self):
297
+ # Should only be called after the thread finishes.
298
+ return self._got_error
299
+
300
+ def result(self, index):
301
+ # Should only be called on results that are ready.
302
+ return self._results[index]
303
+
304
+ def results(self):
305
+ # Should only be called after the thread finishes.
306
+ return self._results
307
+
308
+ def next_ready_index(self, timeout=None):
309
+ try:
310
+ return self._ready_index_queue.get(timeout=timeout)
311
+ except queue.Empty:
312
+ # queue.Queue signals a timeout by raising queue.Empty.
313
+ raise TimeoutError
314
+
315
+
316
+ class AsyncResult:
317
+ """An asynchronous interface to task results.
318
+
319
+ This should not be constructed directly.
320
+ """
321
+
322
+ def __init__(
323
+ self, chunk_object_refs, callback=None, error_callback=None, single_result=False
324
+ ):
325
+ self._single_result = single_result
326
+ self._result_thread = ResultThread(
327
+ chunk_object_refs, single_result, callback, error_callback
328
+ )
329
+ self._result_thread.start()
330
+
331
+ def wait(self, timeout=None):
332
+ """
333
+ Returns once the result is ready or the timeout expires (does not
334
+ raise TimeoutError).
335
+
336
+ Args:
337
+ timeout: timeout in milliseconds.
338
+ """
339
+
340
+ self._result_thread.join(timeout)
341
+
342
+ def get(self, timeout=None):
343
+ self.wait(timeout)
344
+ if self._result_thread.is_alive():
345
+ raise TimeoutError
346
+
347
+ results = []
348
+ for batch in self._result_thread.results():
349
+ for result in batch:
350
+ if isinstance(result, PoolTaskError):
351
+ raise result.underlying
352
+ elif isinstance(result, Exception):
353
+ raise result
354
+ results.extend(batch)
355
+
356
+ if self._single_result:
357
+ return results[0]
358
+
359
+ return results
360
+
361
+ def ready(self):
362
+ """
363
+ Returns true if the result is ready, else false if the tasks are still
364
+ running.
365
+ """
366
+
367
+ return not self._result_thread.is_alive()
368
+
369
+ def successful(self):
370
+ """
371
+ Returns true if none of the submitted tasks errored, else false. Should
372
+ only be called once the result is ready (can be checked using `ready`).
373
+ """
374
+
375
+ if not self.ready():
376
+ raise ValueError(f"{self!r} not ready")
377
+ return not self._result_thread.got_error()
378
+
379
+
380
+ class IMapIterator:
381
+ """Base class for OrderedIMapIterator and UnorderedIMapIterator."""
382
+
383
+ def __init__(self, pool, func, iterable, chunksize=None):
384
+ self._pool = pool
385
+ self._func = func
386
+ self._next_chunk_index = 0
387
+ self._finished_iterating = False
388
+ # List of bools indicating if the given chunk is ready or not for all
389
+ # submitted chunks. Ordering mirrors that in the in the ResultThread.
390
+ self._submitted_chunks = []
391
+ self._ready_objects = collections.deque()
392
+ self._iterator = iter(iterable)
393
+ if isinstance(iterable, collections.abc.Iterator):
394
+ # Got iterator (which has no len() function).
395
+ # Make default chunksize 1 instead of using _calculate_chunksize().
396
+ # Indicate unknown queue length, requiring explicit stopping.
397
+ self._chunksize = chunksize or 1
398
+ result_list_size = float("inf")
399
+ else:
400
+ self._chunksize = chunksize or pool._calculate_chunksize(iterable)
401
+ result_list_size = div_round_up(len(iterable), chunksize)
402
+
403
+ self._result_thread = ResultThread([], total_object_refs=result_list_size)
404
+ self._result_thread.start()
405
+
406
+ for _ in range(len(self._pool._actor_pool)):
407
+ self._submit_next_chunk()
408
+
409
+ def _submit_next_chunk(self):
410
+ # The full iterable has already been submitted, so no-op.
411
+ if self._finished_iterating:
412
+ return
413
+
414
+ actor_index = len(self._submitted_chunks) % len(self._pool._actor_pool)
415
+ chunk_iterator = itertools.islice(self._iterator, self._chunksize)
416
+
417
+ # Check whether we have run out of samples.
418
+ # This consumes the original iterator, so we convert to a list and back
419
+ chunk_list = list(chunk_iterator)
420
+ if len(chunk_list) < self._chunksize:
421
+ # Reached end of self._iterator
422
+ self._finished_iterating = True
423
+ if len(chunk_list) == 0:
424
+ # Nothing to do, return.
425
+ return
426
+ chunk_iterator = iter(chunk_list)
427
+
428
+ new_chunk_id = self._pool._submit_chunk(
429
+ self._func, chunk_iterator, self._chunksize, actor_index
430
+ )
431
+ self._submitted_chunks.append(False)
432
+ # Wait for the result
433
+ self._result_thread.add_object_ref(new_chunk_id)
434
+ # If we submitted the final chunk, notify the result thread
435
+ if self._finished_iterating:
436
+ self._result_thread.add_object_ref(ResultThread.END_SENTINEL)
437
+
438
+ def __iter__(self):
439
+ return self
440
+
441
+ def __next__(self):
442
+ return self.next()
443
+
444
+ def next(self):
445
+ # Should be implemented by subclasses.
446
+ raise NotImplementedError
447
+
448
+
449
+ class OrderedIMapIterator(IMapIterator):
450
+ """Iterator to the results of tasks submitted using `imap`.
451
+
452
+ The results are returned in the same order that they were submitted, even
453
+ if they don't finish in that order. Only one batch of tasks per actor
454
+ process is submitted at a time - the rest are submitted as results come in.
455
+
456
+ Should not be constructed directly.
457
+ """
458
+
459
+ def next(self, timeout=None):
460
+ if len(self._ready_objects) == 0:
461
+ if self._finished_iterating and (
462
+ self._next_chunk_index == len(self._submitted_chunks)
463
+ ):
464
+ # Finish when all chunks have been dispatched and processed
465
+ # Notify the calling process that the work is done.
466
+ raise StopIteration
467
+
468
+ # This loop will break when the next index in order is ready or
469
+ # self._result_thread.next_ready_index() raises a timeout.
470
+ index = -1
471
+ while index != self._next_chunk_index:
472
+ start = time.time()
473
+ index = self._result_thread.next_ready_index(timeout=timeout)
474
+ self._submit_next_chunk()
475
+ self._submitted_chunks[index] = True
476
+ if timeout is not None:
477
+ timeout = max(0, timeout - (time.time() - start))
478
+
479
+ while (
480
+ self._next_chunk_index < len(self._submitted_chunks)
481
+ and self._submitted_chunks[self._next_chunk_index]
482
+ ):
483
+ for result in self._result_thread.result(self._next_chunk_index):
484
+ self._ready_objects.append(result)
485
+ self._next_chunk_index += 1
486
+
487
+ return self._ready_objects.popleft()
488
+
489
+
490
+ class UnorderedIMapIterator(IMapIterator):
491
+ """Iterator to the results of tasks submitted using `imap`.
492
+
493
+ The results are returned in the order that they finish. Only one batch of
494
+ tasks per actor process is submitted at a time - the rest are submitted as
495
+ results come in.
496
+
497
+ Should not be constructed directly.
498
+ """
499
+
500
+ def next(self, timeout=None):
501
+ if len(self._ready_objects) == 0:
502
+ if self._finished_iterating and (
503
+ self._next_chunk_index == len(self._submitted_chunks)
504
+ ):
505
+ # Finish when all chunks have been dispatched and processed
506
+ # Notify the calling process that the work is done.
507
+ raise StopIteration
508
+
509
+ index = self._result_thread.next_ready_index(timeout=timeout)
510
+ self._submit_next_chunk()
511
+
512
+ for result in self._result_thread.result(index):
513
+ self._ready_objects.append(result)
514
+ self._next_chunk_index += 1
515
+
516
+ return self._ready_objects.popleft()
517
+
518
+
519
+ @ray.remote(num_cpus=0)
520
+ class PoolActor:
521
+ """Actor used to process tasks submitted to a Pool."""
522
+
523
+ def __init__(self, initializer=None, initargs=None):
524
+ if initializer:
525
+ initargs = initargs or ()
526
+ initializer(*initargs)
527
+
528
+ def ping(self):
529
+ # Used to wait for this actor to be initialized.
530
+ pass
531
+
532
+ def run_batch(self, func, batch):
533
+ results = []
534
+ for args, kwargs in batch:
535
+ args = args or ()
536
+ kwargs = kwargs or {}
537
+ try:
538
+ results.append(func(*args, **kwargs))
539
+ except Exception as e:
540
+ results.append(PoolTaskError(e))
541
+ return results
542
+
543
+
544
+ # https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool
545
+ class Pool:
546
+ """A pool of actor processes that is used to process tasks in parallel.
547
+
548
+ Args:
549
+ processes: number of actor processes to start in the pool. Defaults to
550
+ the number of cores in the Ray cluster if one is already running,
551
+ otherwise the number of cores on this machine.
552
+ initializer: function to be run in each actor when it starts up.
553
+ initargs: iterable of arguments to the initializer function.
554
+ maxtasksperchild: maximum number of tasks to run in each actor process.
555
+ After a process has executed this many tasks, it will be killed and
556
+ replaced with a new one.
557
+ ray_address: address of the Ray cluster to run on. If None, a new local
558
+ Ray cluster will be started on this machine. Otherwise, this will
559
+ be passed to `ray.init()` to connect to a running cluster. This may
560
+ also be specified using the `RAY_ADDRESS` environment variable.
561
+ ray_remote_args: arguments used to configure the Ray Actors making up
562
+ the pool.
563
+ """
564
+
565
+ def __init__(
566
+ self,
567
+ processes: Optional[int] = None,
568
+ initializer: Optional[Callable] = None,
569
+ initargs: Optional[Iterable] = None,
570
+ maxtasksperchild: Optional[int] = None,
571
+ context: Any = None,
572
+ ray_address: Optional[str] = None,
573
+ ray_remote_args: Optional[Dict[str, Any]] = None,
574
+ ):
575
+ usage_lib.record_library_usage("util.multiprocessing.Pool")
576
+
577
+ self._closed = False
578
+ self._initializer = initializer
579
+ self._initargs = initargs
580
+ self._maxtasksperchild = maxtasksperchild or -1
581
+ self._actor_deletion_ids = []
582
+ self._registry: List[Tuple[Any, ray.ObjectRef]] = []
583
+ self._registry_hashable: Dict[Hashable, ray.ObjectRef] = {}
584
+ self._current_index = 0
585
+ self._ray_remote_args = ray_remote_args or {}
586
+ self._pool_actor = None
587
+
588
+ if context and log_once("context_argument_warning"):
589
+ logger.warning(
590
+ "The 'context' argument is not supported using "
591
+ "ray. Please refer to the documentation for how "
592
+ "to control ray initialization."
593
+ )
594
+
595
+ processes = self._init_ray(processes, ray_address)
596
+ self._start_actor_pool(processes)
597
+
598
+ def _init_ray(self, processes=None, ray_address=None):
599
+ # Initialize ray. If ray is already initialized, we do nothing.
600
+ # Else, the priority is:
601
+ # ray_address argument > RAY_ADDRESS > start new local cluster.
602
+ if not ray.is_initialized():
603
+ # Cluster mode.
604
+ if ray_address is None and (
605
+ RAY_ADDRESS_ENV in os.environ
606
+ or ray._private.utils.read_ray_address() is not None
607
+ ):
608
+ ray.init()
609
+ elif ray_address is not None:
610
+ init_kwargs = {}
611
+ if ray_address == "local":
612
+ init_kwargs["num_cpus"] = processes
613
+ ray.init(address=ray_address, **init_kwargs)
614
+ # Local mode.
615
+ else:
616
+ ray.init(num_cpus=processes)
617
+
618
+ ray_cpus = int(ray._private.state.cluster_resources()["CPU"])
619
+ if processes is None:
620
+ processes = ray_cpus
621
+ if processes <= 0:
622
+ raise ValueError("Processes in the pool must be >0.")
623
+ if ray_cpus < processes:
624
+ raise ValueError(
625
+ "Tried to start a pool with {} processes on an "
626
+ "existing ray cluster, but there are only {} "
627
+ "CPUs in the ray cluster.".format(processes, ray_cpus)
628
+ )
629
+
630
+ return processes
631
+
632
+ def _start_actor_pool(self, processes):
633
+ self._pool_actor = None
634
+ self._actor_pool = [self._new_actor_entry() for _ in range(processes)]
635
+ ray.get([actor.ping.remote() for actor, _ in self._actor_pool])
636
+
637
+ def _wait_for_stopping_actors(self, timeout=None):
638
+ if len(self._actor_deletion_ids) == 0:
639
+ return
640
+ if timeout is not None:
641
+ timeout = float(timeout)
642
+
643
+ _, deleting = ray.wait(
644
+ self._actor_deletion_ids,
645
+ num_returns=len(self._actor_deletion_ids),
646
+ timeout=timeout,
647
+ )
648
+ self._actor_deletion_ids = deleting
649
+
650
+ def _stop_actor(self, actor):
651
+ # Check and clean up any outstanding IDs corresponding to deletions.
652
+ self._wait_for_stopping_actors(timeout=0.0)
653
+ # The deletion task will block until the actor has finished executing
654
+ # all pending tasks.
655
+ self._actor_deletion_ids.append(actor.__ray_terminate__.remote())
656
+
657
+ def _new_actor_entry(self):
658
+ # NOTE(edoakes): The initializer function can't currently be used to
659
+ # modify the global namespace (e.g., import packages or set globals)
660
+ # due to a limitation in cloudpickle.
661
+ # Cache the PoolActor with options
662
+ if not self._pool_actor:
663
+ self._pool_actor = PoolActor.options(**self._ray_remote_args)
664
+ return (self._pool_actor.remote(self._initializer, self._initargs), 0)
665
+
666
+ def _next_actor_index(self):
667
+ if self._current_index == len(self._actor_pool) - 1:
668
+ self._current_index = 0
669
+ else:
670
+ self._current_index += 1
671
+ return self._current_index
672
+
673
+ # Batch should be a list of tuples: (args, kwargs).
674
+ def _run_batch(self, actor_index, func, batch):
675
+ actor, count = self._actor_pool[actor_index]
676
+ object_ref = actor.run_batch.remote(func, batch)
677
+ count += 1
678
+ assert self._maxtasksperchild == -1 or count <= self._maxtasksperchild
679
+ if count == self._maxtasksperchild:
680
+ self._stop_actor(actor)
681
+ actor, count = self._new_actor_entry()
682
+ self._actor_pool[actor_index] = (actor, count)
683
+ return object_ref
684
+
685
+ def apply(
686
+ self,
687
+ func: Callable,
688
+ args: Optional[Tuple] = None,
689
+ kwargs: Optional[Dict] = None,
690
+ ):
691
+ """Run the given function on a random actor process and return the
692
+ result synchronously.
693
+
694
+ Args:
695
+ func: function to run.
696
+ args: optional arguments to the function.
697
+ kwargs: optional keyword arguments to the function.
698
+
699
+ Returns:
700
+ The result.
701
+ """
702
+
703
+ return self.apply_async(func, args, kwargs).get()
704
+
705
+ def apply_async(
706
+ self,
707
+ func: Callable,
708
+ args: Optional[Tuple] = None,
709
+ kwargs: Optional[Dict] = None,
710
+ callback: Callable[[Any], None] = None,
711
+ error_callback: Callable[[Exception], None] = None,
712
+ ):
713
+ """Run the given function on a random actor process and return an
714
+ asynchronous interface to the result.
715
+
716
+ Args:
717
+ func: function to run.
718
+ args: optional arguments to the function.
719
+ kwargs: optional keyword arguments to the function.
720
+ callback: callback to be executed on the result once it is finished
721
+ only if it succeeds.
722
+ error_callback: callback to be executed the result once it is
723
+ finished only if the task errors. The exception raised by the
724
+ task will be passed as the only argument to the callback.
725
+
726
+ Returns:
727
+ AsyncResult containing the result.
728
+ """
729
+
730
+ self._check_running()
731
+ func = self._convert_to_ray_batched_calls_if_needed(func)
732
+ object_ref = self._run_batch(self._next_actor_index(), func, [(args, kwargs)])
733
+ return AsyncResult([object_ref], callback, error_callback, single_result=True)
734
+
735
+ def _convert_to_ray_batched_calls_if_needed(self, func: Callable) -> Callable:
736
+ """Convert joblib's BatchedCalls to RayBatchedCalls for ObjectRef caching.
737
+
738
+ This converts joblib's BatchedCalls callable, which is a collection of
739
+ functions with their args and kwargs to be ran sequentially in an
740
+ Actor, to a RayBatchedCalls callable, which provides identical
741
+ functionality in addition to a method which ensures that common
742
+ args and kwargs are put into the object store just once, saving time
743
+ and memory. That method is then ran.
744
+
745
+ If func is not a BatchedCalls instance, it is returned without changes.
746
+
747
+ The ObjectRefs are cached inside two registries (_registry and
748
+ _registry_hashable), which are common for the entire Pool and are
749
+ cleaned on close."""
750
+ if RayBatchedCalls is None:
751
+ return func
752
+ orginal_func = func
753
+ # SafeFunction is a Python 2 leftover and can be
754
+ # safely removed.
755
+ if isinstance(func, SafeFunction):
756
+ func = func.func
757
+ if isinstance(func, BatchedCalls):
758
+ func = RayBatchedCalls(
759
+ func.items,
760
+ (func._backend, func._n_jobs),
761
+ func._reducer_callback,
762
+ func._pickle_cache,
763
+ )
764
+ # go through all the items and replace args and kwargs with
765
+ # ObjectRefs, caching them in registries
766
+ func.put_items_in_object_store(self._registry, self._registry_hashable)
767
+ else:
768
+ func = orginal_func
769
+ return func
770
+
771
+ def _calculate_chunksize(self, iterable):
772
+ chunksize, extra = divmod(len(iterable), len(self._actor_pool) * 4)
773
+ if extra:
774
+ chunksize += 1
775
+ return chunksize
776
+
777
+ def _submit_chunk(self, func, iterator, chunksize, actor_index, unpack_args=False):
778
+ chunk = []
779
+ while len(chunk) < chunksize:
780
+ try:
781
+ args = next(iterator)
782
+ if not unpack_args:
783
+ args = (args,)
784
+ chunk.append((args, {}))
785
+ except StopIteration:
786
+ break
787
+
788
+ # Nothing to submit. The caller should prevent this.
789
+ assert len(chunk) > 0
790
+
791
+ return self._run_batch(actor_index, func, chunk)
792
+
793
+ def _chunk_and_run(self, func, iterable, chunksize=None, unpack_args=False):
794
+ if not hasattr(iterable, "__len__"):
795
+ iterable = list(iterable)
796
+
797
+ if chunksize is None:
798
+ chunksize = self._calculate_chunksize(iterable)
799
+
800
+ iterator = iter(iterable)
801
+ chunk_object_refs = []
802
+ while len(chunk_object_refs) * chunksize < len(iterable):
803
+ actor_index = len(chunk_object_refs) % len(self._actor_pool)
804
+ chunk_object_refs.append(
805
+ self._submit_chunk(
806
+ func, iterator, chunksize, actor_index, unpack_args=unpack_args
807
+ )
808
+ )
809
+
810
+ return chunk_object_refs
811
+
812
+ def _map_async(
813
+ self,
814
+ func,
815
+ iterable,
816
+ chunksize=None,
817
+ unpack_args=False,
818
+ callback=None,
819
+ error_callback=None,
820
+ ):
821
+ self._check_running()
822
+ object_refs = self._chunk_and_run(
823
+ func, iterable, chunksize=chunksize, unpack_args=unpack_args
824
+ )
825
+ return AsyncResult(object_refs, callback, error_callback)
826
+
827
+ def map(self, func: Callable, iterable: Iterable, chunksize: Optional[int] = None):
828
+ """Run the given function on each element in the iterable round-robin
829
+ on the actor processes and return the results synchronously.
830
+
831
+ Args:
832
+ func: function to run.
833
+ iterable: iterable of objects to be passed as the sole argument to
834
+ func.
835
+ chunksize: number of tasks to submit as a batch to each actor
836
+ process. If unspecified, a suitable chunksize will be chosen.
837
+
838
+ Returns:
839
+ A list of results.
840
+ """
841
+
842
+ return self._map_async(
843
+ func, iterable, chunksize=chunksize, unpack_args=False
844
+ ).get()
845
+
846
+ def map_async(
847
+ self,
848
+ func: Callable,
849
+ iterable: Iterable,
850
+ chunksize: Optional[int] = None,
851
+ callback: Callable[[List], None] = None,
852
+ error_callback: Callable[[Exception], None] = None,
853
+ ):
854
+ """Run the given function on each element in the iterable round-robin
855
+ on the actor processes and return an asynchronous interface to the
856
+ results.
857
+
858
+ Args:
859
+ func: function to run.
860
+ iterable: iterable of objects to be passed as the only argument to
861
+ func.
862
+ chunksize: number of tasks to submit as a batch to each actor
863
+ process. If unspecified, a suitable chunksize will be chosen.
864
+ callback: Will only be called if none of the results were errors,
865
+ and will only be called once after all results are finished.
866
+ A Python List of all the finished results will be passed as the
867
+ only argument to the callback.
868
+ error_callback: callback executed on the first errored result.
869
+ The Exception raised by the task will be passed as the only
870
+ argument to the callback.
871
+
872
+ Returns:
873
+ AsyncResult
874
+ """
875
+ return self._map_async(
876
+ func,
877
+ iterable,
878
+ chunksize=chunksize,
879
+ unpack_args=False,
880
+ callback=callback,
881
+ error_callback=error_callback,
882
+ )
883
+
884
+ def starmap(self, func, iterable, chunksize=None):
885
+ """Same as `map`, but unpacks each element of the iterable as the
886
+ arguments to func like: [func(*args) for args in iterable].
887
+ """
888
+
889
+ return self._map_async(
890
+ func, iterable, chunksize=chunksize, unpack_args=True
891
+ ).get()
892
+
893
+ def starmap_async(
894
+ self,
895
+ func: Callable,
896
+ iterable: Iterable,
897
+ callback: Callable[[List], None] = None,
898
+ error_callback: Callable[[Exception], None] = None,
899
+ ):
900
+ """Same as `map_async`, but unpacks each element of the iterable as the
901
+ arguments to func like: [func(*args) for args in iterable].
902
+ """
903
+
904
+ return self._map_async(
905
+ func,
906
+ iterable,
907
+ unpack_args=True,
908
+ callback=callback,
909
+ error_callback=error_callback,
910
+ )
911
+
912
+ def imap(self, func: Callable, iterable: Iterable, chunksize: Optional[int] = 1):
913
+ """Same as `map`, but only submits one batch of tasks to each actor
914
+ process at a time.
915
+
916
+ This can be useful if the iterable of arguments is very large or each
917
+ task's arguments consumes a large amount of resources.
918
+
919
+ The results are returned in the order corresponding to their arguments
920
+ in the iterable.
921
+
922
+ Returns:
923
+ OrderedIMapIterator
924
+ """
925
+
926
+ self._check_running()
927
+ return OrderedIMapIterator(self, func, iterable, chunksize=chunksize)
928
+
929
+ def imap_unordered(
930
+ self, func: Callable, iterable: Iterable, chunksize: Optional[int] = 1
931
+ ):
932
+ """Same as `map`, but only submits one batch of tasks to each actor
933
+ process at a time.
934
+
935
+ This can be useful if the iterable of arguments is very large or each
936
+ task's arguments consumes a large amount of resources.
937
+
938
+ The results are returned in the order that they finish.
939
+
940
+ Returns:
941
+ UnorderedIMapIterator
942
+ """
943
+
944
+ self._check_running()
945
+ return UnorderedIMapIterator(self, func, iterable, chunksize=chunksize)
946
+
947
+ def _check_running(self):
948
+ if self._closed:
949
+ raise ValueError("Pool not running")
950
+
951
+ def __enter__(self):
952
+ self._check_running()
953
+ return self
954
+
955
+ def __exit__(self, exc_type, exc_val, exc_tb):
956
+ self.terminate()
957
+
958
+ def close(self):
959
+ """Close the pool.
960
+
961
+ Prevents any more tasks from being submitted on the pool but allows
962
+ outstanding work to finish.
963
+ """
964
+
965
+ self._registry.clear()
966
+ self._registry_hashable.clear()
967
+ for actor, _ in self._actor_pool:
968
+ self._stop_actor(actor)
969
+ self._closed = True
970
+ gc.collect()
971
+
972
+ def terminate(self):
973
+ """Close the pool.
974
+
975
+ Prevents any more tasks from being submitted on the pool and stops
976
+ outstanding work.
977
+ """
978
+
979
+ if not self._closed:
980
+ self.close()
981
+ for actor, _ in self._actor_pool:
982
+ ray.kill(actor)
983
+
984
+ def join(self):
985
+ """Wait for the actors in a closed pool to exit.
986
+
987
+ If the pool was closed using `close`, this will return once all
988
+ outstanding work is completed.
989
+
990
+ If the pool was closed using `terminate`, this will return quickly.
991
+ """
992
+
993
+ if not self._closed:
994
+ raise ValueError("Pool is still running")
995
+ self._wait_for_stopping_actors()
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _amp_foreach_non_finite_check_and_unscale_ {
18
+ using schema = void (at::TensorList, at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_amp_foreach_non_finite_check_and_unscale_")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_amp_foreach_non_finite_check_and_unscale_(Tensor(a!)[] self, Tensor(b!) found_inf, Tensor inv_scale) -> ()")
24
+ static void call(at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale);
25
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale);
26
+ };
27
+
28
+ struct TORCH_API _amp_foreach_non_finite_check_and_unscale_out {
29
+ using schema = void (at::TensorList, at::Tensor &, const at::Tensor &, at::TensorList);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_amp_foreach_non_finite_check_and_unscale")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_amp_foreach_non_finite_check_and_unscale.out(Tensor[] self, Tensor(b!) found_inf, Tensor inv_scale, *, Tensor(a!)[] out) -> ()")
35
+ static void call(at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale, at::TensorList out);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale, at::TensorList out);
37
+ };
38
+
39
+ struct TORCH_API _amp_foreach_non_finite_check_and_unscale {
40
+ using schema = ::std::tuple<::std::vector<at::Tensor>,at::Tensor> (at::TensorList, const at::Tensor &, const at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_amp_foreach_non_finite_check_and_unscale")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_amp_foreach_non_finite_check_and_unscale(Tensor[] self, Tensor found_inf, Tensor inv_scale) -> (Tensor[] self_out, Tensor found_inf_out)")
46
+ static ::std::tuple<::std::vector<at::Tensor>,at::Tensor> call(at::TensorList self, const at::Tensor & found_inf, const at::Tensor & inv_scale);
47
+ static ::std::tuple<::std::vector<at::Tensor>,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & found_inf, const at::Tensor & inv_scale);
48
+ };
49
+
50
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor _cast_Half(const at::Tensor & self, bool non_blocking=false);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Int_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor _cast_Int(const at::Tensor & self, bool non_blocking=false);
20
+ } // namespace native
21
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_conj_physical.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_conj_physical_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_conj_physical(Tensor self) -> Tensor
26
+ inline at::Tensor _conj_physical(const at::Tensor & self) {
27
+ return at::_ops::_conj_physical::call(self);
28
+ }
29
+
30
+ // aten::_conj_physical.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & _conj_physical_out(at::Tensor & out, const at::Tensor & self) {
32
+ return at::_ops::_conj_physical_out::call(self, out);
33
+ }
34
+ // aten::_conj_physical.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & _conj_physical_outf(const at::Tensor & self, at::Tensor & out) {
36
+ return at::_ops::_conj_physical_out::call(self, out);
37
+ }
38
+
39
+ }
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_convolution_double_backward_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _convolution_double_backward(const ::std::optional<at::Tensor> & ggI, const ::std::optional<at::Tensor> & ggW, const ::std::optional<at::Tensor> & ggb, const at::Tensor & gO, const at::Tensor & weight, const at::Tensor & self, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask);
20
+ } // namespace native
21
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_affine_quantized_cpu_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _empty_affine_quantized(at::IntArrayRef size, at::TensorOptions options={}, double scale=1, int64_t zero_point=0, ::std::optional<at::MemoryFormat> memory_format=MemoryFormat::Contiguous);
21
+ TORCH_API at::Tensor _empty_affine_quantized(at::IntArrayRef size, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory, double scale, int64_t zero_point, ::std::optional<at::MemoryFormat> memory_format);
22
+ TORCH_API at::Tensor _empty_affine_quantized_symint(c10::SymIntArrayRef size, at::TensorOptions options={}, double scale=1, int64_t zero_point=0, ::std::optional<at::MemoryFormat> memory_format=MemoryFormat::Contiguous);
23
+ TORCH_API at::Tensor _empty_affine_quantized_symint(c10::SymIntArrayRef size, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory, double scale, int64_t zero_point, ::std::optional<at::MemoryFormat> memory_format);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_add.h ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_foreach_add_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_foreach_add.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
26
+ inline ::std::vector<at::Tensor> _foreach_add(at::TensorList self, const at::Scalar & scalar) {
27
+ return at::_ops::_foreach_add_Scalar::call(self, scalar);
28
+ }
29
+
30
+ // aten::_foreach_add_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
31
+ inline void _foreach_add_(at::TensorList self, const at::Scalar & scalar) {
32
+ return at::_ops::_foreach_add__Scalar::call(self, scalar);
33
+ }
34
+
35
+ // aten::_foreach_add.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[]
36
+ inline ::std::vector<at::Tensor> _foreach_add(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1) {
37
+ return at::_ops::_foreach_add_List::call(self, other, alpha);
38
+ }
39
+
40
+ // aten::_foreach_add_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> ()
41
+ inline void _foreach_add_(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1) {
42
+ return at::_ops::_foreach_add__List::call(self, other, alpha);
43
+ }
44
+
45
+ // aten::_foreach_add.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
46
+ inline ::std::vector<at::Tensor> _foreach_add(at::TensorList self, at::ArrayRef<at::Scalar> scalars) {
47
+ return at::_ops::_foreach_add_ScalarList::call(self, scalars);
48
+ }
49
+
50
+ // aten::_foreach_add_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
51
+ inline void _foreach_add_(at::TensorList self, at::ArrayRef<at::Scalar> scalars) {
52
+ return at::_ops::_foreach_add__ScalarList::call(self, scalars);
53
+ }
54
+
55
+ // aten::_foreach_add.Tensor(Tensor[] self, Tensor other, *, Scalar alpha=1) -> Tensor[]
56
+ inline ::std::vector<at::Tensor> _foreach_add(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1) {
57
+ return at::_ops::_foreach_add_Tensor::call(self, other, alpha);
58
+ }
59
+
60
+ // aten::_foreach_add_.Tensor(Tensor(a!)[] self, Tensor other, *, Scalar alpha=1) -> ()
61
+ inline void _foreach_add_(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1) {
62
+ return at::_ops::_foreach_add__Tensor::call(self, other, alpha);
63
+ }
64
+
65
+ // aten::_foreach_add.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()
66
+ inline void _foreach_add_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar) {
67
+ return at::_ops::_foreach_add_Scalar_out::call(self, scalar, out);
68
+ }
69
+ // aten::_foreach_add.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()
70
+ inline void _foreach_add_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out) {
71
+ return at::_ops::_foreach_add_Scalar_out::call(self, scalar, out);
72
+ }
73
+
74
+ // aten::_foreach_add.List_out(Tensor[] self, Tensor[] other, *, Scalar alpha=1, Tensor(a!)[] out) -> ()
75
+ inline void _foreach_add_out(at::TensorList out, at::TensorList self, at::TensorList other, const at::Scalar & alpha=1) {
76
+ return at::_ops::_foreach_add_List_out::call(self, other, alpha, out);
77
+ }
78
+ // aten::_foreach_add.List_out(Tensor[] self, Tensor[] other, *, Scalar alpha=1, Tensor(a!)[] out) -> ()
79
+ inline void _foreach_add_outf(at::TensorList self, at::TensorList other, const at::Scalar & alpha, at::TensorList out) {
80
+ return at::_ops::_foreach_add_List_out::call(self, other, alpha, out);
81
+ }
82
+
83
+ // aten::_foreach_add.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()
84
+ inline void _foreach_add_out(at::TensorList out, at::TensorList self, at::ArrayRef<at::Scalar> scalars) {
85
+ return at::_ops::_foreach_add_ScalarList_out::call(self, scalars, out);
86
+ }
87
+ // aten::_foreach_add.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()
88
+ inline void _foreach_add_outf(at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out) {
89
+ return at::_ops::_foreach_add_ScalarList_out::call(self, scalars, out);
90
+ }
91
+
92
+ // aten::_foreach_add.Tensor_out(Tensor[] self, Tensor other, *, Scalar alpha=1, Tensor(a!)[] out) -> ()
93
+ inline void _foreach_add_out(at::TensorList out, at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1) {
94
+ return at::_ops::_foreach_add_Tensor_out::call(self, other, alpha, out);
95
+ }
96
+ // aten::_foreach_add.Tensor_out(Tensor[] self, Tensor other, *, Scalar alpha=1, Tensor(a!)[] out) -> ()
97
+ inline void _foreach_add_outf(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha, at::TensorList out) {
98
+ return at::_ops::_foreach_add_Tensor_out::call(self, other, alpha, out);
99
+ }
100
+
101
+ }
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_softmax_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _masked_softmax_backward(const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & mask, ::std::optional<int64_t> dim=::std::nullopt);
21
+
22
+ } // namespace cpu
23
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_native_multi_head_attention_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _native_multi_head_attention_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional<at::Tensor> & mask={}, bool need_weights=true, bool average_attn_weights=true, ::std::optional<int64_t> mask_type=::std::nullopt);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _native_multi_head_attention_outf(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional<at::Tensor> & mask, bool need_weights, bool average_attn_weights, ::std::optional<int64_t> mask_type, at::Tensor & out0, at::Tensor & out1);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_mask_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _nested_tensor_from_mask {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_from_mask")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_from_mask(Tensor t, Tensor mask, bool mask_check=True) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & t, const at::Tensor & mask, bool mask_check);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & t, const at::Tensor & mask, bool mask_check);
26
+ };
27
+
28
+ struct TORCH_API _nested_tensor_from_mask_out {
29
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, bool, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_from_mask")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_from_mask.out(Tensor t, Tensor mask, bool mask_check=True, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & t, const at::Tensor & mask, bool mask_check, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & t, const at::Tensor & mask, bool mask_check, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _scaled_dot_product_flash_attention_backward {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymInt, c10::SymInt, double, bool, const at::Tensor &, const at::Tensor &, ::std::optional<double>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_scaled_dot_product_flash_attention_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)")
24
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale);
25
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale);
26
+ };
27
+
28
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_broadcast_to_copy_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _sparse_broadcast_to_copy {
18
+ using schema = at::Tensor (const at::Tensor &, at::IntArrayRef);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_broadcast_to_copy")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_broadcast_to_copy(Tensor self, int[] size) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, at::IntArrayRef size);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size);
26
+ };
27
+
28
+ struct TORCH_API _sparse_broadcast_to_copy_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_broadcast_to_copy")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_broadcast_to_copy.out(Tensor self, int[] size, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, at::IntArrayRef size, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_compressed_tensor_with_dims_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor _sparse_compressed_tensor_with_dims(int64_t nnz, int64_t dense_dim, at::IntArrayRef size, at::IntArrayRef blocksize, at::ScalarType index_dtype, at::TensorOptions options);
21
+ TORCH_API at::Tensor _sparse_compressed_tensor_with_dims(int64_t nnz, int64_t dense_dim, at::IntArrayRef size, at::IntArrayRef blocksize, at::ScalarType index_dtype, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact2d_cuda_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor _upsample_nearest_exact2d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
21
+ TORCH_API at::Tensor _upsample_nearest_exact2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
22
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
23
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_outf(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & out);
24
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
25
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & out);
26
+
27
+ } // namespace cuda
28
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/ccol_indices_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API ccol_indices {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::ccol_indices")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ccol_indices(Tensor(a) self) -> Tensor(a)")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/fft_ifft2.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/fft_ifft2_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::fft_ifft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
26
+ inline at::Tensor fft_ifft2(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
27
+ return at::_ops::fft_ifft2::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ at::Tensor fft_ifft2(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
32
+ return at::_ops::fft_ifft2::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm);
33
+ }
34
+ }
35
+
36
+ // aten::fft_ifft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
37
+ inline at::Tensor fft_ifft2_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
38
+ return at::_ops::fft_ifft2::call(self, s, dim, norm);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ at::Tensor fft_ifft2(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
43
+ return at::_ops::fft_ifft2::call(self, s, dim, norm);
44
+ }
45
+ }
46
+
47
+ // aten::fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
48
+ inline at::Tensor & fft_ifft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
49
+ return at::_ops::fft_ifft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
50
+ }
51
+ namespace symint {
52
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
53
+ at::Tensor & fft_ifft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
54
+ return at::_ops::fft_ifft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
55
+ }
56
+ }
57
+
58
+ // aten::fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
59
+ inline at::Tensor & fft_ifft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
60
+ return at::_ops::fft_ifft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
61
+ }
62
+ namespace symint {
63
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
64
+ at::Tensor & fft_ifft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
65
+ return at::_ops::fft_ifft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
66
+ }
67
+ }
68
+
69
+ // aten::fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
70
+ inline at::Tensor & fft_ifft2_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
71
+ return at::_ops::fft_ifft2_out::call(self, s, dim, norm, out);
72
+ }
73
+ namespace symint {
74
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
75
+ at::Tensor & fft_ifft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
76
+ return at::_ops::fft_ifft2_out::call(self, s, dim, norm, out);
77
+ }
78
+ }
79
+
80
+ // aten::fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
81
+ inline at::Tensor & fft_ifft2_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
82
+ return at::_ops::fft_ifft2_out::call(self, s, dim, norm, out);
83
+ }
84
+ namespace symint {
85
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
86
+ at::Tensor & fft_ifft2_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
87
+ return at::_ops::fft_ifft2_out::call(self, s, dim, norm, out);
88
+ }
89
+ }
90
+
91
+ }