Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

indexed_dataset.py 5.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. import numpy as np
  8. import os
  9. import struct
  10. import torch
  11. from fairseq.tokenizer import Tokenizer
  12. def read_longs(f, n):
  13. a = np.empty(n, dtype=np.int64)
  14. f.readinto(a)
  15. return a
  16. def write_longs(f, a):
  17. f.write(np.array(a, dtype=np.int64))
  18. dtypes = {
  19. 1: np.uint8,
  20. 2: np.int8,
  21. 3: np.int16,
  22. 4: np.int32,
  23. 5: np.int64,
  24. 6: np.float,
  25. 7: np.double,
  26. }
  27. def code(dtype):
  28. for k in dtypes.keys():
  29. if dtypes[k] == dtype:
  30. return k
  31. def index_file_path(prefix_path):
  32. return prefix_path + '.idx'
  33. def data_file_path(prefix_path):
  34. return prefix_path + '.bin'
  35. class IndexedDataset(object):
  36. """Loader for TorchNet IndexedDataset"""
  37. def __init__(self, path):
  38. with open(index_file_path(path), 'rb') as f:
  39. magic = f.read(8)
  40. assert magic == b'TNTIDX\x00\x00'
  41. version = f.read(8)
  42. assert struct.unpack('<Q', version) == (1,)
  43. code, self.element_size = struct.unpack('<QQ', f.read(16))
  44. self.dtype = dtypes[code]
  45. self.size, self.s = struct.unpack('<QQ', f.read(16))
  46. self.dim_offsets = read_longs(f, self.size + 1)
  47. self.data_offsets = read_longs(f, self.size + 1)
  48. self.sizes = read_longs(f, self.s)
  49. self.read_data(path)
  50. def read_data(self, path):
  51. self.data_file = open(data_file_path(path), 'rb', buffering=0)
  52. def check_index(self, i):
  53. if i < 0 or i >= self.size:
  54. raise IndexError('index out of range')
  55. def __del__(self):
  56. self.data_file.close()
  57. def __getitem__(self, i):
  58. self.check_index(i)
  59. tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]]
  60. a = np.empty(tensor_size, dtype=self.dtype)
  61. self.data_file.seek(self.data_offsets[i] * self.element_size)
  62. self.data_file.readinto(a)
  63. return torch.from_numpy(a)
  64. def __len__(self):
  65. return self.size
  66. @staticmethod
  67. def exists(path):
  68. return (
  69. os.path.exists(index_file_path(path)) and
  70. os.path.exists(data_file_path(path))
  71. )
  72. class IndexedInMemoryDataset(IndexedDataset):
  73. """Loader for TorchNet IndexedDataset, keeps all the data in memory"""
  74. def read_data(self, path):
  75. self.data_file = open(data_file_path(path), 'rb')
  76. self.buffer = np.empty(self.data_offsets[-1], dtype=self.dtype)
  77. self.data_file.readinto(self.buffer)
  78. self.data_file.close()
  79. def __del__(self):
  80. pass
  81. def __getitem__(self, i):
  82. self.check_index(i)
  83. tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]]
  84. a = np.empty(tensor_size, dtype=self.dtype)
  85. np.copyto(a, self.buffer[self.data_offsets[i]:self.data_offsets[i + 1]])
  86. return torch.from_numpy(a)
  87. class IndexedRawTextDataset(IndexedDataset):
  88. """Takes a text file as input and binarizes it in memory at instantiation.
  89. Original lines are also kept in memory"""
  90. def __init__(self, path, dictionary, append_eos=True, reverse_order=False):
  91. self.tokens_list = []
  92. self.lines = []
  93. self.sizes = []
  94. self.append_eos = append_eos
  95. self.reverse_order = reverse_order
  96. self.read_data(path, dictionary)
  97. self.size = len(self.tokens_list)
  98. def read_data(self, path, dictionary):
  99. with open(path, 'r') as f:
  100. for line in f:
  101. self.lines.append(line.strip('\n'))
  102. tokens = Tokenizer.tokenize(
  103. line, dictionary, add_if_not_exist=False,
  104. append_eos=self.append_eos, reverse_order=self.reverse_order,
  105. ) + 1 # +1 for Lua compatibility
  106. self.tokens_list.append(tokens)
  107. self.sizes.append(len(tokens))
  108. self.sizes = np.array(self.sizes)
  109. def __getitem__(self, i):
  110. self.check_index(i)
  111. return self.tokens_list[i]
  112. def get_original_text(self, i):
  113. self.check_index(i)
  114. return self.lines[i]
  115. def __del__(self):
  116. pass
  117. def __len__(self):
  118. return self.size
  119. class IndexedDatasetBuilder(object):
  120. element_sizes = {
  121. np.uint8: 1,
  122. np.int8: 1,
  123. np.int16: 2,
  124. np.int32: 4,
  125. np.int64: 8,
  126. np.float: 4,
  127. np.double: 8
  128. }
  129. def __init__(self, out_file, dtype=np.int32):
  130. self.out_file = open(out_file, 'wb')
  131. self.dtype = dtype
  132. self.data_offsets = [0]
  133. self.dim_offsets = [0]
  134. self.sizes = []
  135. self.element_size = self.element_sizes[self.dtype]
  136. def add_item(self, tensor):
  137. # +1 for Lua compatibility
  138. bytes = self.out_file.write(np.array(tensor.numpy() + 1, dtype=self.dtype))
  139. self.data_offsets.append(self.data_offsets[-1] + bytes / self.element_size)
  140. for s in tensor.size():
  141. self.sizes.append(s)
  142. self.dim_offsets.append(self.dim_offsets[-1] + len(tensor.size()))
  143. def finalize(self, index_file):
  144. self.out_file.close()
  145. index = open(index_file, 'wb')
  146. index.write(b'TNTIDX\x00\x00')
  147. index.write(struct.pack('<Q', 1))
  148. index.write(struct.pack('<QQ', code(self.dtype),
  149. self.element_size))
  150. index.write(struct.pack('<QQ', len(self.data_offsets) - 1,
  151. len(self.sizes)))
  152. write_longs(index, self.dim_offsets)
  153. write_longs(index, self.data_offsets)
  154. write_longs(index, self.sizes)
  155. index.close()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...