[51873b]: / docproduct / mqa_load_dataset.py

Download this file

151 lines (124 with data), 5.0 kB

  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
import glob
import numpy as np
import os
import random
import tensorflow.compat.v1 as tf
import tqdm
import csv
import pandas as pd
def load_dataset(enc, path, combine, pretokenize=True, topk=10):
paths = []
if os.path.isfile(path):
# Simple file
paths.append(path)
elif os.path.isdir(path):
# Directory
for (dirpath, _, fnames) in os.walk(path):
for fname in fnames:
paths.append(os.path.join(dirpath, fname))
else:
# Assume glob
paths = glob.glob(path)
if paths == []:
raise Exception("No data found")
token_chunks = []
if pretokenize:
pt_path = path.split('.')[0] + '_pretokenized.' + 'npy'
if not os.path.exists(pt_path):
print('Pretokenizing data..')
token_list = []
for path in paths:
df = pd.read_parquet(path)
for sample_ind, sample in tqdm.tqdm(df.iterrows(), total=df.shape[0], desc='Pretokenization'):
line = '`QUESTION: %s `ANSWER: %s' % (
sample[0], sample[1])
for i in range(2, len(sample), 2):
if i <= topk*2:
line = '`QUESTION: %s `ANSWER: %s ' % (
sample[i], sample[i+1]) + line
line = line.replace('\n', '')
if sample_ind <= 10:
print(line)
token_list.append(np.stack(enc.encode(line)))
print('Pretokenization successful!')
np.save(pt_path, np.array(token_list))
print('Loading pretokenized data..')
token_chunks = np.load(pt_path, allow_pickle=True)
# with open(pt_path, 'r', encoding='utf8') as pt:
# pt_reader = csv.reader(pt)
# pt_iter = list(pt_reader)
# for j, sample in enumerate(tqdm.tqdm(pt_iter[1:])):
# tokens = np.asarray(
# sample[-1].strip('[]').replace(',', '').split(), dtype=np.int32)
# token_chunks.append(tokens)
else:
raise NotImplementedError
for path in paths:
'''
if path.endswith('.npz'):
# Pre-encoded
with np.load(path) as npz:
for item in npz.files:
token_chunks.append(npz[item])
else:
# Plain text
with open(path, 'r', encoding='utf8', errors='ignore') as fp:
raw_text += fp.read()
if len(raw_text) >= combine:
tokens = np.stack(enc.encode(raw_text))
token_chunks.append(tokens)
raw_text = ''
else:
raw_text += '<|endoftext|>'
'''
with open(path, 'r', encoding='utf8', errors='ignore') as fp:
csv_reader = csv.reader(fp)
for j, sample in enumerate(tqdm.tqdm(csv_reader)):
line = '`QUESTION: %s `ANSWER: %s' % (
sample[0], sample[1])
for i in range(len(sample), 2, -2):
line = '`QUESTION: %s `ANSWER: %s ' % (
sample[i-2], sample[i-1]) + line
tokens = np.stack(enc.encode(line))
token_chunks.append(tokens)
'''
if raw_text:
tokens = np.stack(enc.encode(raw_text))
token_chunks.append(tokens)
'''
return token_chunks
def binary_search(f, lo, hi):
if f(lo) or not f(hi):
return None
while hi > lo + 1:
mid = (lo + hi) // 2
if f(mid):
hi = mid
else:
lo = mid
return hi
class Sampler(object):
"""Fairly samples a slice from a set of variable sized chunks.
'Fairly' means that the distribution is the same as sampling from one concatenated chunk,
but without crossing chunk boundaries."""
def __init__(self, chunks):
self.chunks = chunks
self.total_size = sum(chunk.shape[0] for chunk in chunks)
self.boundaries = [0]
for i in range(len(chunks)):
self.boundaries.append(self.boundaries[-1] + chunks[i].shape[0])
def sample(self, length):
'''
assert length < self.total_size // len(
self.chunks
), "Dataset files are too small to sample {} tokens at a time".format(
length)
while True:
index = random.randint(0, self.total_size - length - 1)
i = binary_search(lambda j: self.boundaries[j] > index, 0,
len(self.boundaries) - 1) - 1
if self.boundaries[i + 1] > index + length:
within_chunk = index - self.boundaries[i]
return self.chunks[i][within_chunk:within_chunk + length]
'''
return random.choice(self.chunks)