SpaCy模型不会在AWS Lambda中加载

pyn*_*ewb 6 aws-lambda spacy

有人得到过SpaCy 2.0可以在AWS Lambda中工作吗?我已正确压缩并打包了所有内容,因为如果我对其进行测试,则可以从lambda函数返回通用字符串。但是,当我执行下面的简单功能进行测试时,它停滞了大约10秒钟,然后返回空白,并且没有收到任何错误消息。我确实将Lambda超时设置为60秒,所以这不是问题。

import spacy

nlp = spacy.load('en_core_web_sm') #model package included

def lambda_handler(event, context):
    doc = nlp(u'They are')
    msg = doc[0].lemma_
    return msg
Run Code Online (Sandbox Code Playgroud)

当我加载模型包而不使用它时,它也返回空,但是如果我注释掉它,它会按预期向我发送字符串,因此它必须与加载模型有关。

import spacy

nlp = spacy.load('en_core_web_sm') #model package included

def lambda_handler(event, context):
    msg = 'message returned'
    return msg
Run Code Online (Sandbox Code Playgroud)

pyn*_*ewb 5

知道这可能会很简单。答案是没有足够的分配内存来运行 Lambda 函数 - 我发现我必须将它最小地增加到接近最大 2816 MB 才能使上面的示例工作。值得注意的是,在上个月之前,不可能涨到这么高:

https://aws.amazon.com/about-aws/whats-new/2017/11/aws-lambda-doubles-maximum-memory-capacity-for-lambda-functions/

我把它调到最大 3008 MB 来处理更多的文本,现在一切似乎都很好。

  • 你是如何将 spacy 模块安装在 AWS Lambda 中的? (2认同)

ryf*_*eus 5

要优化模型加载,您必须将其存储在 S3 上,并使用您自己的脚本将其下载到 lambda 中的 tmp 文件夹,然后将其加载到 spacy 中。

从 S3 下载并运行需要 5 秒钟。这里最好的优化是将模型保存在热容器上并检查它是否已经下载。在暖容器上运行代码需要 0.8 秒。

这是代码和包的链接,示例:https : //github.com/ryfeus/lambda-packs/blob/master/Spacy/source2.7/index.py

import spacy
import boto3
import os


def download_dir(client, resource, dist, local='/tmp', bucket='s3bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        if result.get('Contents') is not None:
            for file in result.get('Contents'):
                if not os.path.exists(os.path.dirname(local + os.sep + file.get('Key'))):
                     os.makedirs(os.path.dirname(local + os.sep + file.get('Key')))
                resource.meta.client.download_file(bucket, file.get('Key'), local + os.sep + file.get('Key'))

def handler(event, context):
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    if (os.path.isdir("/tmp/en_core_web_sm")==False):
        download_dir(client, resource, 'en_core_web_sm', '/tmp','ryfeus-spacy')
    spacy.util.set_data_path('/tmp')
    nlp = spacy.load('/tmp/en_core_web_sm/en_core_web_sm-2.0.0')
    doc = nlp(u'Apple is looking at buying U.K. startup for $1 billion')
    for token in doc:
        print(token.text, token.pos_, token.dep_)
    return 'finished'
Run Code Online (Sandbox Code Playgroud)

PS 要在 AWS Lambda 中打包 spacy,您必须剥离共享库。