[英]Tokenizing & encoding dataset uses too much RAM
尝试对数据进行标记和编码以提供给神经网络。
我只有 25GB 的 RAM,每次我尝试在我的 google colab 崩溃下运行代码时。 知道如何防止他的发生吗? “您的 session 在使用所有可用 RAM 后崩溃”
我认为标记/编码 50000 个句子的块会起作用,但不幸的是没有。 该代码适用于长度为 130 万的数据集。 当前数据集的长度为 500 万。
max_q_len = 128
max_a_len = 64
trainq_list = train_q.tolist()
batch_size = 50000
def batch_encode(text, max_seq_len):
for i in range(0, len(trainq_list), batch_size):
encoded_sent = tokenizer.batch_encode_plus(
text,
max_length = max_seq_len,
pad_to_max_length=True,
truncation=True,
return_token_type_ids=False
)
return encoded_sent
# tokenize and encode sequences in the training set
tokensq_train = batch_encode(trainq_list, max_q_len)
分词器来自 HuggingFace:
tokenizer = BertTokenizerFast.from_pretrained('bert-base-multilingual-uncased')
无论大小如何,您都应该使用生成器并将数据传递给tokenizer.batch_encode_plus
。
从概念上讲,是这样的:
这可能包含从某些文件中读取的句子列表。 如果这是一个大文件,您可以按照这个答案懒惰地读取部分输入(最好一次读取batch_size
行):
def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
否则打开单个文件(比 memory 小得多,因为使用 BERT 编码后它会大得多),如下所示:
import pathlib
def read_in_chunks(directory: pathlib.Path):
# Use "*.txt" or any other extension your file might have
for file in directory.glob("*"):
with open(file, "r") as f:
yield f.readlines()
编码器应该使用这个yield
器并返回编码部分,如下所示:
# Generator should create lists useful for encoding
def batch_encode(generator, max_seq_len):
tokenizer = BertTokenizerFast.from_pretrained("bert-base-multilingual-uncased")
for text in generator:
yield tokenizer.batch_encode_plus(
text,
max_length=max_seq_len,
pad_to_max_length=True,
truncation=True,
return_token_type_ids=False,
)
由于文件太大而无法放入 RAM memory,您应该将它们保存到磁盘(或在生成时以某种方式使用)。
沿着这些思路:
import numpy as np
# I assume np.arrays are created, adjust to PyTorch Tensors or anything if needed
def save(encoding_generator):
for i, encoded in enumerate(encoding_generator):
np.save(str(i), encoded)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.