오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-02 05:05
관리 메뉴

우노

[AWS CLI] Custom Sparse Matrix 생성 자동화 코드 본문

AWS/CLI

[AWS CLI] Custom Sparse Matrix 생성 자동화 코드

운호(Noah) 2020. 12. 20. 02:34

사전 작업

  • 생성할 Custom Sparse Matrix 값이 담겨있는 csv 파일을 s3에 업로드
  • 로컬에 있는 customsparsematrix.sh 수정
    • 생성할 Custom Sparse Matrix 값이 담겨있는 csv s3 경로 수정
    • 생성한 Custom Sparse Matrix를 저장할 s3 경로 수정

AWS CLI Instance 생성 명령어

  • --user-data : Instance 생성 시 실행할 로컬 쉘 스크립트 경로

      aws ec2 run-instances \
      --user-data file:///Users/bdlab/Desktop/aws-lab/customsparsematrix.sh \
      --image-id ami-00f045aed21a55240 \
      --count 1 \
      --instance-type c5a.xlarge \
      --key-name unho-tokyo \
      --security-group-ids sg-05c13765ef7b68b36 \
      --subnet-id subnet-956befce

Custom Sparse Matrix 생성 쉘 스크립트 (customsparsematrix.sh)

#!/bin/bash

# 생성할 Custom Sparse Matrix 값이 담겨있는 csv s3 경로
inputcsv_s3="s3://unho-spmm/csv/spmm-scenario-extraction/test/input-2-3.csv"
# 생성한 Custom Sparse Matrix를 저장할 s3 경로
export matrixdata_s3="s3://unho-spmm/custom-nonsquare-matrix/test/"

# 입력파일을 절대경로로 재설정
inputcsv_parse=(`echo $inputcsv_s3 | tr "/" "\n"`)
export inputcsv_local="/home/ec2-user/${inputcsv_parse[${#inputcsv_parse[@]}-1]}"

yum update -y # 패키지 업데이트
yum install python3 -y # python3 설치

# aws configure 설정
aws configure set aws_access_key_id **********
aws configure set aws_secret_access_key **********
aws configure set region ap-northeast-1
aws configure set output text

# S3에서 local로 input.csv 파일 다운로드
aws s3 cp ${inputcsv_s3} ${inputcsv_local}

count=1
# 입력파일의 마지막 줄 마지막 문자를 \n으로 치환하며
# line 마다 ',' 기준으로 split 해 변수로 사용한다.
sed "$ s/\$/\\n/" ${inputcsv_local} | tr -d '\r' | while IFS=',' read lr lc rc ld rd lnnz rnnz;
do 

    # head 이후부터 실행
    if [ $count -gt 1 ]; then

                export lr=$lr
                export lc=$lc
                export rc=$rc
                export ld=`printf '%.8f' $ld`
                export rd=`printf '%.8f' $rd`
                export lnnz=$lnnz
                export rnnz=$rnnz

                python3 - << 'EOF'
import random
import os
import subprocess

# row, col, density를 만족하는 custom sparse matrix 생성 후 dir에 저장
def make_sparse_matrix(row, col, density, nnz, dir):

    # 결과 파일명 (M_행_열_density_nnz)
    file = "M_" + str(row) + "_" + str(col) + "_" + str(density) + "_" + str(nnz)  

    # nnz 개수 만큼 행, 열, 값 난수를 생성
    with open(dir+file,"w") as w:  
        for i in range(nnz): 
            # 행,열,값 난수 생성
            row_idx = random.randrange(0,row)
            col_idx = random.randrange(0,col)
            value = random.random()

            # COO 형식의 line 생성 
            line = str(row_idx) + " " + str(col_idx) + " " + str(value) + "\n"

            w.write(line)

    # 해당 파일 s3로 업로드
    subprocess.call(["aws","s3","cp",dir+file,os.environ["matrixdata_s3"]])

    # 해당 파일 instance에서 삭제        
    subprocess.call(["rm","-rf",dir+file])

# left custom sparse matrix 생성
make_sparse_matrix(int(os.environ["lr"]), int(os.environ["lc"]), os.environ["ld"], int(os.environ["lnnz"]),"/home/ec2-user/")

# right custom sparse matrix 생성
make_sparse_matrix(int(os.environ["lc"]), int(os.environ["rc"]), os.environ["rd"], int(os.environ["rnnz"]),"/home/ec2-user/")

EOF
    fi

        ((count++))

done

# 인스턴스 종료
instance_id=(`ec2-metadata -i | tr ":" "\n"`)
aws ec2 terminate-instances --instance-ids ${instance_id[1]}
Comments