问题描述
在tensorflow_hub模型中加载时是否可以减少内存使用量?
截至目前,它已达到heroku的内存配额上限512 mb。
是否可以以某种方式拆分负载?我曾尝试将其线程化并在后台加载,但这仅解决了请求超时的问题。
from flask import Flask,render_template,url_for,make_response,jsonify,request
import tensorflow_hub as hub
import numpy as np
import tensorflow as tf
import threading
app = Flask(__name__,template_folder='templates')
def semantic(search1,search2):
comparison = model([search1,search2])
return np.inner(comparison[0],comparison[1])
def task():
module_url = "https://tfhub.dev/google/universal-sentence-encoder/4" #@param ["https://tfhub.dev/google/universal-sentence-encoder/4","https://tfhub.dev/google/universal-sentence-encoder-large/5"]
model = hub.load(module_url)
tf.keras.backend.clear_session()
@app.route('/')
def menu():
threading.Thread(target=task).start()
return render_template("index.html")
@app.route('/<search1>/<search2>',methods=['POST','GET'])
def deploy(search1,search2):
compare = semantic(search1,search2)
compare = compare*100
compare = str(compare)
compare = compare.strip("")
response = {
"Semantic Similarity": compare
}
if request.method == 'POST':
return make_response(jsonify(response),200)
else:
return render_template("results.html",compare=compare,)
感谢您浏览此线程,我一直在寻找答案,但唯一的解决方案是要么迁移到另一个平台,要么只是付费。
解决方法
据我所知,在这种情况下没有太多人可以做。内存量取决于负责从序列化表示中加载权重和图形的逻辑的内部TensorFlow实现。因此,您可以尝试向TensorFlow提交功能请求,以查看是否可以改进该逻辑以提高内存意识。
或者,从tfhub.dev加载模型时,库会将内容复制到本地临时目录。如果此目录是内存映射的,则将缓存的位置更改为非内存映射的位置可能会有所帮助。这可以通过设置TFHUB_CACHE_DIR环境变量来完成。
最后,如果这些方法都不起作用,那么也可以尝试使用尺寸较小的其他模型。