GithubHelp home page GithubHelp logo

ddps-lab / lambda-optimize-serving Goto Github PK

View Code? Open in Web Editor NEW
3.0 3.0 4.0 8.53 MB

lambda converter and lambda serving

License: Apache License 2.0

Dockerfile 0.01% CMake 0.74% Shell 0.86% Python 55.23% Makefile 0.24% Java 0.73% C++ 39.79% RenderScript 0.01% C 1.26% Objective-C 0.09% Objective-C++ 0.32% Rust 0.11% Batchfile 0.01% Cython 0.11% Cuda 0.06% HTML 0.01% JavaScript 0.06% TypeScript 0.35% Jupyter Notebook 0.03%

lambda-optimize-serving's People

Contributors

kmu-leeky avatar subeans avatar workdd avatar

Stargazers

 avatar  avatar

Watchers

 avatar

lambda-optimize-serving's Issues

[AYCI] Max Memory parsing 에러 해결

아카이브 람다에서 해당 에러가 발생했습니다.

[ERROR] ValueError: invalid literal for int() with base 10: ‘5.21E8’
Traceback (most recent call last):
  File “/var/task/lambda_function.py”, line 100, in lambda_handler
    max_memory_used = getMemoryUsed(info)
  File “/var/task/lambda_function.py”, line 36, in getMemoryUsed
    max_memory_used = int(r[‘value’]) / 1000000

이는 memory가 클경우 5.21E8과 같은 형식으로 제공하는 것으로 판단되며 int() 로 변환이 안되는 경우인 듯 합니다.
python의 해당 경우를 처리할 수 있는 library가 있는걸로 알고있으며 해결해보겠습니다.

lambda model serving / optimize 이미지 생성

lambda 이미지 생성

  1. s3 에 있는 모델을 가져와 serving 하는 이미지( torch serving , onnx serving , tvm serving )
  2. torch 원본 모델을 optimize 해서 s3에 저장하는 lambda이미지 ( onnx - graph optimize , tvm - hardware optimize )

[ AYCI ] lambda 이미지 복원 불가능 에러

이전에 재강이가 실행시 확인한 에러와 동일한 에러가 발생하였습니다.
이전 상황의 경우 ECR내에 복원할 이미지가 존재하지 않아 복원이 불가능한 문제였습니다.

하지만 현재의 경우 ECR내 복원할 이미지가 존재함에도 불구하고 자동으로 복원이 되지 않는 문제입니다. 수동적으로 이미지 할당을 진행하니 별 다른 변경없이 다시 잘 작동합니다. 이와 같은 에러가 빈번하게 일어나기 때문에 정확한 이유를 확인해볼 필요도 있을 것 같습니다.

Image

base serving의 경우 convert_time 0으로 리턴하도록 수정

람다 아카이브 모듈 구성실험을 해보면서 convert_time이 없다는 에러가 떳습니다.
현재 base serving에서는 convert 과정이 없어 해당 parameter를 넘겨주지 않았는데 따라서 해당 에러가 발생했습니다.
base serving의 경우 0의 값으로 넘겨주어 해결하려고합니다.

[ AYCI ] s3 객체 불러오는 방법 수정

현재 convert 후 json 으로 결과저장 , inference 후 json으로 결과저장 그리고 종합적으로 maxmemoryUsed 포함 json 파일을 s3에 업로드합니다.

s3의 obj_list = s3_client.list_objects(Bucket=BUCKET_NAME,Prefix=prefix) 코드 사용시 해당 API에서는 최대 1000개 까지의 objects만 불러올 수 있어 원하는 결과가 저장되어있더라도 불러오지 못하는 이슈가 있습니다.

따라서 S3 버킷의 객체가 1,000개를 넘을 때 객체 목록 조회하는 방법을 적용합니다.
https://gonigoni.kr/posts/list-over-1000-files-from-s3/

[ AYCI ] convert , inference , maxmemory used 결과 파일 분리

현재 convert time, inference time을 파라미터로 전달하여 발생할 수 있는 종속성을 분리하기 위해 결과 저장하는 형식을 변경합니다.
archive module에서 하나의 json 파일을 업로드하는 방식에서 각 convert,inference 람다에서 결과를 json으로 저장하도록 구성합니다.

[AYCI] 프론트엔드를 위한 해싱 및 바이트 크기 계산

  1. sha256 함수를 이용해 파일을 hashing하는 코드를 구현하였습니다.
  2. byte 단위로 파일의 크기를 측정하는 코드를 구현하였습니다.

두 가지의 작업을 하나의 웹상에 출력하기 위해서
파일 업로드 후 hashing과 size가 출력되도록 하는 html 파일을 작성하였습니다.

아래는 파일 업로드 후의 결과입니다.
image

아래는 파일 hashing, sizing 코드입니다.

<h2>File Select</h2>
<div>
  Select file
  <br/>
  <input type="file" id="fileselector" onchange="javascript:hashfile(); fileSize(this)">
</div>
<br/>
<div id="divresult"></div>
<div id="filesize"></div>

<script>
    function hashfile() {
        readbinaryfile(fileselector.files[0])
          .then(function(result) {
            result = new Uint8Array(result);
            return window.crypto.subtle.digest('SHA-256', result);
          }).then(function(result) {
            result = new Uint8Array(result);
            var resulthex = Uint8ArrayToHexString(result);
            divresult.innerText = 'hash : ' + resulthex;
          });
      }
      
      function readbinaryfile(file) {
        return new Promise((resolve, reject) => {
          var fr = new FileReader();
          fr.onload = () => {
            resolve(fr.result)
          };
          fr.readAsArrayBuffer(file);
        });
      }
      
      function Uint8ArrayToHexString(ui8array) {
        var hexstring = '',
          h;
        for (var i = 0; i < ui8array.length; i++) {
          h = ui8array[i].toString(16);
          if (h.length == 1) {
            h = '0' + h;
          }
          hexstring += h;
        }
        var p = Math.pow(2, Math.ceil(Math.log2(hexstring.length)));
        hexstring = hexstring.padStart(p, '0');
        return hexstring;
      }

</script>

<script>
  var fileSize = ($target) => {
    var file = $target.files[0];
    document.getElementById("filesize").innerText = 'size : ' + file.size.toLocaleString("en-US") + ' Byte'; 
  }
</script>


[AYCI] input parameter의 구조 변경

기존 compiler, hardware에 대해서 input은 다음과 같은 구조로 입력받습니다.
compiler: ["onnx", "tvm"]
hardware:["intel", "arm"]

하지만, 중복체크를 하는 람다를 만들면서 해당 구조에 문제가 있음을 알게 되었습니다.
만약 onnx - intel 조합과 tvm-arm 조합은 s3에 이미 저장된 결과가 있고, tvm-intel 조합과, onnx-arm 조합은 저장된 결과가 없어 step function에서 추론 작업이 진행해야 될 때 현재 처리하는 방식으로는 문제가 있습니다.
왜냐하면 똑같이 step function에는 다음과 같이 전달되기 때문입니다.
compiler: ["onnx", "tvm"]
hardware:["intel", "arm"]
그래서 이미 결과가 있는 onnx-intel, tvm-arm 조합도 추론 작업이 진행될 것이며 이는 s3 결과가 있음에도 추론이 진행되는 문제가 있습니다.

따라서 파라미터 구조를 다음과 같이 변경하기로 했습니다.
configuration : {"intel" : ["onnx", "tvm"] , "arm" : ["onnx", "tvm"] }

이렇게 변경하면 각 조합별로 처리가 가능하며 s3에 없는 것만 추론 작업을 진행할 수 있을 것 입니다.
이와 같은 방식으로 코드를 수정할 계획입니다.

추가 개발 사항 정리

  • model size 파라미터 bytes 단위로 받기
  • 클라이언트에서 model input size도 받기
  • 클라이언트에서 workload 종류 정하기 (이미지 분류, 자연어 처리 등)
  • 자연어 처리 inference 작업 진행

[ AYCI ] 메모리 부족으로 요청한 추론이 모두 진행되지 않을 경우 에러처리

현재 사용자는 하드웨어와 optimizer 의 중복 선택으로 요청을 한 번에 여러개를 줄 수 있습니다.
해당 과정은 stepfunction 을 통해 병렬적으로 진행됩니다.

만약 사용자가 4가지 요청을 주었을 때 그 중 3가지 요청만 진행되는 경우에 대한 에러처리는 완료되었으나 4가지 요청이 모두 실행이 안될 경우 archive lambda 에서 받는 파라미터에 문제가 발생합니다. 따라서 해당 부분을 코드 작업으로 해결진행합니다.

[AYCI] MaxMemoryUsed 값 return

진행해야할 작업

  • inference 람다에서는 log group name과, log에 해당하는 request id를 return
  • archive 람다에서는 얻은 log 관련 정보로 boto3를 이용해 MaxMemoryUsed값을 얻고 리턴함

maxMemoryUsed값은 byte 단위로 추가적으로 MB로 변환하는 과정 포함될 수 있습니다

[AYCI] Arm Tvm converter, inference lambda 코드 이상, tvm 환경 이상 체크

현재 step function 시스템 내에서 성능 측정을 해보는 중입니다.
그 결과 예전에 arm tvm에서 추론 성능을 측정해보았을 때보다 성능이 정상적이지 않은 수준으로 안좋게 나오는 상황입니다.

<style type="text/css"></style>

inception_v3 torch onnx tvm torch onnx tvm
convert time   8.56 89.5   9.21 565.59
inference lambda time 11.43 2.46 13.53 4.61 4.57 66.65

inception_v3를 대표적으로 보았을 때, 565초의 convert time과 1분 이상의 추론 시간이 소요되는 것은 세팅에 문제가 있다고 판단이 됩니다. 따라서 이를 한번 체크해보아야 할 듯 합니다.

[ AYCI ] archive lambda 의 cloudwatch log 지연으로 인한 에러

추론을 진행하고 저장하는 단계에서 Max memory used 를 cloud watch log를 보고 지표를 가져옵니다.
이때 cloud watch log 지연으로 인해 response를 제대로 못가져오는 경우가 발생하여 wait 을 2분을 설정하였지만
2분도 부족한 경우가 발생하여 150초 혹은 180초(3분)으로 늘려서 진행합니다.

wait 시간을 늘림에 따라 발생할 수 있는 이슈를 생각하고 ses 전송하는 방법에 대해서도 다시 고려해볼 필요가 있습니다.

모델 download, upload hashing 코드 추가

현재 코드상에서 추가적으로 아래 규칙에 따른 모델 이름 해싱 작업이 필요합니다.

batch 별로 모델이 달라야 하는 optimizer들과 모델 구별이 필요없는 base를 나누어 고려했습니다.
아래의 규칙 대로 해시 작업을 진행합니다.

tvm , onnx
hardware + framework + optimizer + batchsize + modelname
base
hardware + framework + optimizer + modelname

[AYCI] 에러 처리

현재 에러 발생을 하면 어떠한 response없이 step function이 중단됩니다.

따라서 에러 상황을 파악하고 코드상으로 처리하여 해당 에러에 대한 response를 보내주는 처리가 필요합니다.

[AYCI] Memory별 Step Function , 람다 생성 자동화

메모리를 웹에서 dropdown과 같은 형태로 선택하고, 각 메모리별 대응 할 수 있도록
Step Function과 람다를 생성해놓는 것으로 람다 메모리 대응을 하기로 결정되었습니다.
따라서 해당 환경을 빠르게 빌드할 수 있도록 자동화 코드를 만들 계획입니다.

Torch, Onnx, TVM Serving 코드 전반적 수정

사용자의 웹에 response를 줄 때, 추론 성능과 더불어 해당 모델의 정확도 또한 표현해 주어야 할 것 같습니다.
따라서 정확도를 return 하는 코드를 추가합니다.
정확도에 대해서 표현을 해주어야 할지 우선 논의가 필요합니다.

[Action Required] Please update to the latest Neuron Driver (aws-neuron-dkms version 2.3.26 or newer)

업데이트 관련한 이메일 옴

[Root: BigData Lab in KMU]

Hello,

Our records indicate that during the last 12 months you have used the EC2 Inf1 instances [1] with this account. AWS Neuron [2] is the SDK for Inf1 instances and is integrated in machine learning (ML) frameworks like PyTorch and TensorFlow. We are asking that you update the Neuron Driver to the latest (version 2.3.26 or newer) so that you can benefit from operational and security updates.

What do I need to do?
You must update to the latest Neuron Driver (aws-neuron-dkms version 2.3.26 or newer) before installing or upgrading to latest Neuron release.

#If you are using Ubuntu please run:

  1. Configure Linux for Neuron repository updates
    . /etc/os-release
    sudo tee /etc/apt/sources.list.d/neuron.list > /dev/null <<EOF
    deb https://apt.repos.neuron.amazonaws.com/ ${VERSION_CODENAME} main
    EOF
    wget -qO - https://apt.repos.neuron.amazonaws.com/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB | sudo apt-key add -

  2. Update OS packages
    sudo apt-get update -y

  3. Install OS headers
    sudo apt-get install linux-headers-$(uname -r) -y

  4. Install Neuron Driver
    sudo apt-get install aws-neuron-dkms -y

    #If you are using Amazon Linux 2 please run:

  5. Configure Linux for Neuron repository updates
    sudo tee /etc/yum.repos.d/neuron.repo > /dev/null <<EOF
    [neuron]
    name=Neuron YUM Repository
    baseurl=https://yum.repos.neuron.amazonaws.com/
    enabled=1
    metadata_expire=0
    EOF
    sudo rpm --import https://yum.repos.neuron.amazonaws.com/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB

  6. Update OS packages
    sudo yum update -y

  7. Install OS headers
    sudo yum install kernel-devel-$(uname -r) kernel-headers-$(uname -r) -y

  8. Remove existing Neuron Driver
    sudo yum remove aws-neuron-dkms

  9. Install Neuron Driver
    sudo yum install aws-neuron-dkms -y

    For full installation instructions please check the Neuron setup guide [4] on Neuron documentation.

    If you have any questions or concerns about this change or if you are facing issues please send an email to “[email protected]”, open a Github issue [5] or post a question in Neuron AWS forums [6].

    [1] https://aws.amazon.com/ec2/instance-types/inf1/
    [2] https://aws.amazon.com/machine-learning/neuron/
    [3] https://awsdocs-neuron.readthedocs-hosted.com/en/latest/release-notes/index.html
    [4] https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-intro/neuron-install-guide.html
    [5] https://github.com/aws/aws-neuron-sdk/issues
    [6] https://forums.aws.amazon.com/forum.jspa?forumID=355

Sincerely,
Amazon Web Services

[AYCI] SES 코드작업

model convert 한 후 이메일 전송과 inference 후 결과 전송을 위한 코드 작성을 진행합니다.

람다 코드 분리와 파라미터 input 받기

현재 model converter, model inference lambda 코드가 base, onnx, tvm 모두 하나에 람다에서 실행되도록 구성되어 있고 각 환경별로 하나의 람다가 매치 되도록 코드 분리작업을 수빈이와 진행중입니다.

[AYCI] json파일을 pandas dataframe으로 변환하기

s3에 저장되어 있는 json 파일들이 너무 많아 하나하나 값을 따로 보기 어려워 pandas를 이용해 한 눈에 보기 쉽도록 python구현을 하였습니다. 재강님과 수빈님께서 할당해주셨습니다.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.