File size: 12,828 Bytes
ee439ff |
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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
import copy
import numpy as np
import pdb
import os
import io
import json
import gzip
import zstandard as zstd
import numpy as np
from tqdm import tqdm
import pandas as pd
class SemiNATForSingleRoundMaskInput(Dataset):
'''
Mask掉了所有的输入,只有输出的loss
'''
def __init__(self, tokenizer, datas, max_length, proc):
self.tokenizer = tokenizer
self.max_length = max_length
self.proc = proc
# 用 apply + 并行加速预处理
processed = self._vectorized_preprocess(datas)
self.input_ids = processed["input_ids"]
self.labels = processed["labels"]
self.attention_mask = processed["attention_mask"]
self.slice_indices = processed["slice_indices"]
def _vectorized_preprocess(self, datas):
# 批量预分配内存
input_ids = np.zeros((len(datas), self.max_length), dtype=np.int64)
attention_mask = np.zeros((len(datas), self.max_length),
dtype=np.int64)
labels = np.full((len(datas), self.max_length), -100, dtype=np.int64)
slice_indices = np.full((len(datas), self.max_length),
-1,
dtype=np.int64)
# 批量处理所有行的 messages
def process_row(row):
total_inputs = []
total_labels = []
sample_slice = []
# pdb.set_trace()
for msg in row['messages']:
# 批量分词(假设 msg['content'] 是文本列表)
inputs = self.tokenizer(msg['content'],
padding=False,
truncation=False,
add_special_tokens=False).input_ids
total_inputs.extend(inputs)
if msg['role'] == 'user':
total_labels.extend(len(inputs) * [-100])
elif msg['role'] == 'assistant':
total_labels.extend(inputs)
sample_slice.extend(msg['split_pos'])
# 截断或填充逻辑
seq_len = min(len(total_inputs), self.max_length)
# 输入和标签
input_ids = total_inputs[:self.max_length] + [
self.tokenizer.pad_token_id
] * (self.max_length - seq_len)
labels = total_labels[:self.max_length] + [-100] * (
self.max_length - seq_len)
# attention_mask
attention_mask = [1] * seq_len + [0] * (self.max_length - seq_len)
# slice_indices
slice_arr = np.array(sample_slice[:self.max_length] + [-1] *
(self.max_length - len(sample_slice)))
slice_arr[slice_arr > self.max_length -
1] = -1 # 过滤超长位置,这里-1是因为max length是1024,最大index是1023
return input_ids, labels, attention_mask, slice_arr
# 并行处理所有行(需安装 pandarallel)
try:
from pandarallel import pandarallel
pandarallel.initialize(nb_workers=self.proc, progress_bar=True)
processed = datas.parallel_apply(process_row, axis=1)
except ImportError:
processed = datas.progress_apply(process_row, axis=1) # tqdm 进度条
# 合并结果
# pdb.set_trace()
for idx, (i_ids, lbl, attn, slc) in enumerate(processed):
input_ids[idx] = i_ids
labels[idx] = lbl
attention_mask[idx] = attn
slice_indices[idx] = slc
return {
"input_ids": input_ids,
"labels": labels,
"attention_mask": attention_mask,
"slice_indices": slice_indices
}
def __len__(self):
return len(self.input_ids)
def __getitem__(self, index):
# 直接返回预分配的张量,避免重复转换
return (torch.as_tensor(self.input_ids[index]),
torch.as_tensor(self.labels[index]),
torch.as_tensor(self.attention_mask[index]),
torch.as_tensor(self.slice_indices[index]))
class SemiNATForSingleRound(Dataset):
def __init__(self, tokenizer, datas, max_length, proc):
self.tokenizer = tokenizer
self.max_length = max_length
self.proc = proc
# 用 apply + 并行加速预处理
processed = self._vectorized_preprocess(datas)
self.input_ids = processed["input_ids"]
self.labels = processed["labels"]
self.attention_mask = processed["attention_mask"]
self.slice_indices = processed["slice_indices"]
def _vectorized_preprocess(self, datas):
# 批量预分配内存
input_ids = np.zeros((len(datas), self.max_length), dtype=np.int64)
attention_mask = np.zeros((len(datas), self.max_length),
dtype=np.int64)
labels = np.full((len(datas), self.max_length), -100, dtype=np.int64)
slice_indices = np.full((len(datas), self.max_length),
-1,
dtype=np.int64)
# 批量处理所有行的 messages
def process_row(row):
total_inputs = []
sample_slice = []
for msg in row['messages']:
# 批量分词(假设 msg['content'] 是文本列表)
inputs = self.tokenizer(msg['content'],
padding=False,
truncation=False,
add_special_tokens=False).input_ids
total_inputs.extend(inputs)
# 直接使用列表扩展 slice
sample_slice.extend(msg['split_pos'])
# 截断或填充逻辑
seq_len = min(len(total_inputs), self.max_length)
# 输入和标签
input_ids = total_inputs[:self.max_length] + [
self.tokenizer.pad_token_id
] * (self.max_length - seq_len)
labels = total_inputs[:self.max_length] + [-100] * (
self.max_length - seq_len)
# attention_mask
attention_mask = [1] * seq_len + [0] * (self.max_length - seq_len)
# slice_indices
slice_arr = np.array(sample_slice[:self.max_length] + [-1] *
(self.max_length - len(sample_slice)))
slice_arr[slice_arr > self.max_length] = -1 # 过滤超长位置
return input_ids, labels, attention_mask, slice_arr
# 并行处理所有行(需安装 pandarallel)
try:
from pandarallel import pandarallel
pandarallel.initialize(nb_workers=self.proc, progress_bar=True)
processed = datas.parallel_apply(process_row, axis=1)
except:
processed = datas.progress_apply(process_row, axis=1) # tqdm 进度条
# 合并结果
for idx, (i_ids, lbl, attn, slc) in enumerate(processed):
input_ids[idx] = i_ids
labels[idx] = lbl
attention_mask[idx] = attn
slice_indices[idx] = slc
return {
"input_ids": input_ids,
"labels": labels,
"attention_mask": attention_mask,
"slice_indices": slice_indices
}
def __len__(self):
return len(self.input_ids)
def __getitem__(self, index):
# 直接返回预分配的张量,避免重复转换
return (torch.as_tensor(self.input_ids[index]),
torch.as_tensor(self.labels[index]),
torch.as_tensor(self.attention_mask[index]),
torch.as_tensor(self.slice_indices[index]))
class SemiNATDatasetForPretrain(Dataset):
# data_path is jsonl.zstd or json.gz file
def __init__(self,
tokenizer,
data_path,
max_length,
proc,
cache_path=None):
if data_path.endswith('.zstd'):
data = pd.DataFrame([
json.loads(line) for line in self._decompress_zst_to_string(
data_path).splitlines()
])
else: # json.gz file, each line a json
with gzip.open(data_path, 'rt', encoding='utf-8') as f:
data = pd.DataFrame([json.loads(line) for line in f])
self.tokenizer = tokenizer
self.max_length = max_length
self.proc = proc
if cache_path and os.path.exists(cache_path):
print(f"[INFO] Loading cached data from {cache_path}")
cached = torch.load(cache_path)
self.input_ids = cached["input_ids"]
self.labels = cached["labels"]
self.attention_mask = cached["attention_mask"]
self.slice_indices = cached["slice_indices"]
else:
processed = self._vectorized_preprocess(data)
self.input_ids = processed["input_ids"]
self.labels = processed["labels"]
self.attention_mask = processed["attention_mask"]
self.slice_indices = processed["slice_indices"]
if type(self.input_ids) != torch.Tensor:
self.input_ids = torch.tensor(self.input_ids, dtype=torch.long)
self.labels = torch.tensor(self.labels, dtype=torch.long)
self.attention_mask = torch.tensor(self.attention_mask,
dtype=torch.long)
self.slice_indices = torch.tensor(self.slice_indices,
dtype=torch.long)
def _decompress_zst_to_string(self, input_file):
with open(input_file, 'rb') as f:
dctx = zstd.ZstdDecompressor()
with dctx.stream_reader(f) as reader:
text_stream = io.TextIOWrapper(reader, encoding='utf-8')
return text_stream.read() # 读取为字符串
def _vectorized_preprocess(self, data):
input_ids = np.zeros((len(data), self.max_length), dtype=np.int64)
attention_mask = np.zeros((len(data), self.max_length), dtype=np.int64)
labels = np.full((len(data), self.max_length), -100, dtype=np.int64)
slice_indices = np.full((len(data), self.max_length),
-1,
dtype=np.int64)
def process_row(row):
inputs = self.tokenizer(row['text'],
padding=False,
truncation=False,
add_special_tokens=False).input_ids
# slice to 8-token segments. that is, sample_slice is [1, 9, 17, 25, ...]
sample_slice = (np.arange(0, len(inputs), 8) + 1).tolist()
# add the end
if len(inputs) % 8 != 1:
sample_slice.append(len(inputs))
# 截断或填充逻辑
seq_len = min(len(inputs), self.max_length)
# 输入和标签
input_ids = inputs[:self.max_length] + [
self.tokenizer.pad_token_id
] * (self.max_length - seq_len)
labels = [
50279 # <EOS>
] + inputs[:self.max_length -
1] + [-100] * (self.max_length - 1 - seq_len)
# attention_mask
attention_mask = [1] * seq_len + [0] * (self.max_length - seq_len)
# slice_indices
slice_arr = np.array(sample_slice[:self.max_length] + [-1] *
(self.max_length - len(sample_slice)))
slice_arr[slice_arr > self.max_length] = -1 # 过滤超长位置
return input_ids, labels, attention_mask, slice_arr
try:
from pandarallel import pandarallel
pandarallel.initialize(nb_workers=self.proc, progress_bar=True)
processed = data.parallel_apply(process_row, axis=1)
except ImportError:
processed = data.progress_apply(process_row, axis=1) # tqdm 进度条
# 合并结果
for idx, (i_ids, lbl, attn, slc) in enumerate(processed):
input_ids[idx] = i_ids
labels[idx] = lbl
attention_mask[idx] = attn
slice_indices[idx] = slc
return {
"input_ids": input_ids,
"labels": labels,
"attention_mask": attention_mask,
"slice_indices": slice_indices
}
def __len__(self):
return len(self.input_ids)
def __getitem__(self, index):
return (self.input_ids[index], self.labels[index],
self.attention_mask[index], self.slice_indices[index])
|