- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的设置有一个 NVIDIA P100 GPU。我正在使用 Google BERT 模型来回答问题。我正在使用 SQuAD 问答数据集,它为我提供了问题和应从中得出答案的段落,我的研究表明该架构应该没问题,但我在训练期间不断收到 OutOfMemory 错误:
ResourceExhaustedError: OOM when allocating tensor with shape[786432,1604] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
[[{{node dense_3/kernel/Initializer/random_uniform/RandomUniform}}]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
import json
import numpy as np
import pandas as pd
import os
assert os.path.isfile("train-v1.1.json"),"Non-existent file"
from tensorflow.python.client import device_lib
import tensorflow.compat.v1 as tf
#import keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import re
regex = re.compile(r'\W+')
#Reading the files.
def readFile(filename):
with open(filename) as file:
fields = []
JSON = json.loads(file.read())
articles = []
for article in JSON["data"]:
articleTitle = article["title"]
article_body = []
for paragraph in article["paragraphs"]:
paragraphContext = paragraph["context"]
article_body.append(paragraphContext)
for qas in paragraph["qas"]:
question = qas["question"]
answer = qas["answers"][0]
fields.append({"question":question,"answer_text":answer["text"],"answer_start":answer["answer_start"],"paragraph_context":paragraphContext,"article_title":articleTitle})
article_body = "\\n".join(article_body)
article = {"title":articleTitle,"body":article_body}
articles.append(article)
fields = pd.DataFrame(fields)
fields["question"] = fields["question"].str.replace(regex," ")
assert not (fields["question"].str.contains("catalanswhat").any())
fields["paragraph_context"] = fields["paragraph_context"].str.replace(regex," ")
fields["answer_text"] = fields["answer_text"].str.replace(regex," ")
assert not (fields["paragraph_context"].str.contains("catalanswhat").any())
fields["article_title"] = fields["article_title"].str.replace("_"," ")
assert not (fields["article_title"].str.contains("catalanswhat").any())
return fields,JSON["data"]
trainingData,training_JSON = readFile("train-v1.1.json")
print("JSON dataset read.")
#Text preprocessing
## Converting text to skipgrams
print("Tokenizing sentences.")
strings = trainingData.drop("answer_start",axis=1)
strings = strings.values.flatten()
answer_start_train_one_hot = pd.get_dummies(trainingData["answer_start"])
# @title Keras-BERT Environment
import os
pretrained_path = 'uncased_L-12_H-768_A-12'
config_path = os.path.join(pretrained_path, 'bert_config.json')
checkpoint_path = os.path.join(pretrained_path, 'bert_model.ckpt')
vocab_path = os.path.join(pretrained_path, 'vocab.txt')
# Use TF_Keras
os.environ["TF_KERAS"] = "1"
# @title Load Basic Model
import codecs
from keras_bert import load_trained_model_from_checkpoint
token_dict = {}
with codecs.open(vocab_path, 'r', 'utf8') as reader:
for line in reader:
token = line.strip()
token_dict[token] = len(token_dict)
model = load_trained_model_from_checkpoint(config_path, checkpoint_path)
#@title Model Summary
model.summary()
#@title Create tokenization stuff.
from keras_bert import Tokenizer
tokenizer = Tokenizer(token_dict)
def tokenize(text,max_len):
tokenizer.tokenize(text)
return tokenizer.encode(first=text,max_len=max_len)
def tokenize_array(texts,max_len=512):
indices = np.zeros((texts.shape[0],max_len))
segments = np.zeros((texts.shape[0],max_len))
for i in range(texts.shape[0]):
tokens = tokenize(texts[i],max_len)
indices[i] = tokens[0]
segments[i] = tokens[1]
#print(indices.shape)
#print(segments.shape)
return np.stack([segments,indices],axis=1)
#@ Tokenize inputs.
def X_Y(dataset,answer_start_one_hot,batch_size=10):
questions = dataset["question"]
contexts = dataset["paragraph_context"]
questions_tokenized = tokenize_array(questions.values)
contexts_tokenized = tokenize_array(contexts.values)
X = np.stack([questions_tokenized,contexts_tokenized],axis=1)
Y = answer_start_one_hot
return X,Y
def X_Y_generator(dataset,answer_start_one_hot,batch_size=10):
while True:
try:
batch_indices = np.random.choice(np.arange(0,dataset.shape[0]),size=batch_size)
dataset_batch = dataset.iloc[batch_indices]
X,Y = X_Y(dataset_batch,answer_start_one_hot.iloc[batch_indices])
max_int = pd.concat((trainingData["answer_start"],devData["answer_start"])).max()
yield (X,Y)
except Exception as e:
print("Unhandled exception in X_Y_generator: ",e)
raise
model.trainable = True
answers_network_checkpoint = ModelCheckpoint('answers_network-best.h5', verbose=1, monitor='val_loss',save_best_only=True, mode='auto')
input_layer = Input(shape=(2,2,512,))
print("input layer: ",input_layer.shape)
questions_input_layer = Lambda(lambda x: x[:,0])(input_layer)
context_input_layer = Lambda(lambda x: x[:,1])(input_layer)
print("questions input layer: ",questions_input_layer.shape)
print("context input layer: ",context_input_layer.shape)
questions_indices_layer = Lambda(lambda x: tf.cast(x[:,0],tf.float64))(questions_input_layer)
print("questions indices layer: ",questions_indices_layer.shape)
questions_segments_layer = Lambda(lambda x: tf.cast(x[:,1],tf.float64))(questions_input_layer)
print("questions segments layer: ",questions_segments_layer.shape)
context_indices_layer = Lambda(lambda x: tf.cast(x[:,0],tf.float64))(context_input_layer)
context_segments_layer = Lambda(lambda x: tf.cast(x[:,1],tf.float64))(context_input_layer)
questions_bert_layer = model([questions_indices_layer,questions_segments_layer])
print("Questions bert layer loaded.")
context_bert_layer = model([context_indices_layer,context_segments_layer])
print("Context bert layer loaded.")
questions_flattened = Flatten()(questions_bert_layer)
context_flattened = Flatten()(context_bert_layer)
combined = Concatenate()([questions_flattened,context_flattened])
#bert_dense_questions = Dense(256,activation="sigmoid")(questions_flattened)
#bert_dense_context = Dense(256,activation="sigmoid")(context_flattened)
answers_network_output = Dense(1604,activation="softmax")(combined)
#answers_network = Model(inputs=[input_layer],outputs=[questions_bert_layer,context_bert_layer])
answers_network = Model(inputs=[input_layer],outputs=[answers_network_output])
answers_network.summary()
answers_network.compile("adam","categorical_crossentropy",metrics=["accuracy"])
answers_network.fit_generator(
X_Y_generator(
trainingData,
answer_start_train_one_hot,
batch_size=10),
steps_per_epoch=100,
epochs=100,
callbacks=[answers_network_checkpoint])
最佳答案
编辑 :我已经就地编辑了我的回复,而不是增加已经很长的回复的长度。
在查看问题后,您的模型中的最后一层出现了问题。我能够让它与以下修复/更改一起工作。
ResourceExhaustedError: OOM when allocating tensor with shape[786432,1604] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [[{{node dense_3/kernel/Initializer/random_uniform/RandomUniform}}]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
[786432,1604]
的数组。 .如果你做一个简单的计算,你就有
5GB
此处分配的数组(假设为 float32)。如果是
float64
转到
10GB
.添加来自
Bert
的参数和模型中的其他层,中提琴!你的内存不足。
float64
因为您正在指定
float64
为您所有
Lambda
层。所以我的第一个建议是,
tf.keras.backend.set_floatx('float16')
question_indices_layer = Input(shape=(256,), dtype='float16')
question_segments_layer = Input(shape=(256,), dtype='float16')
context_indices_layer = Input(shape=(256,), dtype='float16')
context_segments_layer = Input(shape=(256,), dtype='float16')
questions_bert_layer = model([question_indices_layer,question_segments_layer])
context_bert_layer = model([context_indices_layer,context_segments_layer])
questions_flattened = Flatten(dtype=tf.float16)(questions_bert_layer)
questions_flattened = Dense(64, activation='relu',dtype=tf.float16)(questions_flattened)
contexts_flattened = Flatten(dtype=tf.float16)(context_bert_layer)
contexts_flattened = Dense(64,activation="relu",dtype=tf.float16)
combined = Concatenate(dtype=tf.float16)([questions_flattened,contexts_flattened])
float16
. softmax
层
[batch size, 512, 768]
输出到您的密集层,您可以使用较小的层或一些转换来压缩它。您可以尝试的几件事是,
1604
softmax 层。这显着减少了模型参数。 questions_flattened = Flatten(dtype=tf.float16)(questions_bert_layer)
questions_flattened = Dense(64, activation='relu',dtype=tf.float16)(questions_flattened)
contexts_flattened = Flatten(dtype=tf.float16)(context_bert_layer)
contexts_flattened = Dense(64,activation="relu",dtype=tf.float16)(contexts_flattened)
combined = Concatenate(dtype=tf.float16)([questions_flattened,contexts_flattened])
question
的时间维度求和/求平均值输出。因为,您只关心理解问题是什么,所以从该输出中丢失位置信息是可以的。您可以通过以下方式执行此操作,questions_flattened = Lambda(lambda x: K.sum(x, axis=1))(questions_bert_layer)
Concatenate
试试 Add()
这样你就不会增加维度。 questions_flattend
的尺寸和 answers_flattened
结合使用这些方法时,否则会出错。 512
.我不确定你是如何得出这个数字的,但我认为你可以在低于这个数字的情况下做得更好。例如,您将获得
questions
的以下统计信息和
paragraphs
.
count 175198.000000
mean 11.217582
std 3.597345
min 1.000000
25% 9.000000
50% 11.000000
75% 13.000000
max 41.000000
Name: question, dtype: float64
count 175198.000000
mean 123.791653
std 50.541241
min 21.000000
25% 92.000000
50% 114.000000
75% 147.000000
max 678.000000
Name: paragraph_context, dtype: float64
pd.Series(trainingData["question"]).str.split(' ').str.len().describe()
pad_sequences
填充序列时您没有指定
maxlen
这导致将句子填充到语料库中找到的最大长度。例如,您有一个 678 个元素的长段落上下文,其中 75% 的数据长度低于 150 个单词。
512
但我希望你明白我的意思。从它的外观来看,长度为
150
似乎可以做得很好。 .
n
。在你的语料库中的次数(
n
可以是 10-25 或更好,做一些进一步的分析并找到一个最佳值。)。
vocabulary
统计如下。
counts = sorted([(k, v) for k, v in list(textTokenizer.word_counts.items())], key=lambda x: x[1])
textTokenizer = Tokenizer(num_words=50000, oov_token='unk')
word_index
仍然包含所有单词。所以当你把它作为
token_dict
传递时,你需要确保把这些生僻词去掉。 .
batch_size=10
这应该没问题。但是为了获得更好的结果(并希望在您执行上述建议后获得更多内存),请使用更高的批量大小,例如
32
或
64
,这将提高性能。
关于python - 训练基于 BERT 的模型会导致 OutOfMemory 错误。我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59617755/
我正在调查我们的应用程序运行缓慢的问题,最终导致集群环境中的一个实例出现故障。几周前我遇到了以下错误: [#|2012-05-11T14:12:03.460-0400|SEVERE|sun-appse
我创建了一个应用程序,基本上使用机器人在客户端获取图像并每隔几秒发送一次到服务器,这样我就可以看到另一台 PC 上发生了什么。问题似乎是它一直将图像保存在数组或其他东西中,因为几秒钟后,它崩溃了。我只
我正在使用 universal-image-loader-1.6.2.jar(最新的)。我正在尝试使用此库下载并缓存该图像。我要从服务器下载 47 张图片,总共 5.22 Mb。我的最大图片尺寸为 7
我在玩 Scala 的惰性迭代器,但遇到了一个问题。我想要做的是读取一个大文件,进行转换,然后写出结果: object FileProcessor { def main(args: Array[S
当涉及到服务器环境的垃圾收集/内存限制时,.Net 框架的行为是否可能有所不同?我在具有 32gbs 物理内存的 64 位服务器计算机上显式运行 x86 编译的应用程序,并且内存不足(SystemOu
在我的应用程序启动时,我正在创建具有 75*10^6 容量的长哈希集。 Profiler 显示,该应用程序使用 1.4g。我尝试设置-Xmx1600m,但发现内存不足。 -Xmx2000m 相同。 -
我有一项关于使用数字列表构建金字塔的任务,但一项测试存在一个问题。在我的任务中,我需要对列表进行排序。我使用 Collections.sort(): Collections.sort(inputNum
在对我为 Windows Mobile 编写的类库进行一些最终测试时(使用 Compact Net Framework 2.0),我遇到了 OOM 异常。 基本上,我的库首先加载一个字典文件(一个带有
编辑:我将其重新表述为问题并将答案移至答案部分... 在一个相对复杂的多线程 .NET 应用程序中,我遇到了 OutOfMemoryException,即使在我认为没有理由的情况下也是如此。 情况:
当我尝试使用下面的方法将一些文本内容设置到我们心爱的窗口的剪贴板时 片段,它在 10-15MB 的范围内工作正常。但是超过这个大小,它会抛出一条错误消息 显示在最后。我们如何将 30+ MB 的 ut
我想在 Android 中将 PDF 图像发送到服务器。 服务器规范需要我应该使用 Base64 编码。 所以我应该将 PDF 图像文件转换为 Base64 字符串。 下面是 HTTP POST 请求
我正在解析设备上的二进制文件并将我关心的字段存储在数组中。这些文件可以生成大小为 100,000 的数组。自然地,java 告诉我内存不足(我认为 android 每个应用程序只允许 16MB)。 还
我正在尝试从一个 txt 文件(书籍)中读取,然后将它的每一行添加到一个链表中。但是,当我运行代码时,我在 l.add(line); 处遇到内存不足错误。你能告诉我这段代码做错了什么吗?或者,是否有更
我通过允许用户选择要显示的图片从 SD 卡加载位图。创建位图后,我在 ImageView 中设置位图: mBitmap = Bitmap.createBitmap(Media.getBitmap(th
我试图在 gridview 中显示很多图像。有两个 Activity 。它们都有 gridviews,其中有图像。当我只启动其中一个时。没有问题,但是当我启动另一个时,存在“outifmemory”问
我需要在我的应用程序中显示许多图像。这些是 jpg 和 png,我将它们加载到 ImageView 中,如下所示: tile.setImageResource(R.drawable.tile_high
我正在开发一个远程备份应用程序,有时我需要上传大文件,例如 15 MB,我在一些手机上测试过我遇到内存不足的错误 有没有办法使用这个函数来使用更少的内存? public int uploadFile(
我在模拟器和设备(acer 平板电脑和三星 galaxy)上运行我的项目时出现 OutOfMemory 异常,显示 the application launcher process com.andro
我有一个程序可以为目录(子)树中的每个文件创建一个对象。在磁盘越来越大的今天,没有办法知道会有多少文件,尤其是。不是几年(几个月?)从现在开始。 我的程序不是企业关键的;它是用户分析该子树的工具。所以
我已经使用以下命令从命令行启动了我的jar java -Xms1200m -Xmx1500m -jar xxx.jar 我正在创建大小为 12600 * 12600 的 BufferedImage 意
我是一名优秀的程序员,十分优秀!