<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Cloud Villains - Medium]]></title>
        <description><![CDATA[복잡하고 신기한 클라우드 컴퓨팅 세계에 오신 것을 환영합니다. 퍼블릭 클라우드와 클라우드 주변의 모든 기술을 담당하는 메가존클라우드의 테크 커뮤니티이자 클라우드 빌런들의 아지트 입니다. - Medium]]></description>
        <link>https://medium.com/cloudvillains?source=rss----b89c9d54c8bb---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Cloud Villains - Medium</title>
            <link>https://medium.com/cloudvillains?source=rss----b89c9d54c8bb---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/cloudvillains" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Snowflake Connector(Python)용 AWS Lambda Custom Layer]]></title>
            <link>https://medium.com/cloudvillains/snowflake-connector-python-%EC%9A%A9-aws-lambda-custom-layer-08d57b2ff6e6?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/08d57b2ff6e6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[snowflake-connector]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 23:44:08 GMT</pubDate>
            <atom:updated>2024-07-08T23:44:08.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Snowflake의 Task를 AWS Lambda를 이용하면 필요한 조건에 따라서 실행할 수 있습니다. 그렇지만 AWS Lambda에서는 Snowflake Connector를 기본적으로 지원하지 않기 때문에 Custom Layer를 생성해서 함수가 잘 작동할 수 있도록 환경을 구성해야 합니다. 따라서 오늘은 Snowflake Connector(Python)용 AWS Lambda Custom Layer를 아래의 순서로 생성해보겠습니다.</p><ul><li>미리 알아두어야 할 사항</li><li>리눅스 환경에서 파일을 생성하기 위해서 Ubuntu EC2를 생성</li><li>Dependencies 설치 및 압축 파일 만들기</li><li>AWS Lambda Custom Layer 생성</li><li>Sample 코드 실행으로 정상적인 동작 확인하기</li></ul><h4>미리 알아두어야 할 사항</h4><p><a href="https://docs.aws.amazon.com/lambda/latest/dg/python-layers.html#python-layer-compatibility">Python용 AWS Lambda Custom Layer는 Amazon Linux에서 동작합니다</a>. 그래서 리눅스 환경에서 Zip File을 생성해야 합니다. 특히 개인 랩탑(Mac, Windows)에서 Zip File 생성 시 잘 동작하지 않습니다. 현시점(2024–07–08) 기준으로 Snowflake는 Python 버전 3.11을 추천합니다.</p><h4>리눅스 환경에서 파일을 생성하기 위해서 Ubuntu EC2를 생성</h4><ul><li>인스턴스에서 Launch Instances를 클릭합니다</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZY5rhvh6h89_QcftZSGeQ.png" /></figure><ul><li>이름을 넣고 우분투를 선택하고 key pair를 생성합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*T8nXXqdSrkRPEfJlpWwCZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*v72rPgbOLM0wcjIcmiJu6w.png" /></figure><ul><li>Connect to your instance를 클릭합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKgPNk2o7krXcoLMwIas1g.png" /></figure><ul><li>아래의 방법을 참고하여 생성된 EC2 인스턴스에 SSH를 통해서 접속합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*hvgGSMDatZLctDSbdDFvFg.png" /></figure><h4>Dependencies 설치 및 압축 파일 만들기</h4><ul><li>접속한 SSH Client(Terminal)에서 아래의 코드를 실행하여 Dependency를 설치합니다.</li></ul><pre># sudo apt를 업데이트합니다<br>sudo apt update<br><br># python dependency를 설치하기 위해 pip를 설치합니다<br>sudo apt install pip<br><br># 압축파일을 만들기 위해 zip을 설치합니다.<br>sudo apt install zip<br><br># 디렉토리를 만들고 snowflake connector를 설치합니다.<br>mkdir -p temp/python<br>cd temp/python<br>pip3 install snowflake-connector-python -t .</pre><ul><li>압축 파일 만들기</li></ul><pre># zip 파일을 생성합니다<br>cd ..<br>zip -r9 ../snowflake-connector-python.zip .</pre><ul><li>로컬 폴더에 압축 파일 다운로드하기</li></ul><pre># 새로운 터미널에서 아래의 명령어를 실행합니다<br># pem키, EC2 디렉토리, 로컬 PC 디렉토리는 사용자의 상황에 맞게 변경합니다<br>scp -i &quot;snowflake_connector_ec2_key.pem&quot; ubuntu@ec2-3-36-67-138.ap-northeast-2.compute.amazonaws.com:/home/ubuntu/snowflake-connector-python.zip /Users/mzc01-ssm/Downloads snowflake-connector-python.zip</pre><h4>AWS Lambda Custom Layer 생성</h4><ul><li>Layers를 선택하고 Create layer를 클릭합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-LathiDBYfzQGFPjAf3Tw.png" /></figure><ul><li>이름을 기입하고 zip file을 업로드하고 생성합니다. 생성 후 ARN을 복사합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*lvRC4_VC1eFWkKXSg75uZA.png" /></figure><h4>Sample 코드 실행으로 정상적인 동작 확인하기</h4><ul><li>함수를 생성합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-87tKuZbftuL7Lht0rcHEg.png" /></figure><ul><li>함수 이름, 런타임을 설정하고 함수를 생성 완료합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*p5V8ly1vmY-6v26xhj5tEg.png" /></figure><ul><li>Add a layer를 클릭하고 복사 된 ARN으로 Layer를 더합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6rPw0APvj3EOBdO-tRfYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*-Rv_41pS3-N6Gd3zydq47Q.png" /></figure><ul><li>아래의 함수를 넣고 Deploy를 누릅니다.</li></ul><pre>import json<br>import snowflake.connector<br><br>conn = snowflake.connector.connect(<br>user=&#39;xxxxxxxxxxxxx&#39;,<br>password=&#39;xxxxxxxxxxxxx&#39;,<br>account=&#39;xxxxxxxxxxxxx&#39;,<br>warehouse=&#39;xxxxxxxxxxxxx&#39;,<br>database=&#39;xxxxxxxxxxxxx&#39;,<br>schema=&#39;xxxxxxxxxxxxx&#39;<br>)<br>cs = conn.cursor()<br>cs.execute(&#39;execute task mzc_test_task1&#39;)<br>one_row = cs.fetchone()<br><br>cs.close()<br>conn.close()<br>    <br>def lambda_handler(event, context):<br><br>    # TODO implement<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;SnowflakeTaskStatus&#39;: one_row[0]<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BIZnewbUQlFhZm2tYAoyg.png" /></figure><ul><li>Test를 눌러서 테스트를 생성하고 코드를 실행합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tc_A-RC64Mw_fp4skJEPgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*uwVL0_yauoyc3cuaHexgdQ.png" /></figure><ul><li>테스트 결과 정상적으로 Python Connector가 동작하고 있을 것을 확인할 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5dfRkj9WchG3gG91tpyXg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08d57b2ff6e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/snowflake-connector-python-%EC%9A%A9-aws-lambda-custom-layer-08d57b2ff6e6">Snowflake Connector(Python)용 AWS Lambda Custom Layer</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform과 AWS Well-Architected Framework를 이용한 마이그레이션과 현대화]]></title>
            <link>https://medium.com/cloudvillains/aws-partner-summit-seoul-hands-on-%EC%84%B8%EC%85%98-%EC%A7%80%EC%9B%90-%ED%9B%84%EA%B8%B0-well-architected-%EC%97%90-%EA%B8%B0%EB%B0%98%ED%95%98%EC%97%AC-%EC%9B%8C%ED%81%AC%EB%A1%9C%EB%93%9C%EB%A5%BC-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%EB%A7%88%EC%9D%B4%EA%B7%B8%EB%A0%88%EC%9D%B4%EC%85%98%ED%95%98%EA%B3%A0-%ED%98%84%EB%8C%80%ED%99%94%ED%95%98%EA%B8%B0-a5a389a61bd6?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5a389a61bd6</guid>
            <category><![CDATA[aws-partner-summit]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[메가존클라우드]]></category>
            <category><![CDATA[terraform-enterprise]]></category>
            <category><![CDATA[hashicorp]]></category>
            <dc:creator><![CDATA[이준호(CTC)]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 04:55:14 GMT</pubDate>
            <atom:updated>2024-05-03T06:32:44.644Z</atom:updated>
            <content:encoded><![CDATA[<p>지난 4월 23일 AWS Partner Summit Seoul에서 ‘<strong>Well-Architected 에 기반하여 워크로드를 안전하게 마이그레이션하고 현대화하기</strong>’를 주제로 Hands On 세션이 진행되었습니다.</p><p>해당 세션에서는 AWS의 Partner들을 대상으로 HashiCorp Terraform을 기반의 안전하게 마이그레이션하고 보안, 거버넌스 관리의 표준을 운영 단계에서도 유지할 수 있는 방안을 소개하였습니다.</p><p>메가존클라우드의 DevOps Product Team은 해당 세션의 Hands-On 환경 구축 및 시나리오 구성을 지원하는 숨은 조력자로 참여하게 되었습니다.</p><p>이 글에서는 간략한 세션 내용과 Hands-On을 위해 준비한 내용 그리고 준비 과정에서 겪은 문제점과 트러블 슈팅 과정에 대해 설명하려고 합니다.</p><h3>세션 내용</h3><ul><li>AWS 아키텍처를 구현하거나 마이그레이션하는 단계에서 부터 보안을 적용하는 시점과 방법을 결정하는 것부터 배포된 워크로드의 구성 변경에 대한 지속적인 보안 거버넌스를 유지하는 것은 어려운 과제입니다. 또한, 다양한 구성 요소에 대한 통합적인 보안 거버넌스를 적용하는 부분도 고려해야 합니다.</li><li>이러한 어려움을 극복하기 위해 <strong>AWS Well-Architected Migration Lens</strong>와 <strong>Secure Migration Framework</strong>을 사용할 수 있으며, <strong>Migration Security Requirements (MSR)</strong>와 <strong>HashiCorp 솔루션(Terraform)</strong>을 통합하여 보안 거버넌스를 강화하고 종합적인 보안 전략을 마련할 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XuYHmFuf1p3rctxB.png" /></figure><h3>해당 세션의 키워드</h3><p>AWS Well-Architected Migration Lens, Secure Migration Framework, Migration Security Requirements (MSR), HashiCorp 솔루션(Terraform)가 무엇인지?</p><p>그리고 해당 Framework &amp; 솔루션을 사용하여 도대체 무엇을 할 수 있을지 궁금하실텐데요. 해당 키워드들에 대한 내용에 간략히 설명드리겠습니다.</p><p><strong>AWS Well-Architected </strong><a href="https://docs.aws.amazon.com/wellarchitected/latest/migration-lens/migration-lens.html"><strong>Migration Lens</strong></a></p><ul><li>클라우드 마이그레이션 과정에서 잘 정립된 아키텍처 설계를 위한 AWS의 지침을 제공합니다.</li><li>이는 <strong>AWS 마이그레이션의 3단계인</strong> assess, mobilize, migrate and modernize의 세 단계에 걸쳐 운영 우수성, 보안, 신뢰성, 성능 효율성, 비용 최적화, 지속 가능성의 여섯 가지 원칙에 대한 베스트 프랙티스를 결합합니다.</li></ul><p><a href="https://docs.aws.amazon.com/pdfs/prescriptive-guidance/latest/secure-migrations-framework/secure-migrations-framework.pdf"><strong>Secure Migration Framework</strong></a></p><ul><li>클라우드로의 전환을 계획할 때 중점적으로 고려해야 할 보안과 규정 준수에 대한 구체적인 지침을 담고 있으며, 클라우드 마이그레이션 동안에 기업의 보안 거버넌스를 강화하는 방법에 대한 인사이트를 제공합니다.</li><li>이를 통해 기업 또는 조직이 언제 어떤 보안 조치를 취해야 하는지, 구성 변경 시 보안 거버넌스를 유지하는 방법, 그리고 여러 구성요소에 걸쳐 보안 거버넌스를 어떻게 적용해야 하는지에 대한 지침을 제공합니다. 기본적으로, 안전한 마이그레이션을 위한 핵심 프로세스의 로드맵을 설명하고 조직이 AWS 환경으로의 부드러운 전환을 도모할 수 있도록 하고있습니다.</li></ul><p><strong>Migration Security Requirements (MSR)</strong></p><ul><li>MSR은 마이그레이션 및 현대화 과정에서 안전한 클라우드 기반을 구축하기 위해 필요한 69까지 보안 및 규정 준수 확인 사항을 정의해놓은 것을 말합니다</li><li>즉, <strong>Secure Migration에 진단해야할 보안항목을 69가지의 백데이터 정의해놓은 것</strong>으로 보실 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EY98wRCjGuWAaZDg.png" /></figure><p><a href="https://github.com/aws-samples/service-screener-v2"><strong>AWS Service Screener</strong></a></p><ul><li>Service Screener는 AWS 환경에서 자동화된 검사를 실행하고 AWS 및 커뮤니티 모범 사례를 기반으로 권장 사항을 제공하는 도구입니다.</li><li>IAM, Logging and Monitoring, infrastructure security, data protection, and incident response 5가지 핵심 보안요구사항에 대해서 service screener v2를 통해 확인할 수 있습니다.</li><li>Screener를 통해 AWS에서 권장 사항을 사용하여 서비스 수준에서 보안, 안정성, 운영 우수성, 성능 효율성 및 비용 최적화를 개선할 수 있습니다.</li><li>Service Screener는 무료로 사용이 가능하며, MSR 프레임워크 기반으로 검사를 진행하여 MSR 리포트 출력 가능이 가능합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FATJz-KkLqWDk6NV.png" /></figure><p><a href="https://www.terraform.io/"><strong>HashiCorp Terraform</strong></a></p><ul><li>HashiCorp Terraform은 IaC 도구 중 하나로, 다양한 클라우드 서비스 및 온프레미스 인프라를 코드로 정의하고 관리할 수 있습니다. Terraform은 간결하고 직관적인 구문을 사용하여 인프라스트럭처를 관리하며, 다양한 프로바이더를 통해 AWS, Azure, Google Cloud Platform, VMware 등의 다양한 환경을 지원합니다.</li><li>HashiCorp에서는 Terraform의 운영 환경을 웹 콘솔로 제공하고, API 기능을 지원해주는 서비스인 HCP Terraform(SaaS)와 Terraform Enterprise(self-hosted) 모델을 제공하고있습니다.</li><li>Terraform Enterprise는 기업 수준의 Terraform 관리 플랫폼으로, 보안, 규정 준수, 협업 기능을 강화한 기능을 제공합니다. 테라폼 엔터프라이즈는 팀원 간의 협업을 촉진하고, 인프라스트럭처 변경 사항의 트래킹 및 자동화를 제공, PaC(Policy as code)를 통한 정책 및 거버넌스 확립, 상태 및 비용 최적화 등을 지원하고 있습니다.</li></ul><h3>Service Screener</h3><ul><li>이번 세션의 Hands-On 내용은 아니었지만 Service Screener에 대해 테스트한 내용입니다.</li><li>테스트를 위해 AWS 환경에 간단한 EC2와 EC2에 연결할 Security Group을 미리 생성해 놓았으며, Security Group은 inbound를 전부 열어 놓았습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PdCjR0Mxg0uF1TfG.png" /></figure><ul><li>AWS에 해당 Security Group은 inbound Rule이 전부 열려 있다면 해당 시스템 악의적인 공격 뿐만 아니라 무작위 포트 스캔과 같은 자동화된 공격에서도 취약점을 노출 시킬 수 있으므로 보안적으로 굉장히 취약합니다.</li><li>Service Screener로 EC2 서비스에 대해서만 검사를 진행하였고 EC2의 분석 결과 중 Security Group에 대해서는 다음과 같이 확인해 볼 수 있습니다.</li></ul><pre>screener --regions ap-northeast-2 --services ec2</pre><ul><li>위와 같은 명령어를 실행하면 ~/service-screener-v2/output.zip 파일로 생성됩니다. 해당 zip파일을 다운로드 받고 압축을 풀면 index.html 파일을 통해 다음과 같이 안전한 클라우드 기반을 구축하기 위해 필요한 69까지 보안 및 규정 준수 확인 사항에 위반되는 내용들을 확인 가능합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wz0ozXQksBtRAXiE.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6vcY7_8vdfVkGZ9R.png" /></figure><h3>Hands-On을 위해 준비내용</h3><ul><li>세션의 내용을 보면 요점은 마이그레이션 및 현대화 단계에서나 클라우드 운영 단계에서 어떻게 지속적으로 보안 요구사항(MSR)을 만족하는 보안 수준을 유지할지입니다.</li><li>HashiCorp Terraform을 사용하게 되면 다음과 같이 MSR기준으로 마이그레이션하고 보안, 거버넌스 관리의 표준을 운영 단계에서 각각 보안 수준을 유지할 수 있습니다.</li><li>Terraform FDO는 23년 9월에 새롭게 GA 된 기능으로 Docker 또는 Kubernetes 환경에서 Terraform enterprise를 빠른 시간에 설치 및 시작할 수 있는 배포 옵션입니다.</li><li>저희 DevOps Product 팀은 작년 10월 27일 DNB 고객사분들을 대상으로 Devops Quest 해결 방식 이벤트인 ‘MEGATHON(메가톤)’을 진행을 EKS에 올리는 Terraform FDO 설치 방식을 경험해봤기 때문에 세션의 Hand-On 환경은 SaaS(HCP Terraform)와 Self Hosted(Terraform Enterprise) 중에서, Kubernetes 환경에 배포하는 FDO 설치 방식으로 Terraform Enterprise를 활용하기로 결정하였습니다.</li><li>Hands-On을 위해 준비한 내용은 다음과 같습니다.</li></ul><h4><strong>1) Terraform 으로 인프라 및 EKS Add-on 배포</strong></h4><ul><li>AWS인프라(EKS, AWS RDS, AWS S3, AWS ElastiCache…)</li><li>EKS add-on (EBS CSI Driver, LoadBalancer Controller, Externer DNS)</li></ul><h4><strong>2) Helm Chart 배포</strong></h4><ul><li>Terraform Enterprise</li><li>Keycloak</li><li>prometheus-stack</li></ul><h4><strong>3) Hand-On 시나리오 (</strong><a href="https://catalog.us-east-1.prod.workshops.aws/workshops/6439509a-d74c-4ade-b987-da059edef101/en-US/0-getting-started"><strong>aws workshop studio</strong></a><strong>)</strong></h4><p>3–1) <strong>컴퓨트 리소스의 attack surface 최소화하기 위해 보안팀과 조직의 컴플라이언스에 부합하는 이미지를 사용해서 성공적으로 EC2 Instance 를 프로비져닝</strong></p><h4>3–2) <strong>코드화된 정책인 Sentinel 적용하여 보안표준 적용</strong></h4><ul><li>A) security groups의 최소 권한 액세스를 Sentinel policy에 정의하여 cidr이 지나치게 관대하게 오픈되는 경우를 사전에 방지</li><li>B) ACL이 활성화되는 버킷을 사전에 방지하고 버킷에 공개적으로 액세스할 수 없도록 제한된 S3 버킷을 프로비져닝</li></ul><h4>3–3) <strong>Drift Detction 기능을 활용하여 인프라 상태 변경 확인 및 복구 자동화 구현</strong></h4><ul><li>A) 사용자가 임의로 Security Group의 설정을 변경하였을 때 이를 감지하고 복구</li><li>B) CloudTrail의 로그 파일 무결성 검증 설정을 고의적으로 변경했을 때 Drift detection을 통해 이를 감지하고 복구</li></ul><h4>3–4) <strong>Continuous Validation 기능을 활용하여 프로비저닝 된 워크로드 상태 확인</strong></h4><ul><li>Web Server 비정상 동작 시 Terraform continuous validation 기능을 통한 탐지</li></ul><h4><strong>4) Load Test &amp; 모니터링 테스트</strong></h4><ul><li>노드 할당 가능 용량과 요청 request 리소스를 표시 해주는 EKS Node Viewer 설치</li><li>200 Workspace 부하 테스트 — Terraform apply Test</li><li>Grafana — TFE 용 대시보드 구축 및 모니터링</li></ul><h3>1. Terraform으로 인프라 및 EKS Add-on 배포</h3><h4>1–1) AWS인프라(EKS, AWS RDS, AWS S3, AWS ElastiCache…) 구축</h4><ul><li>Terraform Enterprise 환경은 해당 세션을 진행하신 AWS 직원분의 AWS 계정을 사용하였는데 직접 AWS UI Console에는 접속할 수 있는 권한을 받을 수 없었기에 Terraform Code를 통해 Terraform Enterprise환경 구축을 진행하였고 구축한 아키텍처는 다음과 같습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TeAHd3efD9_6M9KB.png" /></figure><ul><li>저희 DevOps Product 팀은 위와 같은 아키텍처로 Terraform Enterprise를 구현하기 위해 각 리소스들을 모듈화하여 관리 및 구축하고있습니다.</li></ul><pre>module &quot;vpc&quot; {<br>  source       = &quot;../module/vpc&quot;<br>  vpc_cidr     = local.vpc_cidr<br>  company_name = local.company_name<br>  server_env   = local.server_env<br>}<br><br>module &quot;subnets&quot; {<br>  source             = &quot;../module/subnets&quot;<br>  vpc_secondary_cidr = module.vpc.vpc_secondary_cidr<br>  vpc_id             = module.vpc.vpc_id<br><br>  company_name = local.company_name<br>  server_env   = local.server_env<br>  elb_cidr     = local.elb_cidr<br>  dmz_cidr     = local.dmz_cidr<br>  ap_cidr      = local.ap_cidr<br>  db_cidr      = local.db_cidr<br>  pod_cidr     = local.pod_cidr<br>  azs          = local.azs<br>}<br><br>module &quot;routingTable&quot; {<br>  source        = &quot;../module/routeTable&quot;<br>  vpc_id        = module.vpc.vpc_id<br>  igw           = module.vpc.igw<br>  dmz_subnet_id = module.subnets.dmz_subnet_id<br>  elb_subnet_id = module.subnets.elb_subnet_id<br>  ap_subnet_id  = module.subnets.ap_subnet_id<br>  pod_subnet_id = module.subnets.pod_subnet_id<br>  db_subnet_id  = module.subnets.db_subnet_id<br>  natgw_az1     = module.gateway.natgw_az1<br>  company_name  = local.company_name<br>  server_env    = local.server_env<br>}<br><br>module &quot;gateway&quot; {<br>  source        = &quot;../module/gw&quot;<br>  igw           = module.vpc.igw<br>  dmz_subnet_id = module.subnets.dmz_subnet_id<br>  company_name  = local.company_name<br>  server_env    = local.server_env<br>}<br><br>module &quot;eks&quot; {<br>  source             = &quot;../module/eks&quot;<br>  ap_subnet_id       = module.subnets.ap_subnet_id<br>  dmz_subnet_id      = module.subnets.dmz_subnet_id<br>  dmz_subnet         = module.subnets.dmz_subnet<br>  vpc_id             = module.vpc.vpc_id<br>  node_instance_type = var.node_instance_type<br>  company_name       = local.company_name<br>  server_env         = local.server_env<br>}<br><br>module &quot;elasticache&quot; {<br>  source                          = &quot;../module/elasticache&quot;<br>  preferred_cache_cluster_azs     = [var.azs.0, var.azs.1]<br>  project_name                    = &quot;dpt&quot;<br>  env                             = &quot;common&quot;<br>  elasticache_redis_name          = var.elasticache_redis_name<br>  elasticache_redis_engine        = var.elasticache_redis_engine<br>  redis_description               = &quot;External Redis cluster for TFE Active/Active&quot;<br>  create_subnet_group             = var.create_subnet_group<br>  redis_subnet_ids                = [module.subnets.ap_subnet_id[0], module.subnets.ap_subnet_id[1], module.subnets.ap_subnet_id[2]]<br>  redis_engine_version            = var.redis_engine_version<br>  redis_port                      = var.redis_port<br>  redis_parameter_group_name      = var.redis_parameter_group_name<br>  redis_node_type                 = var.redis_node_type<br>  redis_enable_multi_az           = var.redis_enable_multi_az<br>  redis_enable_encryption_at_rest = var.redis_enable_encryption_at_rest<br>  redis_kms_key_arn               = module.s3.kms[0].arn<br>  redis_enable_transit_encryption = var.redis_enable_transit_encryption<br>  redis_password                  = var.redis_password<br>  vpc_id                          = module.vpc.vpc_id<br>  sg_csv                          = &quot;./sg_rule/elasticache.csv&quot;<br>}<br><br>module &quot;rds-postgresql&quot; {<br>  source                    = &quot;../module/rds&quot;<br>  create                    = var.rds_create<br>  skip_final_snapshot       = var.skip_final_snapshot<br>  identifier                = var.identifier<br>  db_size                   = var.db_size<br>  db_type                   = var.db_type<br>  engine                    = var.engine<br>  engine_version            = var.engine_version<br>  instance_class            = var.instance_class<br>  db_name                   = var.db_name<br>  username                  = var.username<br>  password                  = var.password<br>  port                      = var.port<br>  network_type              = var.network_type<br>  availability_zone         = [var.azs.0, var.azs.1]<br>  final_snapshot_identifier = var.final_snapshot_identifier<br>  timezone                  = var.timezone<br>  param_group               = var.param_group<br>  cidr_block                = var.cidr_block<br>  db_subnet_id              = module.subnets.ap_subnet_id<br>  project_name              = var.project_name<br>  env                       = var.env<br>  vpc_id                    = module.vpc.vpc_id<br>}<br><br>module &quot;s3&quot; {<br>  source                               = &quot;../module/s3&quot;<br>  env                                  = var.s3_env<br>  project_name                         = var.s3_project_name<br>  s3_name                              = var.s3_name<br>  s3_acl                               = var.s3_acl<br>  s3_ownership                         = var.s3_ownership<br>  s3_block_public_acls                 = var.s3_block_public_acls<br>  s3_block_public_policy               = var.s3_block_public_policy<br>  s3_ignore_public_acls                = var.s3_ignore_public_acls<br>  s3_restrict_public_buckets           = var.s3_restrict_public_buckets<br>  s3_versioning                        = var.s3_versioning<br>  create_kms_for_s3                    = var.create_kms_for_s3<br>  kms_alias                            = var.kms_alias<br>  kms_key_arn                          = var.kms_key_arn<br>  s3_sse_algorithm                     = var.s3_sse_algorithm<br>  accountID                            = local.accountID<br>  principals_identifiers_for_s3_policy = [&quot;${module.eks.worker_ng_role_arn}&quot;]<br>}</pre><h4>1–2) EKS add-on (EBS CSI Driver, LoadBalancer Controller, Externer DNS)</h4><ul><li><strong>EBS CSI Driver</strong>는 Kubernetes 클러스터에서 Amazon Elastic Block Store (EBS) 볼륨을 사용할 수 있도록 하는 Kubernetes CSI(컨테이너 스토리지 인터페이스) 드라이버입니다. 이 드라이버를 사용하면 Kubernetes 클러스터 내에서 EBS 볼륨을 동적으로 프로비저닝하고 관리할 수 있습니다.</li><li>Terraform Enterprise의 경우 RDS, S3등의 External Service를 사용했기 때문에 따로 EBS CSI Driver가 필요하진 않았지만, Keycloak, prometheus-stack을 위해 EBS CSI Driver를 설치하였습니다.</li></ul><pre>##### ebs csi driver ######<br>###########################<br>resource &quot;kubernetes_service_account&quot; &quot;ebs_csi_service_account&quot; {<br>  metadata {<br>    name      = &quot;ebs-csi-controller-sa&quot;<br>    namespace = &quot;kube-system&quot;<br>    labels = {<br>      &quot;app.kubernetes.io/name&quot; = &quot;aws-ebs-csi-driver&quot;<br>    }<br>    annotations = {<br>      &quot;eks.amazonaws.com/role-arn&quot; = module.eks.ebs_csi_driver_role_arn<br>    }<br>  }<br>  depends_on = [module.eks]<br>}<br><br>resource &quot;helm_release&quot; &quot;aws_ebs_csi_driver&quot; {<br>  name = &quot;aws-ebs-csi-driver&quot;<br><br>  repository = &quot;https://kubernetes-sigs.github.io/aws-ebs-csi-driver&quot;<br>  chart      = &quot;aws-ebs-csi-driver&quot;<br>  namespace  = &quot;kube-system&quot;<br>  version    = &quot;2.24.0&quot;<br><br>  set {<br>    name  = &quot;controller.serviceAccount.create&quot;<br>    value = &quot;false&quot;<br>  }<br>  set {<br>    name  = &quot;controller.serviceAccount.name&quot;<br>    value = &quot;ebs-csi-controller-sa&quot;<br>  }<br><br>  values = [<br>    templatefile(&quot;${path.module}/custom-yaml/ebs_csi_values.yaml&quot;,<br>      {<br>        ebs-csi-controller-role-arn = module.eks.ebs_csi_driver_role_arn,<br>      }<br>    )<br>  ]<br><br>  depends_on = [<br>    kubernetes_service_account.ebs_csi_service_account,<br>    module.eks<br>  ]<br>}</pre><ul><li><strong>LoadBalancer Controller</strong>는 Kubernetes 클러스터에서 외부 트래픽을 내부 서비스로 라우팅하기 위해 클라우드 프로바이더의 로드 밸런서를 관리하는 Kubernetes 컨트롤러입니다. AWS에서는 Amazon ELB(Application Load Balancer, Network Load Balancer, Classic Load Balancer)를 관리하는 데 사용됩니다.</li></ul><pre>##### LoadBalancer Controller ######<br>####################################<br>resource &quot;helm_release&quot; &quot;helm_AWSLoadBalancerController&quot; {<br>  name = &quot;aws-load-balancer-controller&quot;<br><br>  repository = &quot;https://aws.github.io/eks-charts&quot;<br>  chart      = &quot;aws-load-balancer-controller&quot;<br>  version    = &quot;1.6.2&quot; # https://github.com/aws/eks-charts/tree/gh-pages<br><br>  namespace = &quot;kube-system&quot;<br><br>  set {<br>    name  = &quot;image.repository&quot;<br>    value = &quot;602401143452.dkr.ecr.us-east-1.amazonaws.com/amazon/aws-load-balancer-controller&quot;<br>  }<br><br>  set {<br>    name  = &quot;serviceAccount.create&quot;<br>    value = &quot;true&quot;<br>  }<br><br>  set {<br>    name  = &quot;serviceAccount.name&quot;<br>    value = &quot;aws-load-balancer-controller&quot;<br>  }<br><br>  set {<br>    name  = &quot;serviceAccount.annotations.eks\\.amazonaws\\.com/role-arn&quot;<br>    value = module.eks.lb_controller_role_arn<br>  }<br><br>  set {<br>    name  = &quot;vpcId&quot;<br>    value = module.vpc.vpc_id<br>  }<br><br>  set {<br>    name  = &quot;region&quot;<br>    value = &quot;ap-northeast-2&quot;<br>  }<br><br>  set {<br>    name  = &quot;clusterName&quot;<br>    value = module.eks.eks_name<br>  }<br><br>  depends_on = [module.eks]<br>}</pre><ul><li><strong>External DNS</strong>는 Kubernetes 클러스터에서 서비스 및 인그레스 리소스와 외부 도메인 간의 매핑을 자동으로 관리하는 도구입니다. Kubernetes 리소스의 변경 사항에 따라 외부 DNS 레코드를 자동으로 업데이트하여 DNS 이름을 동적으로 할당합니다.</li></ul><pre>########## External DNS ###########<br>###################################<br>resource &quot;kubernetes_service_account&quot; &quot;external_dns_service_account&quot; {<br>  metadata {<br>    name      = &quot;external-dns&quot;<br>    namespace = &quot;kube-system&quot;<br>    labels = {<br>      &quot;app.kubernetes.io/name&quot; = &quot;external-dns-controller&quot;<br>    }<br>    annotations = {<br>      &quot;eks.amazonaws.com/role-arn&quot; = module.eks.external_dns_role_arn<br>    }<br>  }<br>  depends_on = [module.eks]<br>}<br><br>resource &quot;helm_release&quot; &quot;external_dns&quot; {<br>  name       = &quot;external-dns&quot;<br>  repository = &quot;https://kubernetes-sigs.github.io/external-dns&quot;<br>  chart      = &quot;external-dns&quot;<br>  namespace  = &quot;kube-system&quot;<br>  <br>  set {<br>    name  = &quot;serviceAccount.create&quot;<br>    value = &quot;false&quot;<br>  }<br><br>  set {<br>    name  = &quot;serviceAccount.name&quot;<br>    value = &quot;external-dns&quot;<br>  }<br><br>  values = [<br>    templatefile(&quot;${path.module}/custom-yaml/external_dns_values.yaml&quot;,<br>      {<br>        txtOwnerId = &quot;{hostzone id}&quot;,<br>        domainFilters = &quot;secureaws.net&quot;,<br>      }<br>    )<br>  ]<br><br>  depends_on = [<br>    kubernetes_service_account.external_dns_service_account,<br>    module.eks<br>  ]<br>}</pre><ul><li>Terraform Enterprise를 위해 External Service로 OBJECT_STORAGE_S3_BUCKET을 사용하였으며 S3에는 Terraform 이 관리하는 State file, Module 등의 저장소 역할을 하게 됩니다.</li><li>AWS Key Management Service(KMS)를 사용하여 저장 데이터를 암호화하도록 하여 S3에 저장된 데이터가 KMS에서 관리하는 키를 사용하여 암호화되어 무단 액세스로부터 저장된 데이터를 보호함으로써 보안 계층이 추가하였습니다.</li><li>EKS에 배포된 Terraform Enterprise 서버가 S3에 데이터를 저장하고 읽어가기 위해서는 ‘<strong>kms:GenerateDataKey’</strong>, ‘<strong>kms:Decrypt’</strong>, ‘<strong>s3:*’</strong> 와 같은 권한이 필요하기에 노드 그룹의 Role해 해당 권한을 추가해주었습니다.</li></ul><pre># Terraform Enterprise의 KMS, S3에 대한 Policy 추가<br>data &quot;aws_iam_policy_document&quot; &quot;tf_eks_fdo_for_policy&quot; {<br>  statement {<br>    effect    = &quot;Allow&quot;<br>    actions   = [&quot;kms:GenerateDataKey&quot;, &quot;kms:Decrypt&quot;, &quot;s3:*&quot;]<br>    resources = [&quot;arn:aws:kms:*:${var.accountID}:key/*&quot;, &quot;arn:aws:s3:::*&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;tf_eks_fdo_for_policy&quot; {<br>  name        = &quot;tf_eks_fdo_for_policy&quot;<br>  description = &quot;tf_eks_fdo_for_policy&quot;<br>  policy      = data.aws_iam_policy_document.tf_eks_fdo_for_policy.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eksng_s3_kmsrole&quot; {<br>  role       = module.eks.worker_ng_role_name<br>  policy_arn = aws_iam_policy.tf_eks_fdo_for_policy.arn<br>}</pre><ul><li>Terraform Enterprise에서는 Cost Estimation라는 기능이 있어서 예상 비용이 Plan과 Apply 사이의 추가 실행 단계로 실행 UI에 표시하여 확인이 가능합니다.</li><li>EKS에 배포된 Terraform Enterprise에서 해당 기능을 활성화하고 사용하기 위해서는 pricing:* 권한이 필요하기에 노드그룹의 Role에 해당 권한을 추가해주었습니다.</li></ul><pre># Terraform Enterprise의 Cost Estimation을 위한 Policy 추가<br>data &quot;aws_iam_policy_document&quot; &quot;tf_eks_fdo_for_cost_estimation_policy&quot; {<br>  statement {<br>    effect    = &quot;Allow&quot;<br>    actions   = [&quot;pricing:*&quot;]<br>    resources = [&quot;*&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;tf_eks_fdo_for_cost_estimation_policy&quot; {<br>  name        = &quot;tf_eks_fdo_for_cost_estimation_policy&quot;<br>  description = &quot;tf_eks_fdo_for_cost_estimation_policy&quot;<br>  policy      = data.aws_iam_policy_document.tf_eks_fdo_for_cost_estimation_policy.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eksng_pricing_role&quot; {<br>  role       = module.eks.worker_ng_role_name<br>  policy_arn = aws_iam_policy.tf_eks_fdo_for_cost_estimation_policy.arn<br>}</pre><h3>2. Helm Chart 로 애플리케이션 배포</h3><h4>2–1) Terraform Enterpirse</h4><ul><li>Terraform Enterprise의 이미지를 다운로드 받기 위해서는 License key가 필요합니다.</li><li>해당 이미지를 다운로드 받기 위해 다음과 같이 Image pull을 위한 Secret을 생성한 후 Helm install을 통해 Enterprise를 설치할 수 있습니다.</li></ul><pre># namespace 생성<br>kubectl create ns tfe<br><br># image pull을 위한 secret 생성<br>kubectl create secret docker-registry terraform-enterprise \<br>--docker-server=images.releases.hashicorp.com \<br>--docker-username=terraform \<br>--docker-password=$(cat license.txt) \<br>-n tfe<br><br># Add the Hashicorp helm registry<br>helm repo add hashicorp https://helm.releases.hashicorp.com<br><br># TFE helm install<br>helm install terraform-enterprise \<br>-f ./override-tfe.yaml hashicorp/terraform-enterprise \<br>-n tfe</pre><ul><li>기본 설치가 아닌 저희는 Terraform Enterprise 를 RDS, ElastiCache, S3, KMS등과의 연동이 필요하므로 기본 value yaml 파일을 커스텀하여 설치를 진행하였습니다.</li></ul><pre>tfe:<br>  metrics:<br>    enable: true<br>    httpPort: 9090<br>    httpsPort: 9091<br>  privateHttpPort: 8080<br>  privateHttpsPort: 8443<br>  <br>env:<br>  secrets:<br>    TFE_DATABASE_PASSWORD: {}<br>    TFE_ENCRYPTION_PASSWORD: {}<br>    TFE_LICENSE: {}<br>    TFE_OBJECT_STORAGE_S3_SERVER_SIDE_ENCRYPTION_KMS_KEY_ID: {}<br>    TFE_REDIS_PASSWORD: {}<br>  variables:<br>    TFE_CAPACITY_CONCURRENCY: 100<br>    TFE_DATABASE_HOST: {}<br>    TFE_DATABASE_NAME: {}<br>    TFE_DATABASE_PARAMETERS: sslmode=require<br>    TFE_DATABASE_USER: tfe<br>    TFE_HOSTNAME: hashicorp.secureaws.net<br>    TFE_IACT_SUBNETS: 0.0.0.0/0<br>    TFE_OBJECT_STORAGE_S3_BUCKET: {}<br>    TFE_OBJECT_STORAGE_S3_ENDPOINT: https://s3.ap-northeast-2.amazonaws.com<br>    TFE_OBJECT_STORAGE_S3_REGION: ap-northeast-2<br>    TFE_OBJECT_STORAGE_S3_SERVER_SIDE_ENCRYPTION: aws:kms<br>    TFE_OBJECT_STORAGE_S3_USE_INSTANCE_PROFILE: &quot;true&quot;<br>    TFE_OBJECT_STORAGE_TYPE: s3<br>    TFE_REDIS_HOST: {}<br>    TFE_REDIS_USE_AUTH: &quot;true&quot;<br>    TFE_REDIS_USE_TLS: &quot;true&quot;<br>image:<br>  name: hashicorp/terraform-enterprise<br>  repository: images.releases.hashicorp.com<br>  tag: v202402-1<br>replicaCount: 5<br>service:<br>  type: ClusterIP<br>tls:<br>  caCertData: {}<br>  certData: {}<br>  keyData: {}</pre><ul><li>Terraform Enterprise의 외부 접속할 수 있는 Endpoint로 LB가 필요하기에 다음과 같이 Ingress를 통해 ALB를 생성하였습니다.</li></ul><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  namespace: tfe<br>  name: hashicorp-tfe<br>  annotations:<br>    alb.ingress.kubernetes.io/listen-ports: &#39;[{&quot;HTTPS&quot;: 443}]&#39;<br>    alb.ingress.kubernetes.io/scheme: internet-facing <br>    alb.ingress.kubernetes.io/subnets: {}<br>    alb.ingress.kubernetes.io/target-type: ip<br>    alb.ingress.kubernetes.io/backend-protocol: &#39;HTTPS&#39;<br>    alb.ingress.kubernetes.io/group.name: hashicorp<br>    alb.ingress.kubernetes.io/group.order: &#39;1&#39;<br>    alb.ingress.kubernetes.io/certificate-arn: {}<br>    external-dns.alpha.kubernetes.io/hostname: hashicorp.secureaws.net<br>spec:<br>  ingressClassName: alb<br>  rules:<br>    - host: hashicorp.secureaws.net<br>      http:<br>        paths:<br>          - path: &quot;/&quot;<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: terraform-enterprise <br>                port:<br>                  number: 443</pre><h4>2–2) Keycloak</h4><ul><li>Keycloak은 ID 및 액세스 관리 솔루션을 제공하는 오픈소스로 다양한 인증 및 권한 부여 기능을 제공하여 사용자의 로그인 및 액세스를 중앙 집중식으로 관리할 수 있습니다.</li><li>저희는 Keycloak을 Terraform Enterpise와 SAML연동을 하여 사용자들이 발급 받은 ID를 통해 쉽게 Terraform Enterprise에 접속할 수 있도록 하기 위해 사용하였습니다.</li></ul><pre># Add the bitnami helm registry<br>helm repo add bitnami https://charts.bitnami.com/bitnami<br><br>helm pull bitnami/keycloak --version 20.0.1 --untar<br><br># Keycloak helm install<br>helm upgrade --install keycloak -f keycloak-values.yaml .</pre><ul><li>keyclock은 Terraform Enterprise와 동일한 LB를 사용하고 별도 리스너로 등록이 필요한 대상 그룹마다 Ingress를 생성하되 각 Ingress를 그루핑 할 수 있는 어노테이션을 추가하여 사용하였습니다.</li><li>Keycloak Helm Chart의 postgresql.architecture 옵션은 PostgreSQL 데이터베이스를 설치할 때 사용할 아키텍처를 지정하는 데 사용됩니다. 여기서 standalone 및 replication 두 가지 옵션을 선택할 수 있습니다.</li><li>많은 참가자들이 동시에 Terraform Enterprise의 keyclock saml을 통해 로그인 시 읽기 전용 슬레이브 노드를 사용하여 읽기 부하를 분산시키고 마스터 노드의 부하를 줄일 수 있도록 replication 옵션을 사용하였습니다.</li></ul><pre>auth:<br>  adminPassword: {password}<br>  adminUser: {username}<br>ingress:<br>  annotations:<br>    alb.ingress.kubernetes.io/certificate-arn: {}<br>    alb.ingress.kubernetes.io/group.name: hashicorp<br>    alb.ingress.kubernetes.io/group.order: &quot;2&quot;<br>    alb.ingress.kubernetes.io/listen-ports: &#39;[{&quot;HTTP&quot;: 80}, {&quot;HTTPS&quot;:443}]&#39;<br>    alb.ingress.kubernetes.io/scheme: internet-facing<br>    alb.ingress.kubernetes.io/ssl-redirect: &quot;443&quot;<br>    alb.ingress.kubernetes.io/subnets: {}<br>    alb.ingress.kubernetes.io/target-type: ip<br>    alb.ingress.kubernetes.io/target-group-attributes: stickiness.enabled=true,stickiness.lb_cookie.duration_seconds=60<br>    external-dns.alpha.kubernetes.io/hostname: keycloak.secureaws.net<br>  enabled: true<br>  hostname: keycloak.secureaws.net<br>  ingressClassName: alb<br>  pathType: Prefix<br>postgresql:<br>  architecture: replication<br>  auth:<br>    database: db_keycloak<br>    existingSecret: &quot;&quot;<br>    password: {password}<br>    postgresPassword: &quot;&quot;<br>    username: {username}<br>  enabled: true<br>proxy: edge<br>service:<br>  http:<br>    enabled: true<br>  ports:<br>    http: 80<br>    https: 443<br>  sessionAffinity: ClientIP<br>  sessionAffinityConfig:<br>    clientIP:<br>      timeoutSeconds: 300<br>  externalTrafficPolicy: Local<br>tls:<br>  autoGenerated: false<br>  enabled: false</pre><h3>3. Terraform Enterprise 부하 테스트</h3><ul><li>부하 테스트를 설명하기 전에, 보다 나은 이해를 위해 Terraform Enterprise의 Workspace와 EKS에서의 Terraform Enterprise의 동작 방식에 대해 먼저 설명드리겠습니다.</li><li><strong>Terraform Enterprise의 Workspace란?</strong></li><li>Terraform Enterprise의 Workspace는 Terraform 구성 파일 및 상태를 관리하는 공간입니다. 이는 클라우드 기반의 서비스로서 Terraform 코드를 관리하고 실행하는 데 중요한 역할을 합니다.</li><li>즉, Terraform이 실행되는 독립적인 작업공간이며, 설정된 backend에 workspace에 state를 저장하고 하나의 state는 하나의 workspace로 관리할 수 있습니다.</li><li><strong>Terraform Enterprise의 동작 방식</strong></li><li>EKS와 같은 쿠버네티스 환경에서 Terraform Enterprise를 설치하게 되면 Workspace에서 테라폼이 동작할 때, tfe-agents 네임스페이스에 agent 파드들이 생기게 됩니다.</li><li>이때, 생성되는 agent 파드들이 테라폼을 실행하는 주체입니다. 해당 agent 파드들은 Workspace가 실행될 때 생기며, Apply가 모두 완료되었다면 종료됩니다.</li><li>해당 세션에 참가자 200명을 최대 인원으로 추산하여 그들이 Terraform workspace를 동시에 배포하는 시나리오 코드를 구현하였으며, 저희가 부하테스트 중 확인한 리소스들은 아래와 같이 액셀로 정리하며 진행하였습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LmGHFETd1iMWoDN-.png" /></figure><ul><li>아래 예시 코드는 참가자 200명이 동시에 Terraform workspace를 배포하는 시나리오를 구현한 부하 테스트 코드입니다.</li></ul><pre># ---------------- vcs 연동 ---------------- #<br># ----------------------------------------- #<br>resource &quot;tfe_oauth_client&quot; &quot;vcs_load&quot; {<br>  name             = &quot;github_load&quot;<br>  organization     = data.tfe_organization.org.name<br>  api_url          = &quot;https://api.github.com&quot;<br>  http_url         = &quot;https://github.com&quot;<br>  oauth_token      = var.github_test_api_token<br>  service_provider = &quot;github&quot;<br>}<br><br>variable &quot;github_test_api_token&quot; {<br>  default = &quot;~~~&quot;<br>}<br><br><br># ---------------- varset 생성---------------- #<br># ------------------------------------------- #<br><br>resource &quot;tfe_variable_set&quot; &quot;load_poc_var_set&quot; {<br>  name         = &quot;PoC Varset&quot;<br>  organization = data.tfe_organization.org.name<br>}<br><br>resource &quot;tfe_project_variable_set&quot; &quot;load_proj_var_set&quot; {<br>  variable_set_id = tfe_variable_set.load_poc_var_set.id<br>  project_id      = tfe_project.load_project.id<br>}<br><br>resource &quot;tfe_variable&quot; &quot;load_access_key&quot; {<br>  key             = &quot;AWS_ACCESS_KEY_ID&quot;<br>  value           = &quot;~~~&quot;<br>  category        = &quot;env&quot;<br>  description     = &quot;AWS ACCESS KEY를 입력하세요&quot;<br>  variable_set_id = tfe_variable_set.load_poc_var_set.id<br>}<br><br>resource &quot;tfe_variable&quot; &quot;load_secret_key&quot; {<br>  key             = &quot;AWS_SECRET_ACCESS_KEY&quot;<br>  value           = &quot;~~~&quot;<br>  category        = &quot;env&quot;<br>  description     = &quot;AWS SECRET KEY를 입력하세요&quot;<br>  variable_set_id = tfe_variable_set.load_poc_var_set.id<br>}<br><br><br># ---------------- project 생성---------------- #<br># -------------------------------------------- #<br><br>resource &quot;tfe_project&quot; &quot;load_project&quot; {<br>  name         = &quot;load_test&quot;<br>  organization = data.tfe_organization.org.name<br>}<br><br><br># ---------------- default_execution_mode 설정 ---------------- #<br># ------------------------------------------------------------ #<br><br>resource &quot;tfe_organization_default_settings&quot; &quot;load_org_default&quot; {<br>  organization           = data.tfe_organization.org.name<br>  default_execution_mode = &quot;remote&quot;<br>  # default_agent_pool_id  = tfe_agent_pool.my_agents.id<br>}<br><br><br># ---------------- load test workspace 생성 ---------------- #<br># --------------------------------------------------------- #<br><br>resource &quot;tfe_workspace&quot; &quot;test_workspace&quot; {<br>  count          = 100<br>  name           = &quot;test_workspace_${count.index}&quot;<br>  organization   = data.tfe_organization.org.name<br>  project_id     = tfe_project.load_project.id<br>  vcs_repo {<br>    identifier     = &quot;mzc-dpt/aws-ps-loadtest-ws&quot;<br>    oauth_token_id = tfe_oauth_client.vcs_load.oauth_token_id<br>  }<br>  force_delete        = true<br>  auto_apply          = true<br>  queue_all_runs      = true<br>  trigger_patterns    = [&quot;/*&quot;]<br>  working_directory   = &quot;/&quot;<br>  global_remote_state = true<br>  assessments_enabled = true<br>}<br><br>resource &quot;tfe_workspace&quot; &quot;test_workspace_japan&quot; {<br>  count          = 100<br>  name           = &quot;test_workspace_japan_${count.index}&quot;<br>  organization   = data.tfe_organization.org.name<br>  project_id     = tfe_project.load_project.id<br>  vcs_repo {<br>    identifier     = &quot;mzc-dpt/aws-ps-loadtest-japan-ws&quot;<br>    oauth_token_id = tfe_oauth_client.vcs_load.oauth_token_id<br>  }<br>  force_delete        = true<br>  auto_apply          = true<br>  queue_all_runs      = true<br>  trigger_patterns    = [&quot;/*&quot;]<br>  working_directory   = &quot;/&quot;<br>  global_remote_state = true<br>  assessments_enabled = true<br>}</pre><ul><li>Terraform Enterprise FDO(EKS)에서는 기본적으로 workspace가 Plan, Apply 같은 동작을할 때 tfe-agent 라는 네임스페이스에서 agent 파드가 생성되어 해당 작업을 진행하게 되며, agent 파드는 cpu, memory request를 물고 들어오게 됩니다.</li><li>해당 agent pod는 Memory Request의 기본값이 2048이 되어 있습니다. 해당 값이 너무 높은 것 같아 하시코프 측에 문의를 해본 결과 하시코프 측 Terraform Enterprise 엔지니어의 FDO를 설계 당시 충분한 테스트 후 나온 최적의 세팅값이다 라는 답변을 받았고, 저희는 Memory Request를 수정하는 것이 아닌 워커 노드를 스케일 아웃(Scale out)하여 부하 테스트를 진행하였습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yk5sfwhlSx_niFOM.png" /></figure><h3>4. Hand-on 준비 과정에서 겪은 몇 가지 문제점과 트러블 슈팅</h3><h4>4–1) Terraform Enterprise(TFE)의 Workspace 생성 실패</h4><ul><li>세션의 참가자가 최대 200명으로 추산하여 저희는 한명한 TFE의 Organization을 제공하고, 참가자가 제공 받은 Organization에는 Hand-on 실습이 가능한 6가지 시나리오 Workspace를 세팅해야 했습니다.</li></ul><p>문제</p><ul><li>한명당 6개의 workspace이므로 200명 기준으로 저희는 총 1200개의 workspace를 세팅해놔야했는데 절반 가량의 workspace가 계속 생성되지 않는 문제가 발생했습니다.</li></ul><p>트러블 슈팅</p><ul><li>로그를 분석한 끝에 DB 쪽 Connection이 실패하는 로그를 확인했고, 해당 RDS의 DB max connection이 몇인지 확인을 진행하였습니다.</li></ul><pre>psql --set=sslmode=require -h {rds_url} -U tfe -d tfepg <br>show max_connections;<br>SELECT count(*) FROM pg_stat_activity WHERE datname = &#39;tfepg&#39; AND usename = &#39;tfe&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yEZjWA1fmwgiP9We.png" /></figure><ul><li>현재 DB의 최대 max connection 수를 확인하고 현재 connection이 맺어져있는 수를 비교해본 후 workspace 생성시 DB connection이 맺어지는지를 확인한 결과 workspace가 생성될 때 DB Connection이 맺어지는 것을 확인할 수 있었습니다.</li><li>AWS RDS는 Instance Type에 따라 max connection 수가 다르며, 기본적으로 t3.small 로 테스트 시 180개 가량의 connection pool 을 맺을수 있으며, 200개 workspace를 동시에 돌리기 위해서는 더 큰 db 인스턴스 타입이 필요하다는 것을 확인 후 RDS의 Scale Up을 진행하였습니다.</li></ul><h4>4–2) Terraform을 통한 RDS의 Instance Type 변경 .. 착각</h4><ul><li>RDS의 max connection를 늘리기 위해 Instance Type을 Scale Up하는 Terraform 코드를 적용하여 Apply를 진행했습니다.</li></ul><p>문제</p><ul><li>Apply가 즉시 적용되었다고 생각하여 부하 테스트를 시작했지만, 계속해서 TFE 로그에는 DB Connection 오류가 나타났습니다. AWS 콘솔에 접속할 수 없어 CLI를 통해 현재 RDS 인스턴스 유형을 확인한 결과, 여전히 t3.small 인스턴스인 것을 확인했습니다.</li><li><strong>이러한 문제의 원인</strong>은 Terraform 코드에 Apply immediately 설정이 기본값 false로 설정되어 있었습니다….</li></ul><p>트러블 슈팅</p><ul><li>AWS RDS는 기본적으로 DB 인스턴스를 수정 후 변경 사항을 즉시 적용하려면 “Apply immediately”를 선택하여 적용할 수 있습니다.</li><li>그러나 Terraform 코드로 설정된 Apply immediately 설정이 기본값으로 false로 동작하여 변경 사항이 즉시 적용되지 않았습니다. 이로 인해 apply 동작은 성공으로 표시되었지만 변경 사항이 즉시 적용되지 않았기 때문에 Scale Up이 이루어지지 않았던 것입니다.</li></ul><h4>4–3) Github 연동 문제</h4><ul><li>VCS 기반 Workspace를 생성하려고 할 때 오류 발생 (ORG/REPO_NAME: 422 Unprocessable Entity)</li></ul><pre>&quot;status&quot;: &quot;400&quot;,<br>&quot;title&quot;: &quot;bad request&quot;,<br>&quot;detail&quot;: &quot;Failed to create webhook on repository: Failed to create webhook on repository: ORG/REPO_NAME: 422 Unprocessable Entity&quot;</pre><ul><li>하나의 Repo에서 Path별로 Hand-on 실습 시나리오 코드를 구현해놓았는데 Workspace 생성 시 VCS(Github)을 연동하지 못하는 위와 같은 에러를 확인하였습니다.</li><li>기본적으로 GitHub은 하나의 리포지토리에 웹훅을 20개로 제한하고 있습니다.</li><li>Github setting 설정(https://github.com/ORG_NAME/REPO_NAME/settings/hooks)에서 현재 구성된 웹훅이 20개 미만인지 확인을 진행해보니 20개 모두가 연동되어있었으며, Gitlab 측 문의를 통해 해당 웹훅 개수를 늘릴 수 있지만 시간문제상 repo를 fork하여 여러개의 repo를 연동하여 workspace를 생성하는 것으로 방향을 바꾸게 되었습니다.</li></ul><h3>5. Grafana를 통한 TFE 모니터링</h3><ul><li>ServiceMonitor는 쿠버네티스에서 사용하는 Custom Resource Definition (CRD)로 쿠버네티스 클러스터 내의 서비스들을 자동으로 모니터링하기 위한 설정을 할 수 있습니다. ServiceMonitor 리소스는 Prometheus가 감시할 서비스의 endpoint들을 정의하고, 어떤 방식으로 스크래핑할지, 어떤 라벨을 사용할지 등의 세부 사항을 포함합니다. Prometheus Operator는 이러한 ServiceMonitor 리소스를 감지하고, Prometheus의 설정을 자동으로 업데이트하여 모니터링할 서비스들을 자동으로 발견하고 감시합니다.</li></ul><pre>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  labels:<br>    app: terraform-enterprise<br>  name: terraform-enterprise<br>  namespace: monitoring<br>spec:<br>  endpoints:<br>    - port: metrics<br>      interval: 10s<br>      path: /metrics<br>      params: <br>        format: <br>          - prometheus<br>  namespaceSelector:<br>    matchNames:<br>    - tfe<br>  selector:<br>    matchLabels:<br>      app: terraform-enterprise</pre><ul><li>Terraform Enterprise value yaml 파일에 다음과 같이 metric을 enable을 설정하여 Terraform Enterprise에서 metric 수집을 활성화 합니다.</li></ul><pre>tfe:<br>  metrics:<br>    enable: true<br>    httpPort: 9090<br>    httpsPort: 9091<br>  privateHttpPort: 8080<br>  privateHttpsPort: 8443</pre><ul><li>Terraform Enterprise에서 해당 metrics를 정상적으로 수집이 안되는 문제가 있어서 임의로 Service의 port를 추가해주었습니다.</li></ul><pre>spec: <br>&lt;생략&gt; <br>  ports: <br>  - name: metrics <br>    port: 9090 <br>    protocol: TCP <br>    targetPort: 9090</pre><ul><li>Grafana Dashborad는 다음과 같이 구현하였습니다.</li></ul><pre>sum by(status)(tfe_run_current_count{status=~&quot;planning|applying&quot;})<br><br>sum(tfe_run_current_count{status=~&quot;applied|errored|planned_and_finished&quot;})<br><br>sum(tfe_run_current_count{status=&quot;errored&quot;})<br><br>topk(5, count by(workspace_name, organization_name)(tfe_run_current_count))<br><br>sum by(organization_name)(tfe_run_current_count{status!~&quot;applied|errored|discarded|canceled|planned_and_finished&quot;})<br><br>sum(tfe_run_current_count{status=~&quot;(?:(?:plan|apply)?_)?queued|pending&quot;})<br><br>sum by(status)(tfe_run_current_count{status!~&quot;applied|errored|discarded|canceled|planned_and_finished&quot;})<br><br>rate(sum by(status)(tfe_run_current_count{status=~&quot;applied|planned_and_finished|errored|discarded|canceled&quot;})[30s:]) * 60</pre><ul><li>구성한 Grafana Dashboard를 통해 세션 당일 사용자들이 실행한 결과를 실시간으로 확인할 수 있었습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q3nZNWogRLO4F5wh.png" /></figure><h3>마치며</h3><p>이번 AWS 파트너 서밋 핸즈온 세션은 실제 현장에서의 클라우드 마이그레이션 경험을 제공하며 특히 보안과 거버넌스 관리의 중요성을 강조했고 Hand-on 환경으로 Terraform의 FDO 옵션인 Terraform Enterprise를 통해 클라우드 환경에 빠르고 안정적으로 인프라를 구축하는 데 필수적인 기능들을 실습할 기회를 제공하였습니다.</p><p>이를 통해 보안 및 규정 준수 사항을 충족하는 Terraform Enterprise의 다양한 기능들을 직접 확인하고 실습하고 AWS의 보안 및 규정 준수 기준(MSR)과 함께 안전한 클라우드 환경 구축에 대한 이해를 깊이 있게 다질 수 있었으며, Terraform이 인프라 구성 뿐만 아니라 보안과 규정 준수를 준수하는 데 도움이 될 수 있음을 파트너분들께 소개할 수 있는 기회가 되어 매우 의미 있는 자리였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0M1FOitZ7edRvmag4_p0g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e3YJCY_rsWB98nroKvaTw.jpeg" /></figure><p>Hand-on 시나리오를 자세히 보고 싶은 분들은 다음 페이지를 통해 확인 할 수 있습니다.</p><p><a href="https://catalog.us-east-1.prod.workshops.aws/workshops/6439509a-d74c-4ade-b987-da059edef101/en-US/0-getting-started"><strong>aws workshop studio</strong></a></p><p><strong>세션 당일에만 </strong>AWS 이벤트에서 제공하는 계정을 제공했기 때문에 현재는 자신의 AWS 계정을 사용하셔야 합니다. 😅</p><p>감사합니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5a389a61bd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/aws-partner-summit-seoul-hands-on-%EC%84%B8%EC%85%98-%EC%A7%80%EC%9B%90-%ED%9B%84%EA%B8%B0-well-architected-%EC%97%90-%EA%B8%B0%EB%B0%98%ED%95%98%EC%97%AC-%EC%9B%8C%ED%81%AC%EB%A1%9C%EB%93%9C%EB%A5%BC-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%EB%A7%88%EC%9D%B4%EA%B7%B8%EB%A0%88%EC%9D%B4%EC%85%98%ED%95%98%EA%B3%A0-%ED%98%84%EB%8C%80%ED%99%94%ED%95%98%EA%B8%B0-a5a389a61bd6">Terraform과 AWS Well-Architected Framework를 이용한 마이그레이션과 현대화</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Arctic의 기술적 진보]]></title>
            <link>https://medium.com/cloudvillains/snowflake-arctic%EC%9D%98-%EA%B8%B0%EC%88%A0%EC%A0%81-%EC%A7%84%EB%B3%B4-f241a56f989c?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/f241a56f989c</guid>
            <category><![CDATA[snowflake-arctic]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[스노우플레이크]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 04:08:49 GMT</pubDate>
            <atom:updated>2024-04-25T04:08:49.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q99Rt-U61DEpQC_S.png" /></figure><p>어제 저녁 스노우플레이크는 자신만의 새로운 LLM을 발표했습니다. 많은 기술적 진보가 엿보이는 스노우플레이크의 새로운 LLM에 대해 알아보겠습니다. 이 글은 <a href="https://www.snowflake.com/blog/arctic-open-efficient-foundation-language-models-snowflake/">Snowflake Arctic 발표</a>를 참고하여 작성되었습니다.</p><p>Snowflake AI 연구팀은 비용 효율적으로 훈련된 기업 중심의 대형 언어 모델인 Snowflake Arctic를 오픈소스로 공개했습니다. 큰 2개의 특징은 아래와 같습니다.</p><ul><li>효율적인 지능: Arctic은 SQL 생성, 코딩 및 지침 따르기 벤치마크와 같은 기업 작업에서 뛰어난 성능을 발휘하며, 상당히 높은 컴퓨팅 예산으로 훈련된 오픈 소스 모델들보다도 우수한 성능을 보입니다. Arctic은 기업 니즈에 맞는 고품질 맞춤형 모델을 저렴한 비용으로 만들 수 있는 새로운 기준을 세웠습니다.</li><li>진정한 개방성: Arctic은 Apache 2.0 라이선스를 통해 가중치, 코드, 데이터 레시피 및 연구 통찰력에 대한 제한 없는 액세스를 제공합니다.</li></ul><p>Snowflake Arctic은 오늘 Hugging Face에서 이용 가능하며, 향후 며칠 동안 Snowflake Cortex, Amazon Web Services(AWS), Microsoft Azure, NVIDIA API 카탈로그, Lamini, Perplexity, Replicate 및 Together를 통해서도 제공될 예정입니다.</p><h3>믿을 수 없을 정도로 낮은 훈련비용으로 구현한 기업용 지능</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hwWCrDG186SodlOm.png" /></figure><p>Snowflake는 새로운 지표인 ‘기업 지능(Enterprise Intelligence)’을 소개합니다. 이 지표는 코딩(HumanEval+와 MBPP+), SQL 생성(Spider) 및 지침 따르기(IFEval)의 평균을 내어 계산됩니다. 이 지표를 근거로 훈련 비용을 비교해보면 Arctic은 다른 LLM과 비교하여 현저히 낮은 비용을 높은 인공지능을 확보했습니다. 특히 데이터브릭스와 비교해서 1/8 정도의 비용으로 더 나은 모델을 개발했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RiHO0Rng9MSP-ZMh.png" /></figure><p>Arctic은 고유한 Dense-MoE 하이브리드 아키텍처를 활용하는데, 이는 10B 밀집 트랜스포머 모델과 잔차 128x3.66B MoE MLP를 결합하여 총 480B, 상위 2개의 게이팅을 통해 선택된 17B 활성 매개변수로 구성됩니다. 다시 말해 Arctic은 128개의 세분화된 전문가에 걸쳐 480B 매개변수를 펼치고, 상위 2개의 게이팅을 사용하여 17B의 활성 매개변수를 선택하도록 설계되었습니다. 최근의 전문가 수가 적은 MoE 모델과 비교하면, Arctic은 더 많은 매개변수와 전문가를 활용하여 최상위 수준의 지능을 발휘합니다.</p><p>하지만 Arctic은 약 200만 달러 미만의 훈련 컴퓨팅 비용(3,000 GPU 주 미만)으로 최상위 성능을 달성했는데, 이는 전문가들이 압축되어 있고 아키텍처/시스템 공동 설계 및 기업 중심 데이터 커리큘럼으로 훈련되었기 때문입니다.</p><h3>효율적인 추론</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rUyR6cncwnryeLh9.png" /></figure><p>작은 배치 크기에서 Arctic(활성 매개변수 17B)은 Code-Llama 70B보다 최대 4배, Mixtral 8x22B(활성 매개변수 44B)보다 최대 2.5배 적은 메모리 읽기가 가능합니다. FP8 양자화를 사용하면 Arctic을 단일 GPU 노드에 탑재할 수 있습니다. 아직 완전히 최적화되지는 않았지만, 배치 크기 1에서 Arctic의 처리량은 초당 70개 이상의 토큰으로 효과적인 대화형 서비스가 가능합니다. 배치 크기가 상당히 증가하면 Arctic은 CodeLlama 70B와 Llama 70B보다 4배 적은 컴퓨팅만 필요합니다.</p><h3>진정한 개방성</h3><p>Snowflake의 개방성은 단순히 가중치와 코드의 공개를 넘어섭니다. Snowflake는 사전 훈련, 미세 조정, 모델링, 데이터, 시스템 등에 대한 연구 통찰력을 공유하는 포괄적인 ‘Cookbook’을 공개하여 효율적으로 세계 수준의 MoE 모델을 구축할 수 있도록 돕습니다.</p><p>요약하자면, Arctic은 기업 사용 사례에 맞는 개방적이고 비용 효율적이며 우수한 성능의 언어 모델을 대표하는 중대한 진전입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f241a56f989c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/snowflake-arctic%EC%9D%98-%EA%B8%B0%EC%88%A0%EC%A0%81-%EC%A7%84%EB%B3%B4-f241a56f989c">Snowflake Arctic의 기술적 진보</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[llama3에 대한 Andrej Karpathy의 생각]]></title>
            <link>https://medium.com/cloudvillains/llama3%EC%97%90-%EB%8C%80%ED%95%9C-andrej-karpathy%EC%9D%98-%EC%83%9D%EA%B0%81-b42c87386f45?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/b42c87386f45</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 00:10:16 GMT</pubDate>
            <atom:updated>2024-04-23T00:10:16.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eWJ0wCnF3nh3x9mx.jpeg" /><figcaption>by llama official github</figcaption></figure><p><a href="https://twitter.com/karpathy/status/1781028605709234613">Andrej Karpathy의 트윗</a>를 번역한 글입니다.</p><p>===============================================================</p><p><a href="https://ai.meta.com/blog/meta-llama-3/">llama3</a> 8B와 70B(Base 및 미세조정 버전 모두) 모델을 출시하며, 해당 모델 클래스에서 우수한 성능을 보이고 있습니다(하지만 순위가 발표되면 알게 될 것입니다). 400B 모델은 여전히 학습 중이지만, 이미 GPT-4 수준(예: MMLU 84.8 vs GPT-4 Turbo 86.5)에 근접하고 있습니다.</p><h3>Tokenizer</h3><p>토큰 수가 32K(llama 2)에서 <strong>128K(llama 3)</strong>로 4배 증가했습니다. 더 많은 토큰을 가지면 시퀀스 길이를 더 잘 압축할 수 있어, 15% 더 적은 토큰 수로 더 나은 downstream 성능을 볼 수 있습니다.</p><h3>Architecture</h3><p>Llama 2와 크게 변화가 없습니다. Llama 2에서는 큰 모델만 <strong>Grouped Query Attention(GQA)</strong>을 사용했지만, 이제 8B 모델을 포함한 모든 모델에서 GQA를 사용합니다. 이는 Attention의 KV 캐시 크기를 줄이는 파라미터 공유 기법입니다. 복잡성을 줄이고 최적화하는 좋은 수정안입니다.</p><ul><li>KV 캐시는 토큰 생성 시 계산되는 Key/Value 텐서를 GPU 메모리에 저장한 후 재사용합니다. 이로써 Key/Value 텐서가 재 계산 되는 것을 막아 연산량을 줄입니다.</li></ul><h3>Sequence Length</h3><p>최대 컨텍스트 윈도우 토큰 수가 8192로 증가했습니다. llama 1은 2048이고 llama 2는 4096입니다. 이 증가는 환영할 만하지만 요즘 기준(예: GPT-4 128K)에 비하면 작은 편입니다. <strong>많은 사람이 이 부분에서 더 많은 발전을 기대</strong>했을 것입니다. 추후 미세조정 버전에서 개선될지도 모르겠습니다.</p><h3>Training Data</h3><p>llama 2는 2조 개의 토큰으로 학습했지만, llama 3는 15조 개의 토큰 데이터 셋으로 학습했습니다. 이 데이터에는 품질 관리에 많은 노력을 기울였고, 코드 토큰이 4배, 30개 이상의 비 영어 언어 토큰이 5% 포함되어 있습니다. <strong>5%는 영어 대비 비영어 비중이 낮은 편이어서 대부분 영어 모델</strong>이지만, 비영어가 포함된 것은 바람직합니다.</p><h3>Scaling Laws</h3><p>특히 주목할 만한 점은, 8B 파라미터 모델에 15조 토큰이라는 매우 대규모 데이터 셋으로 학습한 것인데, 이는 일반적이지 않고 새로운 시도이며 환영할 만합니다. <a href="https://paperswithcode.com/method/chinchilla">Chinchilla</a> 기준으로 8B 모델의 ‘컴퓨팅 최적화’ 지점은 2,000억 토큰 정도입니다(해당 크기에서 모델 성능 대비 가성비만 따진다면). 그러나 llama 3는 이 지점을 75배 이상 초과하여 학습했습니다. 이는 이례적이지만, 저는 작고 다루기 쉬우며 추론이 용이한 매우 유능한 모델을 얻게 된 것을 매우 바람직하게 생각합니다. Meta에 따르면 이 지점에서도 모델이 ‘표준적인 의미에서 수렴하지 않았다’고 합니다. 즉, <strong>우리가 사용하는 LLM들은 수렴 지점에 훨씬 미치지 못하고 100~1000배 이상 부족하게 학습되어 있다는 의미</strong>입니다. 실제로 저는 사람들이 이 흐름을 계속 이어나가 더 작은 모델에 대해서도 장기간 훈련하고 공개하기를 정말 바랍니다.</p><h3>Systems</h3><p>llama 3는 400 TFLOPS 처리량으로 16K GPU에서 훈련되었다고 합니다. 세부 사항은 언급되지 않았지만, H100 GPU를 fp16 정밀도로 사용했다고 가정하면, NVIDIA 마케팅 자료에서 1,979 TFLOPS로 명시되어 있습니다. 하지만 우리 모두가 아는 것처럼 작은 별표(*희소성 포함)가 상당한 역할을 하고 있어 실제 TFLOPS는 약 990 정도라고 봐야 합니다. 왜 희소성을 FLOPS로 계산하는지 모르겠습니다. 어쨌든 중요한 건, <strong>400/990에서 약 40% 활용도를 보였다는 것</strong>인데, 이 규모에서 그렇게 나쁘지 않습니다! 이 수준에 이르기 위해서는 <strong>매우 견고한 엔지니어링</strong>이 필요합니다.</p><h3>TLDR</h3><p>매우 환영할 만한 llama 3 모델을 Meta에서 공개했습니다. 기초적인 부분에 충실하고, 견고한 시스템과 데이터 작업에 많은 시간을 할애하여 장기 학습 모델의 한계를 탐구했습니다. 또한 GPT-4 수준의 첫 오픈소스 모델이 될 수 있는 400B 모델이 기대됩니다. 많은 사람들이 더 긴 컨텍스트 길이를 요구할 것 같습니다. 개인적으로도, 교육 및 테스트, 임베디드 애플리케이션 등을 위해 8B보다 훨씬 작은 100M, 1B 규모의 모델도 매우 필요하다고 생각합니다.</p><p>===============================================================</p><p><a href="https://www.linkedin.com/in/andrej-karpathy-9a650716/"><strong>Andrej Karpathy</strong></a>의 트윗을 요약해보겠습니다.</p><ul><li>메타는 8B와 70B llama3 모델(기본 및 미세조정 버전)을 공개했으며, 각 모델 클래스에서 우수한 성능을 보입니다.</li><li>400B 모델도 계속 학습 중이며, 이미 GPT-4 수준에 근접하는 성능을 보이고 있습니다. 토크나이저의 토큰 수가 128K(Llama 3)로 4배 증가했습니다.</li><li>아키텍처는 Llama 2와 크게 변화가 없지만, 모든 모델에서 Grouped Query Attention(GQA) 기법을 적용했습니다.</li><li>최대 컨텍스트 윈도우 길이가 8192로 증가했습니다.</li><li>15조 토큰 데이터 셋으로 훈련했으며, 코드 데이터와 다국어 데이터의 비중이 늘었습니다. 그러나 여전히 영어모델이 라고 보는 것이 합당합니다.</li><li>작은 8B 모델에 대해 15조 토큰으로 16K GPU로 훈련했으며, 엔지니어링 측면에서 매우 안정적인 시스템입니다. 400B 모델이 GPT-4 수준의 첫 번째 오픈소스 모델이 될 것으로 기대됩니다.</li><li>더 작은 100M, 1B 수준의 모델도 필요할 것이라는 의견을 제시했습니다.</li><li>전반적으로 Llama 3는 높은 성능과 견고한 시스템, 대규모 고품질 데이터 셋 기반의 모델로 평가되며, 오픈소스 분야에서 매우 의미 있는 진전입니다.</li></ul><p>Andrej Karpathy는 llama3에 대해서 긍정적인 시각으로 바로 보고 있는 것을 알 수 있으며 많은 기술적 진보가 일어났다고 생각하고 있습니다. 다면 영어 이외의 언어에 대한 제약과 조금 더 작은 모델이 공개되었으면 한다는 의견도 피력하였습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b42c87386f45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/llama3%EC%97%90-%EB%8C%80%ED%95%9C-andrej-karpathy%EC%9D%98-%EC%83%9D%EA%B0%81-b42c87386f45">llama3에 대한 Andrej Karpathy의 생각</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[스노우파크 모델 레지스트리로 모델관리하기]]></title>
            <link>https://medium.com/cloudvillains/%EC%8A%A4%EB%85%B8%EC%9A%B0%ED%8C%8C%ED%81%AC-%EB%AA%A8%EB%8D%B8-%EB%A0%88%EC%A7%80%EC%8A%A4%ED%8A%B8%EB%A6%AC%EB%A1%9C-%EB%AA%A8%EB%8D%B8%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0-70d1ff5883e9?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/70d1ff5883e9</guid>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 04:24:11 GMT</pubDate>
            <atom:updated>2024-04-19T04:24:11.665Z</atom:updated>
            <content:encoded><![CDATA[<p>과거 <a href="https://medium.com/@soonmo.seong/how-to-use-snowpark-ml-model-registry-in-snowflake-09f93312241b">영문으로 작성된 글</a>을 <a href="https://claude.ai/chats">Claude</a>를 활용해서 국문으로 번역한 글입니다. 빠른 이해를 위해 약간 수정하였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*nWN6rtE4Gr9qXsew" /></figure><p>Snowpark ML 모델링 시대가 도래함에 따라, <a href="https://medium.com/cloudvillains/snowpark-native-linear-regression-modeling-d75d0b9535f1">우리는 Snowpark 네이티브 방식으로 선형 회귀 모델을 개발했습니다</a>. 이는 테이블에 대한 ML 모델링이 Snowpark 적용으로 얼마나 쉬운지 보여줍니다. 따라서 우리는 쉽게 모델을 만들 수 있고 여러 버전을 관리해야 하는 상황에 놓이게 되었습니다. Snowpark ML 모델 레지스트리를 통해 편리한 버전 관리와 모델 배포가 가능해졌습니다. 기술적 준비 외에도 Snowpark ML 모델링을 포함한 핵심 ML 프레임워크도 확실히 지원됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*W2XvnNqkFPjgePTF.png" /></figure><p>우리는 다음과 같은 단계를 통해 모델 레지스트리를 ML 워크플로를 구현할 예정입니다.</p><ul><li>세션 생성</li><li>선형 회귀 모델 구축</li><li>모델 평가</li><li>모델 레지스트리에 모델 등록</li><li>등록된 모델을 이용한 추론</li><li>요약</li></ul><h3>세션 생성</h3><p>Snowpark를 활용한 선형 회귀 모델 개발 블로그 글과 같이 Snowpark를 사용하겠습니다. 다음과 같이 세션을 생성해 보겠습니다. getpass.getpass(f&quot;Enter password:&quot;)를 통해 보안 문제로부터 더 잘 보호 받을 수 있습니다.</p><pre>import getpass<br>from snowflake.snowpark.session import Session<br><br>from snowflake.ml.modeling.linear_model import LinearRegression<br>from snowflake.ml.modeling.preprocessing import OneHotEncoder<br>from snowflake.ml.registry import registry<br>from snowflake.ml._internal.utils import identifier<br>import snowflake.snowpark.functions as F<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from snowflake.ml.modeling.metrics import mean_absolute_error<br><br># Session<br>connection_parameters = {<br>    &quot;account&quot;: &quot;xxxxxxxxxxxx&quot;,<br>    &quot;user&quot;: &quot;xxxxxxxxxxxx&quot;,<br>    &quot;role&quot;: &quot;ACCOUNTADMIN&quot;,<br>    &quot;warehouse&quot;: &quot;COMPUTE_WH&quot;,<br>    &quot;database&quot;: &quot;SNOWPARK_ML_MODELING&quot;,<br>    &quot;schema&quot;: &quot;PUBLIC&quot;<br>}<br><br># Establish and configure connection.<br>connection_parameters[&quot;password&quot;] = getpass.getpass(f&quot;Enter password:&quot;)<br>session = Session.builder.configs(connection_parameters).create()</pre><h3>선형 회귀 모델 구축</h3><p>다음 코드는 이전에 사용했던 테이블을 활용하여 선형 회귀 모델을 학습시킵니다.</p><pre># reaing a table <br>df = session.table(&quot;NYC_ZIP_INCOME&quot;)<br><br># feature engineering<br>ohe = OneHotEncoder(input_cols = [&#39;ZIP&#39;], output_cols = [&#39;ZIP_OHE&#39;], drop_input_cols=True)<br>transformed_df = ohe.fit(df).transform(df)<br>input_columns = transformed_df.columns[:-1]<br>label_columns = transformed_df.columns[-1]<br>output_columns = str(&#39;PREDICTED_ANNUAL_INCOME&#39;)<br><br># model fitting<br>regr = LinearRegression(<br>    input_cols = input_columns,<br>    label_cols = label_columns,<br>    output_cols = output_columns<br>)<br>regr.fit(transformed_df)</pre><p>학습된 모델이 확인하기 위해 2025년에 10001 우편번호에 거주하는 사람들의 총 연간 소득을 예측하는지 확인해 보겠습니다.</p><pre># inferencing without model registry<br>def annual_income_predictor(zip_code, year):<br>    <br>    # create snowpark dataframe<br>    input = session.create_dataframe([(str(zip_code), year)], schema = [&#39;ZIP&#39;, &#39;YEAR&#39;])<br>    # one hot encode input<br>    transformed_input = ohe.transform(input)<br>    # predict<br>    prediction = regr.predict(transformed_input)<br><br>    return prediction.select(&#39;PREDICTED_ANNUAL_INCOME&#39;).show()<br><br># result = 3040481376.845398 <br>annual_income_predictor(10001, 2025)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*-YYux_JJ0PJyzq5k.png" /></figure><h3>모델 평가</h3><p>평균 절대 오차(Mean Absolute Error)는 선형 모델을 사용하더라도 xgboost나 랜덤 포레스트 같은 회귀 모델을 평가하는 간단하고 효과적인 지표 중 하나 입니다. 이 코드에서는 mean_absolute_error 함수를 사용하여 모델의 평균 절대 오차를 계산하고 결과를 출력합니다. 평균 절대 오차는 실제값과 예측값의 차이를 절대값으로 계산하여 평균을 낸 것으로, 모델의 정확도를 간단하게 확인할 수 있는 지표입니다.</p><pre>transformed_df = regr.predict(transformed_df)<br>transformed_df.select(F.col(label_columns), F.col(output_columns)).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/0*RCYqxRiVOZAEWX56.png" /></figure><pre>mae = mean_absolute_error(df = transformed_df,<br>                          y_true_col_names = label_columns,<br>                          y_pred_col_names = output_columns)<br>print(f&quot;Mean Absolute Error: {mae}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*Uq1X_LVWMhBgNarK.png" /></figure><h3>모델 레지스트리에 모델 등록</h3><p>Snowpark 모델 레지스트리는 테이블 형태로 구성되어 있어 익숙하고 사용하기 쉽습니다. 또한 필수 인자와 선택 인자가 있어 환경 의존성과 중요한 메모를 저장할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*e4oBZBCsMD_J74QT.png" /></figure><p>학습된 모델과 함께 샘플 데이터를 레지스트리에 등록하면 모델 구축 및 데이터 준비 과정을 더 잘 이해할 수 있습니다. 따라서 샘플 데이터를 등록하는 것으로 시작해보겠습니다. 데이터 프레임을 잘라내는 것 만으로도 충분합니다.</p><pre># Get sample input data to pass into the registry logging function<br>sample_data = transformed_df.select(input_columns).limit(100)</pre><p>다음과 같이 데이터베이스, 스키마, 모델 이름, 모델 버전, 모델 자체를 설정할 수 있습니다.이 코드에서는 다음과 같은 변수들을 설정합니다:</p><ul><li>database_name: 모델을 저장할 데이터베이스 이름</li><li>schema_name: 모델을 저장할 스키마 이름</li><li>model_name: 모델의 이름</li><li>version_name: 모델의 버전</li><li>model: 실제 모델 객체</li><li>sample_input_data : 실제 활용한 데이터의 샘플</li></ul><p>이렇게 설정한 정보를 바탕으로 모델 레지스트리에 모델을 등록할 수 있습니다</p><pre># database and schema<br>db = identifier._get_unescaped_name(session.get_current_database())<br>schema = identifier._get_unescaped_name(session.get_current_schema())<br><br># model name<br>model_name = &quot;ZIPCODE_ANNUAL_INCOME_PREDICTION&quot;<br><br># create a registry and log the model<br>model_registry = registry.Registry(session=session, database_name=db, schema_name=schema)<br><br># log the fitted model<br>model_ver = model_registry.log_model(<br>    model_name=model_name,<br>    version_name=&#39;V0&#39;,<br>    model=regr,<br>    sample_input_data=sample_data<br>)</pre><p>또한 모델 평가 지표와 코멘트를 추가할 수 있습니다. 이 코드에서는 모델 평가 지표와 코멘트를 추가하고, 모델 레지스트리에 모델을 등록합니다. 모델 이름과 버전을 기반으로 레지스트리를 확인하여, 새로운 모델인 경우에만 등록을 진행합니다. 우리가 만든 모델이 제대로 레지스트리에 등록되었는지 확인해 보겠습니다.</p><pre># evaluation metric<br>model_ver.set_metric(metric_name=&quot;mean_abs_err&quot;, value=mae)<br><br># comments<br>model_ver.comment = &quot;This is the first iteration of our ZIPCODE ANNUAL INCOME PREDICTION model.&quot;<br><br># check<br>model_registry.get_model(model_name).show_versions()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d59j00PxRTG3-twx.png" /></figure><p>Snowflake의 모델 레지스트리는 테이블 형태로 구현되어 있습니다. 비록 최근에 GA(Generally Available) 버전이 출시되었지만, Pandas 데이터 프레임과 유사하게 보이기 때문에 친숙해 보입니다.</p><h3>등록된 모델을 이용한 추론</h3><p>모델 레지스트리를 활용하면 일반적인 머신러닝 모델 추론과 코드에서 몇 가지 차이점이 있습니다. 그러나 어렵지는 않습니다. get_model과 run 함수를 사용하면 모델 추론을 보다 쉽게 수행할 수 있습니다.</p><pre>zip_code = 10001<br>year = 2025<br><br># create snowpark dataframe<br>input = session.create_dataframe([(str(zip_code), year)], schema = [&#39;ZIP&#39;, &#39;YEAR&#39;])<br><br># one hot encode input<br>test_df = ohe.transform(input)<br><br># inference with model registry<br>model_ver = model_registry.get_model(model_name).version(&#39;v0&#39;)<br>result = model_ver.run(test_df, function_name=&quot;predict&quot;)<br>result.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2uEaKD5CYeBkplud.png" /></figure><p>더 이상 필요하지 않은 모델이 있다면 모델 레지스트리를 정리할 수 있습니다. 모델 레지스트리를 정리하면 불필요한 모델 정보를 관리하지 않아도 되므로, 전체 시스템의 효율성을 높일 수 있습니다. 더 이상 사용되지 않는 모델은 정기적으로 삭제하는 것이 좋습니다.</p><pre># clean up<br>model_registry.delete_model(model_name)<br># see it is empty<br>model_registry.show_models()</pre><h3>요약</h3><p>이번 블로그에서는 Snowflake의 Snowpark Model Registry에 대해 살펴보았습니다. 이 새로운 기능은 모델 배포와 추론 과정에 일부 차이점을 만들어냅니다. 그러나 기본적인 Python 프로그래밍 기술만 있다면 구현하는 것은 그리 어렵지 않습니다.</p><p>주요 내용은 다음과 같습니다:</p><ul><li>Snowpark를 활용하여 선형 회귀 모델을 구축하고 평가했습니다.</li><li>모델 메타데이터와 샘플 데이터를 Snowpark 모델 레지스트리에 등록했습니다.</li><li>데이터베이스, 스키마, 모델 이름 및 버전 등을 설정하여 모델을 관리했습니다.</li><li>모델 레지스트리에서 모델을 로드하고 추론을 수행했습니다.</li><li>더 이상 필요하지 않은 모델은 레지스트리에서 삭제했습니다.</li></ul><p>Snowpark 모델 레지스트리는 모델 관리와 배포 과정을 편리하게 만들어줍니다. 테이블 형태의 인터페이스를 제공하여 개발자들에게 친숙한 환경을 제공하는 것이 특징입니다. 이를 활용하면 ML 모델 운영을 보다 효율적으로 수행할 수 있습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d1ff5883e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/%EC%8A%A4%EB%85%B8%EC%9A%B0%ED%8C%8C%ED%81%AC-%EB%AA%A8%EB%8D%B8-%EB%A0%88%EC%A7%80%EC%8A%A4%ED%8A%B8%EB%A6%AC%EB%A1%9C-%EB%AA%A8%EB%8D%B8%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0-70d1ff5883e9">스노우파크 모델 레지스트리로 모델관리하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Parallelism in Machine Learning Training]]></title>
            <link>https://medium.com/cloudvillains/data-parallelism-in-machine-learning-training-686ed9ab05fb?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/686ed9ab05fb</guid>
            <category><![CDATA[training]]></category>
            <category><![CDATA[data-parallelism]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 00:52:38 GMT</pubDate>
            <atom:updated>2024-04-15T00:52:38.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iL0zs3NNir12XtqbQQuJmw.jpeg" /><figcaption>Generated by Gemini</figcaption></figure><p>In the era of Generative AI, a distributed training system is essential to anyone who wants to leverage Gen AI since the Generative AI model is mostly huge. The first notion of the distributed system you should know is data parallelism. That is, a very large dataset is split into multiple GPUs and each GPU has a copy of the machine learning model to train in a parallel manner.</p><p>Given a single GPU, its full internal state is available locally, such as model parameters, optimizer parameters, gradients, etc. Using data parallelism, the training set is split into mini-batches evenly distributed across GPUs. Each GPU only trains the model on a subset of the total dataset so that the model state is slightly different on each GPU. To converge the internal states while training, the model state must be regularly updated on all GPUs synchronously or asynchronously.</p><h3>Data Parallelism</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dW-pXm7MfnVav5nlBzLTuA.jpeg" /><figcaption>Generated by Gemini</figcaption></figure><p>As I mentioned, data parallelism is a core technique for distributed training of large machine learning models. The basic idea is to split the training dataset across multiple GPUs, where each GPU maintains a full copy of the model. During each training iteration:</p><ol><li>The dataset is divided into small batches, and each batch is assigned to a different GPU.</li><li>Each GPU independently computes the gradients for its assigned batch using its own copied model.</li><li>The gradients from all GPUs are then aggregated.</li><li>The aggregated gradients are used to update the model parameters on all GPUs.</li></ol><p>This approach allows the training to scale linearly with the number of GPUs, as each GPU can process a different batch of data in parallel. The key benefit is that it allows you to effectively leverage multiple GPUs’ aggregate memory and compute power to train much larger models than those of a single GPU.</p><h3>Synchronous vs. Asynchronous Updates</h3><p>We already touched on the need to regularly update the model state across all GPUs. There are two main approaches for this:</p><h4>Synchronous updates</h4><p>In this approach, the gradients from all GPUs are aggregated and the model parameters are updated simultaneously on all GPUs after each iteration. This ensures that the model state is consistent across all GPUs, but can limit the training throughput if the communication between GPUs is slow. In other words, all GPUs report their updates to all other GPUs or to a central parameter server that redistributes them. As updates are applied simultaneously, the model state is in sync on all GPUs.</p><h4>Asynchronous updates</h4><p>Here, each GPU updates its local model copy independently, without waiting for the other GPUs. The parameter updates are then shared asynchronously with the other GPUs, typically using a parameter server architecture. This can improve training throughput, but also lead to inconsistent model states across GPUs, which may impact convergence.</p><p>That is to say, if gradient updates are sent to all other nodes or a central server and they are applied immediately, the problem of scaling comes to us. As the number of GPUs increases, a parameter server will inevitably suffer from a bottleneck. Without a parameter server, network congestion becomes a problem as well. We will train a model more slowly than we expect even though many GPUs are used.</p><p>Choosing between synchronous and asynchronous updates often involves a trade-off between training throughput and model convergence. Synchronous updates generally lead to more stable training, while asynchronous updates can be faster but may require more careful hyperparameter tuning.</p><h4>The Challenges of Asynchronous Updates</h4><p>As you mentioned, the key issue with asynchronous updates is the potential for inconsistent model states across the GPUs. When each GPU updates its local model copy independently, without waiting for the other GPUs, it can lead to the following problems:</p><ol><li>Staleness: The parameter updates made by one GPU may not get propagated to the other GPUs on time. This can result in some GPUs training on “stale” model parameters that are out of sync with the latest updates.</li><li>Divergence: The independent updates on each GPU can cause the model parameters to diverge, leading to inconsistent internal states across the replicas. This can negatively impact the model’s ability to converge to a stable solution.</li><li>Bottlenecks: As you pointed out, without a central parameter server, the need to communicate parameter updates across the distributed network can lead to congestion and become a performance bottleneck, especially as the number of GPUs increases.</li></ol><p>However, AllReduce handles this issue efficiently. Ring-AllReduce is one of the decentralized asynchronous algorithms which are called AllReduce. Ring-AllReduce organizes nodes in a directed one-way ring.</p><h3>How AllReduce Works</h3><p>There are multiple types of AllReduce .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cS4ad1gBSyOCj_dRIOhZhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_9jdeoR4uDTtAw5FFxxmg.png" /></figure><p>These are easily thought algorithms of AllReduce ; however, each has some problems. The first one has redundant communications and the second one’s GPU_1 suffers from a bottleneck as the number of GPUs increases.</p><h3>How Ring-AllReduce Works</h3><p>DespiteAllReduce algorithms’ hurdles, Ring-AllReduce provides an elegant solution to these challenges. The key benefits of Ring-AllReduce are:</p><ol><li>Efficient communication: Ring-AllReduce organizes the GPUs in a ring topology, allowing the gradients to be aggregated efficiently, with each GPU only needing to communicate with its immediate neighbors in the ring.</li><li>Decentralization: The ring-based communication pattern of Ring-AllReduce eliminates the need for a centralized parameter server. This avoids the bottleneck that can occur with a parameter server architecture.</li><li>Synchronization: This type of AllReduce operation ensures that the parameter updates are synchronized across all GPUs, maintaining a consistent model state and avoiding the divergence issues that can arise with fully asynchronous updates.</li></ol><p>By using Ring-AllReduce, the distributed training system can achieve the benefits of asynchronous updates (faster throughput) while mitigating the potential downsides (inconsistent model state and divergence). The synchronization provided by Ring-AllReduce helps to stabilize the training process and improve convergence, even with the asynchronous parameter updates.</p><p>Ring-AllReduce has two steps, Scatter-Reduce and AllGather.</p><h4>Scatter-Reduce</h4><p>Before seeing how this step communicates, we assume that there are 4 GPUs and each has the same copy of the model, which consists of 4 neurons. After finishing computing gradients, each model has its own gradient. That is, the model on GPU_1 has a gradient of A1 , B1 , C1 and D1 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmErrCiLx6CP73_sWAkOpw.png" /></figure><p>To aggregate the gradients in a way of Scatter-Reduce, All the GPUs send an element of their gradient to the next GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2TS52INTIALg91-X4Ud2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOlE2Z98cjDpBJZA6TuiQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psypnDQQEdUTCUfxl6SICg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAQHSHaaHPbBlUnHdRWeLg.png" /></figure><h4>AllGather</h4><p>After Scatter-Reduce is done, each GPU has the sum of elements of gradients spreaded in all the GPUs. As you can see above, GPU_1 has the sum of the second elements from all the GPUs.</p><p>AllGather get all the GPUs have the same aggregation of gradients. So, the first GPU sends its sum of elements to the second GPU. Finally All the GPUs have the same gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgqP5QqI37U-HnwGE-1NYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqKXX4tDFd9LKKmYw2MX9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDbdAOlT6m-EOF0RtYc6aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zm4jp4aS-JPi2UhCgHfw6Q.png" /></figure><h3>Conclusion</h3><p>We discuss distributed training for large-scale generative AI models, focusing on the concept of data parallelism. Key points:</p><ol><li>Data parallelism is a core technique for distributed training, where the dataset is split across multiple GPUs, each with a full copy of the model.</li><li>There are two main approaches for updating the model state across GPUs<br>- Synchronous updates: Gradients are aggregated and model parameters are updated simultaneously on all GPUs<br>- Asynchronous updates: Each GPU updates its local model independently, sharing updates asynchronously.</li><li>Asynchronous updates can improve training throughput but may lead to issues like staleness, divergence, and bottlenecks due to inconsistent model states across GPUs.</li><li>Ring-AllReduce, a decentralized asynchronous algorithm, provides an efficient solution by organizing GPUs in a ring topology. This allows for efficient communication between neighboring GPUs, elimination of the need for a central parameter server, and synchronized parameter updates to maintain a consistent model state</li><li>Ring-AllReduce has two main steps. Scatter-Reduce aggregates gradients by passing elements between neighboring GPUs. AllGather shares the aggregated gradients across all GPUs.</li></ol><p>The summary highlights the importance of distributed training techniques like data parallelism and the challenges of asynchronous updates, as well as the benefits of the Ring-AllReduce algorithm as a solution to these challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686ed9ab05fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/data-parallelism-in-machine-learning-training-686ed9ab05fb">Data Parallelism in Machine Learning Training</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[그리드서치로 랜덤포레스트 튜닝하기]]></title>
            <link>https://medium.com/cloudvillains/%EA%B7%B8%EB%A6%AC%EB%93%9C%EC%84%9C%EC%B9%98%EB%A1%9C-%EB%9E%9C%EB%8D%A4%ED%8F%AC%EB%A0%88%EC%8A%A4%ED%8A%B8-%ED%8A%9C%EB%8B%9D%ED%95%98%EA%B8%B0-f9ca547d484f?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/f9ca547d484f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[gridsearchcv]]></category>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 23:51:31 GMT</pubDate>
            <atom:updated>2024-04-10T23:51:31.056Z</atom:updated>
            <content:encoded><![CDATA[<p>이 블로그는 영문으로 작성된 <a href="https://medium.com/cloudvillains/random-forest-with-grid-search-b739fb0da311">Random Forest with Grid Search</a>를 <a href="https://claude.ai/chats">Claude</a>를 통해 국문으로 번역하여 작성되었습니다. 이해를 돕기 위해 약간 수정했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EbwXJCxXPoUohKGy.jpeg" /><figcaption>Generated by Gemini</figcaption></figure><blockquote>나무를 보고 숲을 보지 못하다.</blockquote><p>이 격언은 세부적인 것에 너무 집중하다 보면 전체적인 큰 그림을 놓치게 된다는 의미입니다. 즉, 큰 그림을 보면서 부분적인 세부사항을 종합하는 것이 중요하다는 교훈을 줍니다. 이는 기계 학습뿐만 아니라 다양한 분야에서 적용될 수 있는 의미 있는 통찰입니다. 기계 학습 분야에서도 적용되는데, 의사 결정 트리 모델은 개별 트리에 집중하지만, 랜덤 포레스트 모델은 다수의 의사 결정 트리를 결합하여 더 나은 성능을 발휘합니다. 랜덤 포레스트가 기계 학습 알고리즘 중 인기 있는 이유입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*wJjYZjdJr_w6jBCU.png" /><figcaption>Generated by Gemini</figcaption></figure><p>우리는 Google Colab에서 랜덤 포레스트를 구현하는 과정을 단계별로 살펴보겠습니다.</p><ul><li>데이터셋 얻기</li><li>데이터셋 읽고 수치 변수에 대한 히스토그램 그리기</li><li>범주형 변수에 대한 원-핫 인코딩</li><li>학습 데이터와 테스트 데이터 분리</li><li>마이너 클래스 인스턴스 오버샘플링</li><li>랜덤 포레스트 모델 학습</li><li>모델 성능 평가</li><li>하이퍼파라미터 튜닝(그리드 서치)</li><li>특성 중요도 분석</li></ul><p>이런 단계를 통해 Google Colab에서 랜덤 포레스트 모델을 구현하고 이해할 수 있을 것 같습니다. 각 단계에서 필요한 코드와 설명을 잘 살펴보시면 좋을 것 같습니다.</p><h3>데이터셋 얻기</h3><p>Kaggle에서 제공하는 <a href="https://www.kaggle.com/datasets/minnikeswarrao/british-airways-customer-booking?source=post_page-----b739fb0da311--------------------------------">항공권 예약 데이터 세트</a>를 사용하겠습니다. 이 데이터 세트는 50,000개의 기록과 14개의 특성으로 구성되어 있네요.</p><p>다음은 데이터 세트의 열 설명입니다. booking_complete가 타깃 변수로, 고객이 예약을 완료했는지 여부를 나타냅니다.</p><ul><li>num_passengers: 여행하는 승객 수</li><li>sales_channel: 예약이 이뤄진 판매 채널</li><li>trip_type: 여행 유형(왕복, 편도, 원 스톱)</li><li>purchase_lead: 여행일과 예약일 사이의 일수</li><li>length_of_stay: 목적지에서의 체류 일수</li><li>flight_hour: 비행 출발 시간</li><li>flight_day: 비행 출발 요일</li><li>route: 출발지 -&gt; 도착지 항공편 경로</li><li>booking_origin: 예약이 이뤄진 국가</li><li>wants_extra_baggage: 고객이 추가 수화물을 원했는지 여부</li><li>wants_preferred_seat: 고객이 우선석을 원했는지 여부</li><li>wants_in_flight_meals: 고객이 기내식을 원했는지 여부</li><li>flight_duration: 총 비행 시간(단위: 시간)</li><li>booking_complete: 고객이 예약을 완료했는지를 나타내는 플래그</li></ul><h3>데이터 세트 읽고 수치 변수에 대한 히스토그램 그리기</h3><p>이 단계에서는 우선 데이터 세트를 읽어들이고, 수치형 변수들에 대한 히스토그램을 그려보겠습니다. 이를 통해 각 변수의 분포와 특성을 살펴볼 수 있습니다.</p><ul><li>데이터 세트 읽기<br>- 제공된 항공권 예약 데이터 세트를 읽어들입니다.<br>- 데이터 프레임 형태로 데이터를 저장합니다.</li><li>수치 변수 히스토그램 그리기<br>- 수치형 변수들(예: num_passengers, purchase_lead, length_of_stay, flight_duration 등)에 대한 히스토그램을 그립니다.<br>- 이를 통해 각 변수의 분포와 특성을 시각적으로 확인할 수 있습니다.<br>- 히스토그램 분석을 통해 이상치 탐지, 변수 변환 등의 전처리 작업을 수행할 수 있습니다.</li></ul><pre>import pandas as pd<br><br>df = pd.read_csv(&#39;customer_booking.csv&#39;, encoding=&#39;ISO-8859–1&#39;)<br>df.hist(figsize = (10, 10))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/0*axicGMe6AV5mYiHw.png" /></figure><p>위의 히스토그램 분석 결과를 보면 다음과 같습니다:</p><ul><li>종속 변수인 booking_complete가 불균형되어 있습니다.</li><li>5개의 변수가 범주형 변수로 확인되었습니다.</li><li>이에 따라 범주형 변수에 대한 원-핫 인코딩이 필요할 것으로 보입니다.</li></ul><p>범주형 변수를 확인하는 방법으로 for 루프를 활용할 수 있습니다. 첫 번째 행의 데이터 유형이 문자열인지 확인하는 조건을 사용하면 됩니다.</p><pre>cat_cols = []<br>num_cols = []<br><br>for col in df.columns:<br>  if type(df[col][0]) == str:<br>    cat_cols.append(col)<br>  else:<br>    num_cols.append(col)</pre><h3>범주형 변수에 대한 원-핫 인코딩</h3><p>범주형 변수에 대한 원-핫 인코딩 방법은 주로 두 가지가 있습니다:</p><ol><li>Sklearn 사용</li><li>Pandas의 pd.get_dummies() 함수 사용</li></ol><p>Pandas의 pd.get_dummies() 함수를 사용하는 것이 코딩 측면에서 더 간단합니다. 이 때 axis=1을 명시해야 합니다. 그렇지 않으면 행 방향으로 연결되기 때문입니다.</p><p>원-핫 인코딩이 완료되면 원래의 범주형 변수 열은 삭제해야 합니다.</p><p>이와 같은 방식으로 데이터 세트의 범주형 변수를 원-핫 인코딩할 수 있습니다.</p><pre>from pandas import get_dummies<br><br>for col in cat_cols:<br>  X = pd.concat([X, pd.get_dummies(X[col])], axis =1 )<br>  X = X.drop(col, axis = 1)</pre><h3>학습 데이터와 테스트 데이터 분리</h3><p>기계 학습 모델링에서 데이터 분할은 매우 중요한 단계입니다. 만약 완전히 분리되지 않으면 데이터 누출로 인해 치명적인 예측 문제가 발생할 수 있습니다. 예를 들어, 학습 정확도와 테스트 정확도가 모두 좋게 나올 수 있지만, 이 모델은 실 운영에서 실패할 수 있습니다. 데이터 누출로 인해 테스트 정확도가 높게 나오지만, 실제 일반화 성능은 좋지 않기 때문입니다. 이 데이터 누출 문제는 오버샘플링 단계에서도 다시 언급될 것입니다. 따라서 학습 데이터와 테스트 데이터를 완전히 분리하는 것이 매우 중요합니다. 그렇지 않으면 모델의 성능과 일반화 능력을 정확하게 평가할 수 없게 됩니다</p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)<br>y_train.hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*k_C5eSCtF-uM6Na5.png" /></figure><h3>마이너 클래스 인스턴스 오버샘플링</h3><p>위의 히스토그램에서 볼 수 있듯이, 타깃 변수의 분포가 매우 불균형합니다. 데이터셋의 이러한 불균형은 ML 모델의 성능을 저하시킵니다. 예를 들어, 데이터셋이 사기 관련이고 사기 비율이 0.01%라고 가정해 보겠습니다. 만약 모델이 모든 고객을 사기가 아닌 것으로 예측한다면, 정확도는 99.99%가 될 것입니다. 하지만 이 모델은 사기를 방지할 수 없습니다. 즉, 정확도가 99.99%임에도 불구하고 모델이 실패하게 되는 것입니다. 따라서 이러한 불균형은 마이너 클래스를 오버샘플링하거나 메이저 클래스를 언더샘플링하여 해결해야 합니다. ML 분야에서는 오버샘플링이 선호됩니다.</p><p>SMOTE(Synthetic Minority Over-sampling Technique)는 K-최근접 이웃(KNN) 알고리즘을 활용하여 마이너 클래스의 새로운 데이터포인트를 생성합니다. 구체적으로는 마이너 클래스의 한 데이터포인트를 선택하고, 이 데이터포인트와 가까운 데이터포인트들 중 하나를 선택하여 새로운 데이터를 생성합니다. 중요한 것은 오버샘플링은 오직 학습 데이터에만 적용해야 한다는 점입니다. 테스트 데이터를 분리하기 전에 오버샘플링을 수행하면 데이터 누출이 발생할 수 있습니다.</p><pre>from imblearn.over_sampling import SMOTE<br><br>smote = SMOTE()<br>X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)<br>y_train_resampled.hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*Kq78WfqEkBqxjJvm.png" /></figure><h3>랜덤 포레스트 모델 학습</h3><p>데이터 전처리 단계를 완료했으니, 이제 랜덤 포레스트 모델을 학습시켜 보도록 하겠습니다. 이처럼 데이터 세트를 준비하고 랜덤 포레스트 모델을 학습시킨 결과, 84%의 정확도를 달성할 수 있었습니다. 이 단계에서는 이렇게 간단하게 랜덤 포레스트 모델을 학습시키고 초기 성능을 확인할 수 있습니다. 다음 단계에서는 모델 성능을 더 자세히 검증하고, 하이퍼파라미터 튜닝을 통해 성능을 향상시키는 방법을 살펴보겠습니다. 이처럼 데이터 세트를 준비하고 랜덤 포레스트 모델을 학습시킨 결과, 84%의 정확도를 달성할 수 있었습니다. 이 단계에서는 이렇게 간단하게 랜덤 포레스트 모델을 학습시키고 초기 성능을 확인할 수 있습니다. 다음 단계에서는 모델 성능을 더 자세히 검증하고, 하이퍼파라미터 튜닝을 통해 성능을 향상시키는 방법을 살펴보겠습니다.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br><br>rf = RandomForestClassifier()<br>rf.fit(X_train_resampled, y_train_resampled)<br>y_pred = rf.predict(X_test)<br>accuracy_score(y_test, y_pred)</pre><h3>모델 성능 검증</h3><p>모델 성능을 검증할 때 가장 먼저 고려해야 하는 것은 혼동 행렬(Confusion Matrix)입니다. 혼동 행렬이라는 이름에서 알 수 있듯이, 이 지표를 정확하게 이해하고 해석하는 것은 쉽지 않습니다. 많은 똑똑한 사람들도 혼동을 겪곤 합니다. 혼동 행렬은 실제 라벨과 예측 라벨 사이의 관계를 보여주는 매트릭스입니다. 이를 통해 모델의 정확도, 정밀도, 재현율 등 다양한 성능 지표를 계산할 수 있습니다. 따라서 혼동 행렬은 모델 평가에 있어 매우 중요한 도구이지만, 이를 올바르게 해석하고 활용하는 것이 관건입니다. 모델 성능 검증 시 혼동 행렬을 면밀히 분석하여 모델의 장단점을 파악해야 합니다.</p><pre>from sklearn.metrics import confusion_matrix<br>import matplotlib.pyplot as plt<br>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br><br>cm = confusion_matrix(y_test, y_pred)<br>disp = ConfusionMatrixDisplay(confusion_matrix=cm,<br>                              display_labels=rf.classes_)<br>disp.plot()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/0*0TfVxcejpdpdX5K3.png" /></figure><p>재현율(recall)이 23%라는 것은 실제로 완료된 예약 중 23%만 모델에 의해 완료된 것으로 예측되었다는 의미입니다. 즉, 모델이 실제 완료된 예약의 77%를 누락하여 예측하지 못했다는 뜻입니다. 이는 모델의 성능이 좋지 않다는 것을 나타내는 지표입니다. 모델이 실제 완료된 예약을 잘 찾아내지 못하고 있다는 문제점을 보여줍니다. 따라서 이 모델의 성능 개선을 위한 추가적인 최적화가 필요할 것으로 보입니다.</p><pre>from sklearn.metrics import recall_score<br><br>recall_score(y_test, y_pred)</pre><p>정밀도(Precision)가 42%라는 것은 모델이 완료된 것으로 예측한 예약 중 실제 완료된 예약은 42%에 불과하다는 것을 의미합니다. 즉, 모델이 완료된 것으로 예측한 예약 중 절반 이상이 실제로는 완료되지 않았다는 것을 의미합니다. 이는 모델의 정밀도가 좋지 않다는 것을 보여줍니다. 모델이 완료된 것으로 잘못 예측하는 경우가 많다는 문제점이 있다고 볼 수 있습니다. 재현율과 마찬가지로 이 모델의 성능 향상을 위한 추가적인 개선이 필요할 것으로 보입니다.</p><pre>from sklearn.metrics import precision_score<br><br>precision_score(y_test, y_pred)</pre><h3>하이퍼파라미터 튜닝(그리드 서치)</h3><p>현재의 모델로는 충분하지 않습니다. 더 나은 성능을 위해 하이퍼파라미터 튜닝을 시도해 보겠습니다. 교차 검증(CV)을 활용한 그리드 서치가 도움이 될 것 같습니다. 다음과 같은 하이퍼파라미터들을 조정해 보겠습니다.</p><ul><li>max_depth: 각 트리의 최대 깊이. 깊이가 너무 깊으면 과적합 될 수 있습니다</li><li>n_estimators: 숲 속 트리의 개수</li><li>max_features: 고려할 특성의 개수. 과적합을 방지하는 주요 하이퍼파라미터입니다. 총 특성 개수의 제곱근을 추천합니다</li><li>min_samples_leaf: 각 리프 노드에 필요한 최소 샘플 수.</li></ul><p>그리고 verbose=3으로 설정하면 그리드 서치 과정을 자세히 볼 수 있습니다. 이와 같은 하이퍼파라미터 튜닝을 통해 모델의 성능을 더 높일 수 있을 것으로 기대됩니다.</p><pre>from sklearn.model_selection import GridSearchCV<br><br>rf_grid = RandomForestClassifier()<br>gr_space = {<br>    &#39;max_depth&#39;: [3,5,7,10],<br>    &#39;n_estimators&#39;: [100, 200, 300, 400, 500],<br>    &#39;max_features&#39;: [10, 20, 30 , 40],<br>    &#39;min_samples_leaf&#39;: [1, 2, 4]<br>}<br>grid = GridSearchCV(rf_grid, gr_space, cv = 3, scoring=&#39;accuracy&#39;, verbose = 3)<br>model_grid = grid.fit(X_train_resampled, y_train_resampled)<br>print(&#39;Best hyperparameters are &#39;+str(model_grid.best_params_))<br>print(&#39;Best score is: &#39; + str(model_grid.best_score_))</pre><p>Google Colab의 CPU를 사용하여 4시간 이상 실행했지만, 정확도는 이전보다 오히려 낮아졌습니다. 그러나 재현율(Recall)은 47%, 정밀도(Precision)는 30%로 향상되었습니다. F1 스코어 측면에서 보면 이전 모델의 F1=0.297에서 이번 모델의 F1=0.366으로 개선되었습니다. 이를 통해 지금까지 수행한 하이퍼파라미터 튜닝 작업이 효과를 발휘한 것으로 볼 수 있습니다. 비록 정확도가 개선되지 않았지만, 재현율과 정밀도, 그리고 F1 스코어 측면에서는 성능 향상이 있었다고 할 수 있습니다. 따라서 지금까지 진행한 모델 개선 작업은 긍정적인 방향으로 작용한 것으로 판단됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*qlKHg8mhmugOltS_.png" /></figure><pre>rf_optimized = model_grid.best_estimator_<br>y_pred = rf_optimized.predict(X_test)<br>accuracy_score(y_test, y_pred)<br>recall_score(y_test, y_pred)<br>precision_score(y_test, y_pred)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/0*t7WnEtSmv8itlLeg.png" /></figure><h3>특성 중요도</h3><p>랜덤 포레스트 모델은 특성 중요도를 제공하여 모델을 해석할 수 있게 해줍니다. 가장 상위 10개의 중요한 특성은 다음과 같습니다.</p><ul><li>출발 요일(월요일, 화요일, 수요일, 금요일, 일요일)</li><li>출발지(호주, 남한)</li><li>비행 시간</li><li>체류 기간</li><li>판매 채널(모바일)</li></ul><p>흥미롭게도 목요일과 토요일은 모델에 상대적으로 적은 영향을 미치는 것으로 나타났습니다. 이러한 특성 중요도 정보를 통해 모델이 어떤 요인들을 더 중요하게 고려하는지 파악할 수 있습니다. 이는 모델의 성능 향상과 해석에 도움이 될 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c2n4VHvnT6iA3SxK.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*xp1M-UymiSu-YxgW.png" /></figure><h3>결론</h3><p>이상의 과정을 요약하면 다음과 같습니다</p><ol><li>항공권 예약 데이터를 활용하여 랜덤 포레스트 모델을 구축하였습니다.</li><li>데이터 전처리 단계에서 범주형 변수에 대한 원-핫 인코딩과 불균형 데이터에 대한 오버샘플링을 수행하였습니다.</li><li>학습 데이터와 테스트 데이터를 분리하여 모델 성능 평가의 신뢰성을 확보하였습니다.</li><li>초기 랜덤 포레스트 모델의 성능은 84%의 정확도로 나타났지만, 재현율과 정밀도가 낮았습니다.</li><li>이에 따라 하이퍼파라미터 튜닝을 수행하였고, 그 결과 F1 스코어가 0.366으로 향상되었습니다.</li><li>특성 중요도 분석을 통해 출발 요일, 출발지, 비행 시간, 체류 기간, 판매 채널 등이 주요 예측 요인임을 확인하였습니다.</li></ol><p>위의 과정을 통해 불균형 데이터에 대한 효과적인 전처리와 하이퍼파라미터 튜닝, 그리고 특성 중요도 분석을 수행하여 랜덤 포레스트 모델의 성능을 개선할 수 있었습니다. 이는 실제 항공권 예약 예측 문제에서 유용한 인사이트를 제공할 것으로 기대됩니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9ca547d484f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/%EA%B7%B8%EB%A6%AC%EB%93%9C%EC%84%9C%EC%B9%98%EB%A1%9C-%EB%9E%9C%EB%8D%A4%ED%8F%AC%EB%A0%88%EC%8A%A4%ED%8A%B8-%ED%8A%9C%EB%8B%9D%ED%95%98%EA%B8%B0-f9ca547d484f">그리드서치로 랜덤포레스트 튜닝하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Langchain을 통한 개인블로그 RAG 프로젝트]]></title>
            <link>https://medium.com/cloudvillains/langchain%EC%9D%84-%ED%86%B5%ED%95%9C-%EA%B0%9C%EC%9D%B8%EB%B8%94%EB%A1%9C%EA%B7%B8-rag-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-d801e7b39015?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/d801e7b39015</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[milvus]]></category>
            <category><![CDATA[langchaing]]></category>
            <category><![CDATA[obsidian]]></category>
            <dc:creator><![CDATA[Minchan Kim]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 02:20:23 GMT</pubDate>
            <atom:updated>2024-03-20T04:34:59.465Z</atom:updated>
            <content:encoded><![CDATA[<p>#RAG#Langchain#Streamlit#Milvus#Obsidian</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*9u51ybIBMSn5ccALmwb1lQ.png" /></figure><h3># 대상</h3><ul><li>langchain을 통해 RAG를 구현한 방법에 관심이 있으신 분들</li><li>LLM 애플리케이션을 만들 때 고민거리에 대해 관심이 있으신 분들</li></ul><h3># 개요</h3><p>- 프로젝트 시작 동기: 습관을 위한 개인 동기 + LLM 관련 개인 흥미 + 개인 브랜딩 등에 도움이 될 것이라 생각<br>- 진행 중인 프로젝트 소개: 웹 플랫폼, LLM 애플리케이션 RAG<br>- 프로젝트 진행하면서 겪은 고민 트러블슈팅: 많은 제품과 추상화 된 내용을 빠르게 쓸 수 있는 레벨이 되기<br>- RAG에서 중요한 토큰 줄이기 구현: 모든 파일 업데이트가 아닌 개별 entity 업데이트<br>- 직접 제품을 만들면서 느낀 점: 고도화에는 끝이 없다</p><h3># 내용</h3><p># 프로젝트 시작 동기</p><p>해당 프로젝트는 기록하는 습관을 만드는 일 + LLM 애플리케이션 + 개인 브랜딩과 같은 요소들을 해결하기 위해 시작된 혼자 진행하고 있는 프로젝트입니다.</p><p>그래서 현재 두 개의 프로젝트가 진행 중 입니다.</p><ul><li>하나는 기록된 markdown기반 텍스트 문서 데이터 생산 및 관리를 위한 웹 플랫폼</li></ul><p><a href="https://murphybooks.me/">https://murphybooks.me</a></p><ul><li>다른 하나는 이 데이터를 사용한 RAG를 사용할 수 있는 LLM 애플리케이션</li></ul><p><a href="https://murphybooks.streamlit.app/">https://murphybooks.streamlit.app</a></p><ul><li>(현재 해당 애플리케이션은 동작이 자주 멈출 수도 있음)</li></ul><p>운영 관리를 고려하여 두 배포 방식은 varcel과 streamlit cloud, milvus serverless 통해 인프라 관리를 솔루션에 맡김으로써 운영 관리와 비용을 줄이는 방법을 선택했습니다.</p><h3># 웹 플랫폼</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcROmjuPDIuKNvGLmTGkWw.png" /></figure><p>기록하는 습관을 만들기 위해 플랫폼을 고민하면서 이것저것 써보았습니다. 노션, 에버노트, 티스토리, 깃헙 페이지 등…<br>고려한 부분은 마크다운, SEO 등이 있었지만 가장 중요한 것은 내가 이 기록을 다시 볼 때 지식을 얻을 수 있느냐 였습니다. 흔히 기록만 하는 Archive용도가 아니라 insight를 얻고자 하는 용도이기에 그 목표로 로컬 환경 기반 옵시디언을 선택하고, 무료 웹 배포 플러그인을 활용하게 됐습니다.</p><p>해당 방식을 통해 얻게 된 가장 큰 이점은 데이터 스키마의 자유로운 조작이었습니다. 후술 할 LLM 애플리케이션을 사용하기 위한 데이터 소스로 작성한 markdown파일을 사용하는데 데이터의 이름 ,데이터 path, metadata등의 빈번한 수정이 있었는데 로컬 환경기반이어서 이런 문제들을 해결할 수 있었습니다.</p><h3># LLM 애플리케이션 RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-BNDgnwsmAKltH-By1nfA.png" /></figure><p>LLM 애플리케이션의 경우 명확한 목적이 중요했습니다. 목적의 경우 모델을 구현한 chatbot이기에 프론트와 백엔드를 배우는데 시간을 너무 많이 써버리지 않으면서도, 적당한 프로덕트의 기능이 구현가능해야한다는 점이 중요했습니다. 그 결과 지인 분의 추천을 받아 streamlit이라는 프레임워크와 널리 알려진 langchain을 선택하게 됐습니다. 두 프레임워크를 통해 LLM 관련 기능을 langchain으로 구현하며, 이 결과를 쉽게 stramlit을 사용해 프로덕트로 만들 수 있었습니다.</p><p>현재 해당 프로젝트는 계속 업데이트 중입니다. 예를 들어 Admin페이지를 구현하기 위한 방법, 메모리 관리, RAG에서 큰 단위와 작은 단위 필터링을 통한 구현 등…</p><h3># 프로젝트 진행하면서 겪은 고민 트러블슈팅</h3><p>프로덕트를 만들다 보니 실제 현실에서 고민해야 할 것들을 배우게 됩니다.</p><p>모니터링 지표 고민하기: 페이지 조회수를 어떻게 할까부터 시작하여, 페이지 default 언어를 영어로 바꾸기까지<br>- 처음에는 페이지 조회수를 집계하기 위한 방법을 찾고, 그걸 모든 페이지마다 구현할 방법을 찾기 위한 조건을 고려하는 인사이트를 얻었습니다. 그리고 Google Analytics라는 적절한 플러그인을 발견해서 그걸 웹 플랫폼에 구현해보며 해당 플랫폼이 영어권에서 오는 사람이 많다는 것을 깨닫고 플랫폼 기본언어를 영어로 설정하기로 하였습니다. 페이지에 머무르는 시간이나 인기 있는 페이지 등도 알 수 있어서 프로덕트 운영에서 모니터링 지표에 대한 자그마한 insight를 얻었습니다<br>Langchain의 추상화: 문제가 생겼을 때 너무 추상화 되다보니 문제가…</p><p>- LLM 구현 시 langchain을 사용했는데 추상화가 너무 돼있어서 커스텀하는 부분에서 파라미터가 숨겨져있다던가 하는 문제가 있었습니다. langchain의 경우 타고 타고 타가다보며 문제를 해결해야하는 경우가 많았습니다. 프로덕션레벨에서의 langchain이 어려운 부분이 언급이 나오는데 특히 데이터의 파라미터가 너무 추상화 돼 있다던가, docs와 가이드 등에서 stream이나 async등의 고급기능이 예제가 부족하다던가 하는 부분도 많았습니다.</p><p>외부 VectorDB 사용 기준: 레퍼런스 많은 걸로…<br>- 외부 벡터 DB를 사용할 때 지속 가능한 운영을 위해 요금,확장성, 커스텀 가능 정도, 오픈소스여부 등의 기준을 세운다던가, 실제 구현 시 솔루션에 한정된 vectordb의 upsert특정 기능에 따라 auto_id와의 충돌로 본인의 환경에 맞춘 구현방법으로 해결하는 과정 등이 있었습니다. 조금만 더 설명을 추가하자면 일단 langchain에서의 milvus라는 벡터 DB 를 구현하는 가이드와 Milvus에서 langchain을 구현하기 위한 가이드가 다르기 때문에 이를 이해하는데 시간이 많이 걸렸습니다. 또한 Milvus로 구현시 upsert의 id를 명시할 경우 id를 명시하지 않아야한다는 auto_id와의 충돌이 발생하는데 이에 대한 설명이 많이 부족해 직접 테스트해보며 깨달을 수 있었습니다. 결론적으로는 저와 같은 생각을 하는 사람이 겪은 레퍼런스가 많았다면 낭비되는 시간을 많이 줄일 수 있었을텐데라는 아쉬움이 남았습니다.</p><h3># RAG에서 중요한 토큰 줄이기 구현</h3><p>특히 가장 최근에 추가 된 업데이트는 LLM 애플리케이션에서 개별 아티클만 업데이트 하는 기능입니다. <br>RAG를 통해 웹 플랫폼의 context를 임베딩 하여 업데이트 할 때 나중에 페이지가 많아질수록 시간과 코스트가 우려됐습니다. 예를 들어 오늘 수정한 한 페이지를 업데이트하기 위해 모든 페이지를 임베딩하는 경우가 생길 수 밖에 없는 로직이었습니다. 특히 텍스트가 많아지면 많아질수록 문제는 커지기에 단일 파일만 업데이트하는 기능을 만들기로 했습니다.</p><p>해당 내용을 구성하기 위해 Milvus 공식 홈페이지에서 Entity에 대한 upsert를 먼저 찾아본 후 시도 하였습니다. 편한 기능이 있다면 바로 구현할 수 있을것이라 생각했지만, 실제로는 원하는 대로 동작하지 않았습니다. 그래서 여러 테스트 후 구조적으로 불가능하다는 것을 깨닫고 upsert가 아닌 delete insert형태로 구조를 만들게 됐습니다.</p><p>현재 기준으로 모든 파일에 대한 임베딩이 약 1500 토큰이 소모되는데, 내가 수정한 단일 파일만 업데이트를 한 경우 40 토큰이 소모됨으로서 속도와 비용을 크게 줄일 수 있습니다.</p><h3># 직접 제품을 만들면서 느낀 점</h3><p>고도화에는 끝이 없다고 느껴집니다…</p><p>버전 정책, 운영 관리를 위한 선언적 방식, 최대한 결합도를 약하고 응집도를 높이는 모듈식 구성, 민감한 변수 다루기<br>그리고 가장 중요한 실제 프로덕트로서의 목적을 잃지 않으면서도 납득할만한 가치를 내기 위한 점 등…<br>예를 들어 지금 하면 좋긴 하지만 이걸 하기 위해서 전체적인 플랜이나 우선순위가 높은 것들이 느려지면 안되는데, 이를 적절한 타이밍을 느끼는 그런 감 같은 것이 필요한 것 같습니다.</p><p>스스로에 질문을 던지며 계속 업데이트 중인 프로젝트들입니다.<br>웹 플랫폼<br>- 모든 파일에 대한 description 작성 (base template을 위한) -&gt; 수동<br>- 모든 아티클 파일(a,b,c와 같은 문자가 붙은)에 대한 내용 작성 -&gt; 수동<br>- 유저 친화적인 UI Component 재배치 (설명글 제거, 버튼 방식을 통한 파일 접근, guestbook 플러그인) <br>- 중앙 관리 env작성 (필요한 정보들 기입.streamlit사용 시 사용 변수, milvus 벡터 db 사용 시 필요한 권한 및 변수 등)</p><p>LLM 애플리케이션<br>- 메모리 문제 해결을 통한 Chat방식 구현(비용, 속도, 확장성, 보안 등 운영을 위한 메모리 방식으로 선정)<br>- 유저 별 history 관리, 유저 별 세션 관리 기능 추가<br>- 모니터링을 통한 정확한 함수 또는 api 별 속도, 성능 파악 -&gt; Langsmith 공부</p><p>이런 과정을 history로 남길 필요가 생기고, 그에 따라 버저닝 정책을 어떻게 가져가야 할 것인가 같은 부분도 고려됐습니다. 그래서 현재 major.minor.path-(LB,PY,FE,OB)라는 저만의 버저닝 정책 등도 만들게 되보네요<br><a href="https://www.murphybooks.me/projects/library/manage/history-of-library/">https://www.murphybooks.me/projects/library/manage/history-of-library/ </a>(해당 내용을 기록하는 library 역사관)</p><h4>## 결론<br>1. 개인 동기로 시작한 프로젝트가 웹 플랫폼과 LLM애플리케이션을 만드는 프로젝트로까지 이어지고 실제로 만들면서 얻을 수 있는 insight가 있다는 것을 배움<br>2. streamlit과 langchain을 통해 RAG를 구현하며 구현 도중 여러 솔루션을 사용해보고 트러블 슈팅하며 프로덕트를 구현<br>3. 레퍼런스가 많은 솔루션이 확실히 낭비되는 시간을 줄일 수 있으며, 고도화에는 끝이 없음</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d801e7b39015" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/langchain%EC%9D%84-%ED%86%B5%ED%95%9C-%EA%B0%9C%EC%9D%B8%EB%B8%94%EB%A1%9C%EA%B7%B8-rag-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-d801e7b39015">Langchain을 통한 개인블로그 RAG 프로젝트</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random Forest with Grid Search]]></title>
            <link>https://medium.com/cloudvillains/random-forest-with-grid-search-b739fb0da311?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/b739fb0da311</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Soonmo Seong]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 03:38:38 GMT</pubDate>
            <atom:updated>2024-04-09T03:46:20.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tjFkQYoKN3uHXKj8-SZjA.jpeg" /><figcaption>By Google Gemini</figcaption></figure><blockquote>Don’t miss the forest for the trees</blockquote><p>This is one of the famous quotes in the world. That works in ML literature as well. Random Forest normally has better performance than decision tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*5-qEWkPK_Erabg_AB34uqw.png" /><figcaption>By Google Gemini</figcaption></figure><p>That’s why Random Forest is one of my favorites in ML algorithms. We are going to implement Random Forest in Google Colab. In this blog, we walk through implementing Random Forest step by step:</p><ul><li>Getting dataset</li><li>Reading the dataset and plotting histogram for numerical variables</li><li>One-hot encoding categorical variables</li><li>Splitting train and test data</li><li>Oversampling the minor class instances</li><li>Fitting Random Forest</li><li>Validating the model performance</li><li>Hyperparameter tuning(Grid Search)</li><li>Feature Importance</li></ul><h4>Getting Dataset</h4><p>Flight booking data is used. The dataset is from <a href="https://www.kaggle.com/datasets/minnikeswarrao/british-airways-customer-booking">Kaggle public dataset</a>. This dataset has 50,000 records with 14 features.</p><p><a href="https://www.kaggle.com/datasets/minnikeswarrao/british-airways-customer-booking">Flight Bookings data</a></p><p>The column description is below. The target is booking_complete. This shows whether customers complete a booking or not.</p><ul><li>num_passengers = number of passengers traveling</li><li>sales_channel = sales channel booking was made on</li><li>trip_type = trip type (Round Trip, One Way, Circle Trip)</li><li>purchase_lead = number of days between travel date and booking date</li><li>length_of_stay = number of days spent at destination</li><li>flight_hour = hour of flight departure</li><li>flight_day = day of the week of flight departure</li><li>route = origin -&gt; destination flight route</li><li>booking_origin = country from where the booking was made</li><li>wants_extra_baggage = if the customer wanted extra baggage in the booking</li><li>wants_preferred_seat = if the customer wanted a preferred seat in the booking</li><li>wants_in_flight_meals = if the customer wanted in-flight meals in the booking</li><li>flight_duration = total duration of flight (in hours)</li><li>booking_complete = flag indicating if the customer completed the booking</li></ul><h4>Reading the dataset and plotting histogram for numerical variables</h4><pre>import pandas as pd<br><br>df = pd.read_csv(&#39;customer_booking.csv&#39;, encoding=&#39;ISO-8859–1&#39;)<br>df.hist(figsize = (10, 10))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*MEgKkxmtukfzrdGCRODXng.png" /></figure><p>From the histograms above, the dependent variable booking_complete is imbalanced and 5 variables are categorical, resulting in one-hot encoding.</p><p>for loop is useful to identify categorical variables. The condition is if the first row is str or not.</p><pre>cat_cols = []<br>num_cols = []<br><br>for col in df.columns:<br>  if type(df[col][0]) == str:<br>    cat_cols.append(col)<br>  else:<br>    num_cols.append(col)</pre><h4>One-hot encoding categorical variables</h4><p>There are mainly two methods of one-hot encoding in sklearn and pandas. Using pandas.get_dummies is easier coding-wise. And, axis=1 should be mentioned in pd.concat. Otherwise, it will be concatenated in a row direction. After one-hot encoding, the column is dropped.</p><pre>from pandas import get_dummies<br><br>for col in cat_cols:<br>  X = pd.concat([X, pd.get_dummies(X[col])], axis =1 )<br>  X = X.drop(col, axis = 1)</pre><h4>Splitting train and test data</h4><p>Splitting data is very important in ML modeling. If not completely separated, data leakage causes fatal prediction problems. For example, both training accuracy and test accuracy are good enough; however, this model fails in production. This is because data leakage gets the test accuracy high, sugar-coating low generalization power. Data leakage will be mentioned again in the oversampling step.</p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)<br>y_train.hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*iOVlfYWw4qUzWzEC2V0LEg.png" /></figure><h4>Oversampling the minor class instances</h4><p>As you can see in the histogram above, the distribution of the target is highly imbalanced. The imbalance of the dataset deteriorates the performance of the ML model. Say, a dataset is fraud-related and the fraud rate is 0.01%. If the model blindly predicts all customers are not fraudulent, the accuracy is 99.99% and the model can’t prevent fraud. In other words, the model fails to save even though the accuracy is 99.99%. So, the imbalance should be handled using oversampling the minor class or undersampling the major classes. Oversampling is preferable in the ML scene.</p><p>SMOTE takes advantage of the K-nearest neighbor(KNN) algorithm to create minor class datapoints. In detail, SMOTE selects one of the minor class datapoints, identifies close ones based on KNN and chooses one of them.</p><p>The thing is that only training data should be oversampled, not test data. If oversampling both, data leakage will happen by mistake.</p><pre>from imblearn.over_sampling import SMOTE<br><br>smote = SMOTE()<br>X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)<br>y_train_resampled.hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*si5Q3FKWdqGqJlzguVVHsg.png" /></figure><h4>Fitting Random Forest</h4><p>We’ve done data preparation for modeling. Let’s fit Random Forest. It gives 84% accuracy.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br><br>rf = RandomForestClassifier()<br>rf.fit(X_train_resampled, y_train_resampled)<br><br>y_pred = rf.predict(X_test)<br>accuracy_score(y_test, y_pred)</pre><h4>Validating the model performance</h4><p>Confusion matrix is the first choice when validating a model. As per the name of it, it isn’t easy to understand and interpret correctly. It confuses many smart guys indeed.</p><pre>from sklearn.metrics import confusion_matrix<br>import matplotlib.pyplot as plt<br>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br><br>cm = confusion_matrix(y_test, y_pred)<br><br>disp = ConfusionMatrixDisplay(confusion_matrix=cm,<br>                              display_labels=rf.classes_)<br>disp.plot()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*fG_M32-FsECigVZB8N0UPA.png" /></figure><p>The recall is 23%, so only 23% of truly complete bookings are predicted to be booked completely.</p><pre>from sklearn.metrics import recall_score<br><br>recall_score(y_test, y_pred)</pre><p>Precision is 42%, so less than half of the predicted complete booking is true.</p><pre>from sklearn.metrics import precision_score<br><br>precision_score(y_test, y_pred)</pre><h4>Hyperparameter tuning(Grid Search)</h4><p>We can’t stay here. Let’s try to improve more. Grid search with CV will help us. We tune some of the hyperparameters as below.</p><ul><li>max_depth : the maximum level of each tree. A deeper tree is more overfitted. So, a high value makes the model fail to generalize.</li><li>n_estimators : the number of trees in the forest.</li><li>max_features : the number of features. This is one of the main hyperparameters that prevents overfitting. The square root of the total number of features is recommended.</li><li>min_samples_leaf : the minimum number of samples required to be at the leaf node of each tree.</li></ul><p>verbose = 3 shows how the model searches the grid search space.</p><pre>from sklearn.model_selection import GridSearchCV<br><br>rf_grid = RandomForestClassifier()<br>gr_space = {<br>    &#39;max_depth&#39;: [3,5,7,10],<br>    &#39;n_estimators&#39;: [100, 200, 300, 400, 500],<br>    &#39;max_features&#39;: [10, 20, 30 , 40],<br>    &#39;min_samples_leaf&#39;: [1, 2, 4]<br>}<br><br>grid = GridSearchCV(rf_grid, gr_space, cv = 3, scoring=&#39;accuracy&#39;, verbose = 3)<br>model_grid = grid.fit(X_train_resampled, y_train_resampled)<br><br>print(&#39;Best hyperparameters are &#39;+str(model_grid.best_params_))<br>print(&#39;Best score is: &#39; + str(model_grid.best_score_))</pre><p>More than 4 hours with Google Colab CPU are taken, but accuracy is worsened than before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*tOaiRmMrkuOScODK3QGgvw.png" /></figure><p>Recall is 47% and precision is 30%. In terms of recall and precision, it looks better than before hyperparameter tuning because the previous one f1=0.297 and this one f1=0.366. Hence, what we have done works.</p><pre>rf_optimized = model_grid.best_estimator_<br>y_pred = rf_optimized.predict(X_test)<br>accuracy_score(y_test, y_pred)<br>recall_score(y_test, y_pred)<br>precision_score(y_test, y_pred)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*khxmEllrZWck6N4oKQzEVQ.png" /></figure><h4>Feature importance</h4><p>Random Forest provides feature importance from where we can interpret the model. The top 10 important features are the day of departure(Mon, Tue, Wed, Fri, and Sun), Origin(Australia and South Korea), flight duration, length of stay, and sales channel(mobile). Surprisingly, Thursday and Saturday have less impact on the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNooMZcDM0IyjbBhm1NH8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*rQnKRhWUnUpS_fQu0GhgMQ.png" /></figure><h4>Conclusion</h4><p>A random forest model was built using the airline booking dataset. During the data preprocessing stage, one-hot encoding was applied to categorical variables, and oversampling was performed to address the imbalanced data. The training and test data were separated to ensure the reliability of the model performance evaluation. The initial random forest model achieved an accuracy of 84%, but had lower recall and precision. As a result, hyperparameter tuning was performed, and the F1 score improved to 0.366. Feature importance analysis revealed that departure day, departure origin, flight duration, length of stay, and sales channel were the key predictive factors. Overall, effective preprocessing of the imbalanced data, hyperparameter tuning and feature importance analysis helped improve the performance of the random forest model. These insights can provide valuable information for real-world airline booking prediction problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b739fb0da311" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/random-forest-with-grid-search-b739fb0da311">Random Forest with Grid Search</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web Application Using AWS Amplify and AWS Services]]></title>
            <link>https://medium.com/cloudvillains/building-a-web-application-using-aws-amplify-and-aws-services-33bac76787ab?source=rss----b89c9d54c8bb---4</link>
            <guid isPermaLink="false">https://medium.com/p/33bac76787ab</guid>
            <category><![CDATA[aws-amplify]]></category>
            <dc:creator><![CDATA[Danny Woo]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 02:13:50 GMT</pubDate>
            <atom:updated>2024-03-05T02:13:50.014Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>This blog aimed to test AWS Amplify and AWS Services for web development, exploring their advantages over on-premises environments. AWS Amplify was utilized for constructing the frontend web application, while AWS Lambda and API Gateway were employed for backend logic implementation. A simple login page was created for data validation, with DynamoDB storing the data for validation purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9SGFH3A4T3u3DusnK9nc-Q.png" /></figure><p>Please note that this blog doesn’t specifically explain setting backend logic using AWS Services such as API Gateway, Lambda, and DynamoDB. Other AWS DB services are viable options, and Lambda functions can be implemented differently based on language preferences.</p><h4><strong>What is Amplify</strong></h4><p>AWS Amplify streamlines full-stack app development. Its libraries, CLI and services enable an easy connection of the frontend to the cloud for authentication, storage, APIs, and more.</p><p><strong>Reference</strong><br><a href="https://docs.amplify.aws/">https://docs.amplify.aws/</a></p><h3>Frontend</h3><h4><strong>AWS Amplify</strong></h4><p>The frontend was built using AWS Amplify. The ‘Host web app’ option in Amplify was selected, which triggered an automatic build and deployment of the code uploaded on GitHub. This process led to the automatic deployment of the pre-uploaded index.html file.</p><p><a href="https://github.com/DaeSikWoo/AWS_Amplify_Login/tree/main"><strong>My GitHub repository</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Hp96jwrzcOFKsJA7cnmwSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*cAe48umjtQLP0ALkReok3A.png" /></figure><p>Once the Github repository branch is added and building settings are configured, the hosting environment is ready with an accessible URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*UctpGjNlqX-T_884zPdTvg.png" /></figure><h3>Backend</h3><h4>Amazon DynamoDB</h4><p>The web application’s purpose is to login and validate data stored in DynamoDB. Items were created with the username ‘Danny’ and its password for verification. DynamoDB was chosen for this task as it is relatively less expensive than RDS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*lDb-miv_b5X54xTv20djPA.png" /></figure><p><strong>Reference<br></strong>https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html</p><h4>AWS Lambda</h4><p>A function was implemented using Python to accept data and verify its validity with information stored in DynamoDB using Lambda. If the entered data exists in the DB, a ‘login success’ message is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*kqe4IBM9owRWnvJyxd2qNg.png" /></figure><p>Ensure ‘AmazonDynamoDBAccess’ and ‘LambdaDynamoDBExecutionRole’ are set for Lambda to access DynamoDB.</p><p><strong>Reference</strong> <br><a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.htm">https://docs.aws.amazon.com/lambda/latest/dg/welcome.htm</a></p><h4>Amazon API Gateway</h4><p>To link Amplify and the Lambda function, a GET method REST API was created using API Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*eu84ZYEOpTLrMP94rs-4kA.png" /></figure><p>In the JavaScript section of the index.html in the Github repository, the ‘url’ variable is where the API Gateway URL should be inserted.</p><p><strong>Reference</strong> <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html">https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html</a></p><h4>Accessing the Web</h4><p>Once all services are ready, the web is accessible and the alert returns to check whether the value is valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*hDAgtttJ384IQw9USEi9jg.png" /></figure><h3>Conclusion</h3><p>The advantages discovered while implementing a simple web using AWS Amplify and AWS services are as follows:</p><ol><li><strong>Easy Deployment and Management:</strong> AWS Amplify simplifies the deployment and management of web applications. Instead of manually handling complex tasks such as server settings and operations, web applications can be deployed and managed with a few clicks.</li><li><strong>High Performance:</strong> AWS Amplify delivers content quickly to users worldwide using a CDN (Content Delivery Network). In on-premises environments, additional work is required to set up and manage separate CDN services, but AWS has this feature built-in.<br> <br><strong>Reference</strong> <br><a href="https://aws.amazon.com/amplify/faqs/?nc1=h_ls">https://aws.amazon.com/amplify/faqs/?nc1=h_ls</a></li><li><strong>Scalability and Security of AWS Services: </strong>AWS services provide high scalability. Services like AWS’s Lambda, API Gateway, and DynamoDB show high integration and scalability, and access management between services is also possible using IAM. This enables tasks that are difficult in on-premises environments.</li></ol><p>The intention of this blog is not to definitively state that using Amplify is the best choice for building a web application over on-premise environments. Instead, it aims to share insights about the strengths of Cloud-Based Development Services in comparison to on-premise environments. Please feel free to share your thoughts and experiences in the comments below. Thank you for reading.</p><p>#MegazonCloud #AWS #Cloud #Cloudvillains #Amplify #Lambda #APIGateway #DynamoDB</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33bac76787ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/building-a-web-application-using-aws-amplify-and-aws-services-33bac76787ab">Building a Web Application Using AWS Amplify and AWS Services</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>