<?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[Stories by 김원중 on Medium]]></title>
        <description><![CDATA[Stories by 김원중 on Medium]]></description>
        <link>https://medium.com/@ki102501?source=rss-25d830e41467------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Em2usI7kQoe23Rr4YsUbFw.png</url>
            <title>Stories by 김원중 on Medium</title>
            <link>https://medium.com/@ki102501?source=rss-25d830e41467------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:35:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ki102501/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWS SageMaker를 활용한 LoRA 모델의 학습과 추론]]></title>
            <link>https://medium.com/toonsquare-tech/aws-sagemaker%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-lora-%EB%AA%A8%EB%8D%B8%EC%9D%98-%ED%95%99%EC%8A%B5%EA%B3%BC-%EC%B6%94%EB%A1%A0-e06f0f891051?source=rss-25d830e41467------2</link>
            <guid isPermaLink="false">https://medium.com/p/e06f0f891051</guid>
            <category><![CDATA[artficial-intelligence]]></category>
            <category><![CDATA[webtoon]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[김원중]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 04:16:50 GMT</pubDate>
            <atom:updated>2023-09-13T04:37:08.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcDAkfzXgo2suhMc3QBB5A.png" /><figcaption>Tooning Magic by Toonsquare</figcaption></figure><ul><li>이 글은 AWS SageMaker를 활용하여 Stable Diffusion을 LoRA(Low-Rank Adaptation of Large Language Models) 학습법으로 훈련, 추론, 배포하는 과정에 대해 다룹니다.</li><li>SageMaker의 편리한 기능과 강력한 자원 관리를 통해 어떻게 모델 학습 및 배포가 수월하게 이루어지는 지에 대해 설명합니다.</li></ul><h3>LoRA(Low-Rank Adaptation of Large Language Models)</h3><p>최근, 대규모 언어 모델은 자연어 처리 분야에서 높은 성과를 거두고 있습니다. 그러나 이러한 모델을 특정 작업에 맞게 조정하는 것은 비용과 GPU 리소스 측면에서 어려운 과제였습니다. 이를 해결하기 위한 방안으로 “LoRA: Low-Rank Adaptation of Large Language Models”라는 혁신적인 기술이 제안되었습니다.</p><h4>Stable Diffusion에서 LoRA 학습</h4><p>이 기술은 자연어 처리 분야의 모델뿐만 아니라 이미지 생성 모델인 Stable Diffusion의 fine tuning에서도 활용이 되었습니다. 사전 훈련된 모델의 가중치를 고정하고 일부 레이어에 학습 가능한 새로운 레이어 가중치를 주입하는 방식을 사용합니다. LoRA학습법으로 학습시 다양한 장점들이 있습니다.</p><ul><li>학습의 속도가 매우 빠릅니다.</li><li>컴퓨터 GPU 요구사항이 매우 낮습니다.</li><li>LoRA로 훈련된 모델의 크기는 매우 작습니다.</li></ul><p>LoRA는 사전 훈련된 모델의 가중치를 동결하고 추가로 학습하는 레이어만을 가지기 때문에 모델이 학습할 파라미터의 수가 크게 줄어들어 학습 속도가 매우 빠르며, Gradient 계산이 줄어들어 GPU 메모리 요구사항이 크게 감소합니다. Stable Diffusion 모델이 2 ~ 3GB로 무거운 것에 비해 LoRA 모델은 3MB 정도로 가볍습니다.</p><h3>SageMaker를 통한 모델 학습</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*IsRPvmEBpjntgIeAOsJ5zQ.png" /><figcaption>SageMaker를 통한 모델 학습</figcaption></figure><p>학습할 이미지와 텍스트 데이터가 한 쌍으로 묶인 데이터 셋을 S3 버킷에 업로드 합니다. 학습을 진행하기 위해 S3에 업로드 한 데이터셋을 가져오고 Hugging Face에서 LoRA 모델의 base 모델이 될 Stable diffusion 모델을 가져옵니다. 해당 모델을 LoRA로 학습하기 위하여 Github에서 kohya_ss 레포를 clone 합니다.</p><h4>데이터 준비</h4><p>데이터 셋에는 동일한 파일 이름을 가진 이미지와 그것을 설명하는 텍스트 파일이 필요합니다. 예를 들어 1.jpg 파일과 1.txt 파일이 한 쌍으로 존재하고 1.txt 파일은 1.jpg를 설명하는 텍스트가 들어있어야 합니다.</p><h4>환경 설정 및 GUI 세팅</h4><p>SageMaker studio launcher에서 environment를 설정한 후 Open image terminal을 클릭하여 터미널을 열어줍니다.</p><p>저의 경우 Python3.10 버전을 사용하기 위해 Image에서 Base Python 3.0을 선택하였고 학습시 GPU를 사용하기 위해 Instance type을 ml.g4dn.xlarge를 선택하여 터미널을 열었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*orCBSgJWUqln-6EprV4kfA.png" /><figcaption>envrionment setting</figcaption></figure><p>터미널이 열렸으면 <a href="https://github.com/bmaltais/kohya_ss.git">kohya_ss repo</a>를 클론합니다. <br>kohya_ss 폴더로 이동한 후 생성한 environment에 학습 관련 dependency를 설치하기 위해 setup.sh 파일을 실행시킵니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiqY6fepX6VV4JnIeY6Eiw.png" /><figcaption>setup</figcaption></figure><p>설치가 완료 된 후에 accelerate config를 입력하여 accelerate configure를 세팅해줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZS4yJJ8akOmqayGzAsDGw.png" /><figcaption>accelerate configure</figcaption></figure><ol><li><strong>This machine</strong></li><li><strong>No distributed training</strong></li><li><strong>no</strong></li><li><strong>no</strong></li><li><strong>no</strong></li><li><strong>all</strong></li><li><strong>fp16</strong></li></ol><p>후에 bash gui.sh를 입력하여 gui URL이 생성되면 Running on public URL을 클릭하여 gui를 open합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlhiC2QtvCg-Gxlbea8Znw.png" /><figcaption>gui open</figcaption></figure><h4>학습 세팅</h4><p>자세한 학습 세팅 가이드는 <a href="https://github.com/bmaltais/kohya_ss">repository</a>에 있는 영상들을 참고해주세요.</p><ol><li>LoRA 탭 -&gt; Training 탭 -&gt; Source model 탭으로 진입하여 Model Quick Pick을 custom으로 변경해주고 Pretrained model name or path를 지정해줍니다.<br>(터미널에서 gui.sh를 실행시킨 위치가 본인의 위치입니다.<br>ex) <strong>/</strong>root/kohya_ss/source_model/StableDiffusion.ckpt)</li><li>Tools 탭 -&gt; Deprecated 탭 -&gt; Dreambooth/LoRA Folder preparation 탭으로 이동합니다.<br>모든 입력창을 입력한 후 Prepare training data 클릭하면 Training 탭 내부에 Folders 입력창이 자동으로 작성됩니다.</li><li>Parameters 탭으로 진입하여 원하는 파라미터들을 입력해줍니다.</li><li>모든 입력을 마친 후 Configuration file 탭에서 경로를 입력해주고 Save 버튼을 클릭합니다. 세팅한 모든 값들이 json 파일로 저장이 되며, 해당 json 파일을 load를 해주면 자동으로 세팅값들이 입력됩니다. 따라서 파라미터를 변경하면서 학습하기에 용이합니다.</li></ol><h4>학습</h4><pre>ImportError: libGL.so.1: cannot open shared object file: No such file or directory</pre><p>라는 에러가 발생한다면 apt install libgl1-mesa-glx 커맨드를 통해 “libgl1-mesa-glx” 패키지를 설치하고 다시 학습을 진행합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTXHPeqJh6YWpPGvtXtLaA.png" /><figcaption>학습 진행 중</figcaption></figure><p>epoch가 진행 될 때마다 지정해 놓은 output 폴더에 LoRA 모델이 저장이 됩니다. 생성된 LoRA 모델과 base 모델을 S3에 저장을 하여 효율적으로 관리할 수 있습니다.</p><h3>SageMaker를 통한 모델 추론</h3><p>학습한 LoRA 모델을 추론하기 위해서 diffusers 라이브러리를 사용하였습니다.</p><p>해당 모델을 추론하고 배포하기 위해 inference.py를 작성합니다. inference.py에는 input_fn, model_fn, predict_fn, output_fn 함수들이 있습니다.</p><h4>input_fn</h4><pre>import argparse<br>import torch<br>import base64<br>import io<br>import os<br>import json<br>from safetensors.torch import load_file<br>from diffusers import StableDiffusionPipeline<br><br>def input_fn(request_body, request_content_type=&#39;application/json&#39;):<br>    &#39;&#39;&#39;<br>    모델에 입력 데이터를 전달하는 함수<br>    request_content_type=&#39;application/json&#39;로 받았기 때문에 클라이언트에서 json으로 받아옴<br>    따라서 해당 request_body를 return함<br>    &#39;&#39;&#39;<br><br>    return request_body</pre><h4>model_fn</h4><pre>def model_fn(model_dir):<br>    &#39;&#39;&#39;<br>    base model를 load하여 pipeline을 생성하고 lora를 load하여 가중치를 입힘<br>    base_model_dir: base model 파일의 경로<br>    lora_model_dir: lora model 파일의 경로<br>    lora_weight: 얼마나 loar의 가중치를 pipeline에 입힐 것인지<br>    &#39;&#39;&#39;<br>    base_model_path = os.path.join(model_dir, &#39;base_model.ckpt&#39;)<br>    lora_model_path = os.path.join(model_dir, &#39;lora_model.safetensors&#39;)<br>    <br>    pipeline = StableDiffusionPipeline.from_single_file(<br>        base_model_path,<br>        torch_dtype=torch.float16<br>    ).to(&quot;cuda&quot;)<br>    <br>    pipeline = load_lora_weights(pipeline, lora_model_path, 0.5)<br><br>    return pipeline</pre><p>diffusers의 from_single_file 이라는 함수를 통해 base 모델을 불러오고 pipeline을 생성합니다. 그리고 load_lora_weights 함수를 통해 LoRA 모델의 가중치를 설정하여 pipeline에 입힐 수 있습니다.</p><p><strong>load_lora_weights</strong></p><pre>def load_lora_weights(pipeline, checkpoint_path, weight):<br>    &#39;&#39;&#39;<br>    lora 모델을 load 함<br>    pipeline: diffusers.StableDiffusionPipeline을 통해서 base 모델을 로드하여 생성<br>    checkpoint_path: lora model의 path<br>    weight: lora의 weight를 얼마나 줄지 정함<br>    &#39;&#39;&#39;<br>    pipeline.to(&quot;cuda&quot;)<br>    LORA_PREFIX_UNET = &quot;lora_unet&quot;<br>    LORA_PREFIX_TEXT_ENCODER = &quot;lora_te&quot;<br>    alpha = weight<br><br>    state_dict = load_file(checkpoint_path, device=&quot;cuda&quot;)<br>    visited = []<br><br>    for key in state_dict:<br>        if &quot;.alpha&quot; in key or key in visited:<br>            continue<br><br>        if &quot;text&quot; in key:<br>            layer_infos = key.split(&quot;.&quot;)[0].split(LORA_PREFIX_TEXT_ENCODER + &quot;_&quot;)[-1].split(&quot;_&quot;)<br>            curr_layer = pipeline.text_encoder<br>        else:<br>            layer_infos = key.split(&quot;.&quot;)[0].split(LORA_PREFIX_UNET + &quot;_&quot;)[-1].split(&quot;_&quot;)<br>            curr_layer = pipeline.unet<br><br><br>        temp_name = layer_infos.pop(0)<br>        while len(layer_infos) &gt; -1:<br>            try:<br>                curr_layer = curr_layer.__getattr__(temp_name)<br>                if len(layer_infos) &gt; 0:<br>                    temp_name = layer_infos.pop(0)<br>                elif len(layer_infos) == 0:<br>                    break<br>            except Exception:<br>                if len(temp_name) &gt; 0:<br>                    temp_name += &quot;_&quot; + layer_infos.pop(0)<br>                else:<br>                    temp_name = layer_infos.pop(0)<br><br>        pair_keys = []<br>        if &quot;lora_down&quot; in key:<br>            pair_keys.append(key.replace(&quot;lora_down&quot;, &quot;lora_up&quot;))<br>            pair_keys.append(key)<br>        else:<br>            pair_keys.append(key)<br>            pair_keys.append(key.replace(&quot;lora_up&quot;, &quot;lora_down&quot;))<br><br><br>        if len(state_dict[pair_keys[0]].shape) == 4:<br>            weight_up = state_dict[pair_keys[0]].squeeze(3).squeeze(2).to(torch.float32)<br>            weight_down = state_dict[pair_keys[1]].squeeze(3).squeeze(2).to(torch.float32)<br>            curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)<br>        else:<br>            weight_up = state_dict[pair_keys[0]].to(torch.float32)<br>            weight_down = state_dict[pair_keys[1]].to(torch.float32)<br>            curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down)<br><br><br>        for item in pair_keys:<br>            visited.append(item)<br><br>    return pipeline</pre><h4>predict_fn</h4><pre>def predict_fn(request_body, pipeline):<br>    &#39;&#39;&#39;<br>    pipeline에 request_body input으로 주어 inference를 함<br>    request_body: input_fn에서 받은 data<br>    pipeline: base 모델과 lora 모델의 가중치가 입힌 pipeline<br>    <br>    prompt: 이미지로 생성될 프롬프트<br>    negative_prompt: 이미지로 생성되지 말아야 할 프롬프트<br>    width: 가로 길이<br>    height: 세로 길이<br>    num_inference_steps: 추론 step 수<br>    num_images_per_prompt: 생성할 이미지의 수<br>    seed: seed<br>    &#39;&#39;&#39;<br>    input_data = json.loads(request_body)<br>    <br>    prompt = input_data[&#39;prompt&#39;]<br>    negative_prompt = input_data[&#39;negative_prompt&#39;]<br>    width = input_data[&#39;width&#39;]<br>    height = input_data[&#39;height&#39;]<br>    num_inference_steps = input_data[&#39;num_inference_steps&#39;]<br>    num_images_per_prompt = input_data[&#39;num_images_per_prompt&#39;]<br>    generator = torch.manual_seed(input_data[&#39;seed&#39;])<br>    <br>    prediction = pipeline(<br>        prompt=prompt, <br>        negative_prompt=negative_prompt, <br>        width=width, <br>        height=height, <br>        num_inference_steps=num_inference_steps, <br>        num_images_per_prompt=num_images_per_prompt,<br>        generator=generator,<br>    ).images<br><br>    return prediction</pre><h4>output_fn</h4><pre>def output_fn(prediction, accept=&#39;application/json&#39;):<br>    &#39;&#39;&#39;<br>    추론 결과를 client에게 반환<br>    1. PIL.Image.Image를 바이트로 변환<br>    2. 이미지를 base64로 인코딩<br>    2. 인코딩된 문자열을 response로 포함하는 json 형식으로 생성<br>    3. json을 return<br>    prediction: 모델의 추론 결과<br>    accept: 클라이언트가 원하는 응답 컨텐츠 타입<br>    &#39;&#39;&#39;<br>    encoded_images = []<br>    <br>    for image in prediction:<br>        img_byte_array = io.BytesIO()<br>        image.save(img_byte_array, format=&#39;PNG&#39;)<br>        img_byte_array = img_byte_array.getvalue()<br>        <br>        base64_image = base64.b64encode(img_byte_array).decode(&#39;utf-8&#39;)<br>        encoded_images.append(base64_image)<br>    <br>    response = {<br>        &#39;base64&#39; : encoded_images<br>    }<br><br>    return json.dumps(response)</pre><h4>추론 결과</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YjnZsGTDWuDe3ItGy4fGg.png" /><figcaption>Tooning Magic by Toonsquare</figcaption></figure><h3>SageMaker를 통한 모델 배포</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*51qpiJDS8HfuXFN7jRCmxg.png" /><figcaption>SageMaker를 통한 모델 배포</figcaption></figure><p>SageMaker를 통해 inference container를 구성하고 학습한 모델을 배포하여, SageMaker endpoint를 생성합니다. endpoint에서 생성된 log들은 CloudWatch에 기록됩니다. Client는 API Gateway를 통해 SageMaker endpoint와 통신하며 모델이 추론한 결과를 전달받습니다.</p><h4>SageMaker 엔드포인트 생성</h4><p>SageMaker를 이용하여 모델을 배포하고 endpoint를 쉽게 생성할 수 있습니다.</p><ul><li>code(requirements.txt, inference.py)폴더와 모델 파일들 tar로 압축</li></ul><p>tar -czvf model.tar.gz base_model.ckpt lora_model.safetensors code</p><ul><li>AWS 리전 출력 및 IAM 역할 지정</li></ul><pre>import os<br>import boto3<br>import sagemaker<br>from sagemaker import get_execution_role<br><br># 현재 AWS 계정의 리전을 가져와 region에 저장<br>region = boto3.Session().region_name<br><br># Sagemaker 작업을 실행하는 데 사용할 IAM 역할을 가져와 role 변수에 저장<br>role = get_execution_role()</pre><ul><li>Sagemaker에서 자동 생성된 S3 버킷으로 model.tar.gz 파일 복사</li></ul><pre># Sagemaker에서 자동으로 생성된 기본 s3 버킷을 가져옴<br># Sagemaker Python SDK로 생성한 것으로 sagemaker에서 사용할 수 있도록 사전 구성된 것)<br>bucket = sagemaker.Session().default_bucket()<br><br># model.tar.gz 파일을 SageMaker에서 가져온 기본 버킷으로 복사함<br>!aws s3 cp model.tar.gz s3://$bucket/model.tar.gz</pre><ul><li>Pytorch 모델을 SageMaker에서 배포 및 호스팅하기 위한 설정 및 정의</li></ul><pre>from sagemaker.pytorch import PyTorchModel<br><br># S3 버킷을 사용해서 모델 아티팩트의 경로를 지정함(model.tar.gz)<br>model_path = &#39;s3://{}/model.tar.gz&#39;.format(bucket)<br><br># 모델 배포<br># PyTorchModel 클래스를 사용하여 pytorch 모델을 정의함<br># model_data = 모델 아티팩트의 s3 경로<br># role = sagemaker 작업을 수행하는 데 사용되는 IAM 역할<br># entry_point = 모델 추론을 수행하기 위한 python script<br># framework_version = pytorch 프레임워크 버전 지정<br># py_version = python 버전 지정<br>pytorch_model = PyTorchModel(model_data=model_path,<br>                             role=role,<br>                             entry_point=&#39;inference.py&#39;,<br>                             framework_version=&quot;2.0.0&quot;,<br>                             py_version=&quot;py310&quot;)</pre><ul><li>Pytorch 모델을 SageMaker에서 배포하고 추론을 위한 predictor 생성</li></ul><pre>from sagemaker.deserializers import JSONDeserializer<br>from sagemaker.serializers import JSONSerializer<br>from sagemaker.serializers import IdentitySerializer<br>from sagemaker.deserializers import BytesDeserializer<br>from sagemaker.deserializers import NumpyDeserializer<br><br># Sagemaker 모델을 배포하고 호스팅 엔드포인트 생성<br># instance_type = 호스팅 할 EC2 인스턴스 유형을 지정<br># initial_instance = 호스팅할 인스턴스 수를 지정<br># serializer = 입력 데이터를 어떻게 직렬화할 지 정의<br># deserializer = 생성된 predictor의 정보를 출력함<br>predictor = pytorch_model.deploy(<br>    instance_type=&#39;ml.g4dn.xlarge&#39;,<br>    initial_instance_count=1,<br>    serializer=IdentitySerializer(content_type=&#39;application/json&#39;),<br>    deserializer=JSONDeserializer()<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7vduApdVKMxAWYxPNtRzw.png" /><figcaption>엔드포인트 생성</figcaption></figure><h3>SageMaker를 통한 endpoint 운영</h3><h4>Auto Scaling</h4><p>SageMaker는 auto scaling을 통해 엔드포인트에 대한 트래픽이 늘어나면 자동으로 인스턴스의 수를 확장하고, 트래픽이 감소하면 자동으로 축소하여 엔드포인트를 관리고 비용을 절감합니다.</p><p>엔드포인트의 설정 탭에서 auto scaling을 적용할 엔드포인트를 선택하고 자동 조정 구성을 누릅니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZYslqh4A3O6FvQq3sHk8A.png" /></figure><p>자신의 상황에 맞게 auto scaling의 구성 항목들을 작성합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*-fOFGQ2LpNBEsP6rgdfTMQ.png" /></figure><p>저장을 하면 auto scaling이 적용된 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Go0ZgiBJLHeoayMqYfLWOw.png" /></figure><p>이를 통해 트래픽의 변동에 따라 인스턴스를 자동으로 확장하거나 축소하여 엔드포인트를 효율적으로 관리할 수 있습니다.</p><h4>CloudWatch 통합</h4><p>SageMaker는 CloudWatch와 통합되어있어 로그 및 지표를 모니터링하고 대시보드를 사용하여 엔드포인트의 상태를 시각화할 수 있습니다.</p><p>엔드포인트 탭을 들어가면 모델 컨테이너 로그 링크가 있는데, 이를 통해 쉽게 CloudWatch로 연결되어 엔드포인트의 로그를 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWO04xaGfh3Gv8U217NVTw.png" /></figure><h3>결론</h3><p>이 글에서는 AWS SageMaker를 활용해 LoRA 모델의 학습, 추론, 배포하는 프로세스를 살펴보았습니다. SageMaker의 사용은 모델을 개발하고 배포하는 과정을 간소화 하였고 작업 비용과 시간을 낮추었습니다.</p><p>LoRA 학습법은 속도가 빠르고 모델이 가벼우며 GPU 요구사항이 낮다는 장점이 있습니다. 그리고 SageMaker를 통해 학습 데이터를 관리하고 환경 설정을 간편히 할 수 있었습니다. 또한, 추론 단계에서는 SageMaker의 모델 배포 기능을 활용하여 결과를 쉽게 얻을 수 있었습니다.</p><p>SageMaker의 Auto Scaling 및 CloudWatch 통합은 엔드포인트의 운영 효율을 높이는 데 도움이 되었습니다. 이 밖에 Experiments, pipelines, inference recommender 등 SageMaker의 다양한 기능들을 숙지하고 활용한다면 AI 모델 개발은 보다 효율적이고 간편해질 것입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e06f0f891051" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/aws-sagemaker%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-lora-%EB%AA%A8%EB%8D%B8%EC%9D%98-%ED%95%99%EC%8A%B5%EA%B3%BC-%EC%B6%94%EB%A1%A0-e06f0f891051">AWS SageMaker를 활용한 LoRA 모델의 학습과 추론</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating gifs using gif.js]]></title>
            <link>https://medium.com/toonsquare-tech/creating-gifs-using-gif-js-c70d04ad3e00?source=rss-25d830e41467------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70d04ad3e00</guid>
            <dc:creator><![CDATA[김원중]]></dc:creator>
            <pubDate>Fri, 12 May 2023 05:47:06 GMT</pubDate>
            <atom:updated>2023-05-12T08:38:43.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Gif image made by tooning.io" src="https://cdn-images-1.medium.com/max/540/1*yKkegrlOGA4vo-pyw9ajWQ.gif" /><figcaption>gif</figcaption></figure><h4>Here’s how to use gif.js:</h4><ol><li>Download gif.js from the github repository.</li><li>Put gif.js and gif.worker.js from the dist folder into your project folder.</li><li>Import gif.js into your project.</li><li>Create a gif instance.</li><li>Load the worker using the workerScript option in the gif constructor.</li><li>Add frames to the gif instance using the gif.addFrame method.</li><li>Finish the gif instance using gif.on(‘finished’, callBackFn).</li><li>Render the gif using the gif.render method.</li></ol><p>By following these steps, you can easily create gifs using gif.js.</p><h4>The formats that can be added to frames in gif.js</h4><ul><li>ImageElement<br><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement">https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement</a><br>gif.addFrame(imageElement);</li><li>CanvasElement<br><a href="https://developer.mozilla.org/ko/docs/Web/API/HTMLCanvasElement">https://developer.mozilla.org/ko/docs/Web/API/HTMLCanvasElement</a><br>gif.addFrame(canvasElement);</li><li>CanvasContext<br><a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D</a><br>gif.addFrame(ctx);</li></ul><p>You can add frames to your gif by selecting the format that is easy for you to use and desired for your purposes.</p><h4>Options for creating a Gif instance:</h4><ul><li>repeat: Sets the number of times the GIF should repeat. A value of -1 indicates a single loop, while a value of 0 indicates an infinite loop.</li><li>quality: Used to specify the sampling frequency of the GIF image. Pixel sample interval indicates the spacing between pixel samples, with higher values resulting in lower image quality. For example, a pixel sample interval of 1 includes every pixel, while a value of 2 only includes every second pixel. This reduces the file size of the GIF image, but can result in lower quality.</li><li>workers: Sets the number of web workers to be used by the web application.</li><li>workerScript: Sets the path to the gif.worker.js file.</li><li>background: This property did not work when I tried to use it.</li><li>width: Sets the width of the generated GIF.</li><li>height: Sets the height of the generated GIF.</li><li>transparent: Sets the hex value of the color to be used as transparency in the generated GIF.</li><li>dither: Sets the dithering method. Dithering is a technique used in image processing to create the illusion of high color depth in images with a limited color palette. <br>Dithering works by mixing the colors of the image in a fixed pattern, which allows more color information to be added to the image. Available dithering methods include Floyd-Steinberg, False Floyd-Steinberg, Stucki, and Atkinson.</li><li>debug: Sets whether debug information should be output to the console.</li></ul><h4>Options for addFrame method:</h4><ul><li>delay: Time interval between frames.</li><li>copy: Indicates whether to copy the pixel data.</li><li>dispose: Specifies how to handle a portion of the previous frame in the current frame.</li></ul><h4>Issue</h4><figure><img alt="image has red line" src="https://cdn-images-1.medium.com/max/431/1*R4hTa8PXYeWGiA-i5hqzKA.png" /></figure><p>GIF images do not support transparent pixels. Therefore, when gif.js handles transparent pixels in a PNG image, it converts them to opaque black (rgb(0,0,0)) and removes the transparent pixel information. If you specify #000000 for the transparent property, all black parts will be transparent. However, in this case, not all black parts disappear cleanly and some of them remain slightly messy and transparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*3TxP1IUpr0zbaHXtVWLLpg.jpeg" /><figcaption><a href="https://github.com/jnordberg/gif.js/issues/100">https://github.com/jnordberg/gif.js/issues/100</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXT1kk5DY7hsBQiwwLEXYw.jpeg" /><figcaption><a href="https://github.com/jnordberg/gif.js/issues/82">https://github.com/jnordberg/gif.js/issues/82</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9p3WEyUitbpdEUAezq88g.png" /><figcaption>If the transparent option is set to red on a red background</figcaption></figure><h4>Cause</h4><p>The GIF format only supports <em>1-bit transparency</em>. However, the edges of PNG images contain alpha values that are not 0 or 255, but values such as 17, 89, 214, and so on. Therefore, if you use an image where every pixel is either completely opaque or completely transparent, you can solve this issue.</p><p>What is “<em>1-bit transparency</em>”?<br>“1-bit transparency” is often used to describe the method of representing transparency in GIF (Graphics Interchange Format) files. GIF is a bitmap image format that uses an 8-bit color table to represent up to 256 different colors. One of these colors can be set as transparent, and the transparency information used for this is 1-bit. This means that each pixel can only have one of two states: completely opaque or completely transparent. This lack of partial transparency for each pixel can result in unnatural results for images with opaque edges, making GIF’s 1-bit transparency one of its limitations. In contrast, more recent image formats such as PNG (Portable Network Graphics) support an alpha channel that allows each pixel to have varying levels of transparency. These formats provide a more natural appearance for transparent areas of an image.</p><h4>Fix</h4><p>To resolve this issue, the canvas was traversed pixel by pixel, and if the alpha value was less than 220, the rgb value of that pixel was modified to rgba(255, 0, 0, 255). The pixels in the canvas were modified to be completely transparent or completely opaque, and the gif transparent option was set to red to create a clean, transparent GIF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvpVbL7Oq4ljd1sSAkHZ3A.gif" /><figcaption>Output gif after fixing the issue</figcaption></figure><p>gif.js demo link: <a href="https://jnordberg.github.io/gif.js/">https://jnordberg.github.io/gif.js/</a></p><p>gif.js github link: <a href="https://github.com/jnordberg/gif.js">https://github.com/jnordberg/gif.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70d04ad3e00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/creating-gifs-using-gif-js-c70d04ad3e00">Creating gifs using gif.js</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction of line drawing]]></title>
            <link>https://medium.com/@ki102501/%EC%84%A0%ED%99%94-%EB%8F%84%EC%9E%85-503e51ccb186?source=rss-25d830e41467------2</link>
            <guid isPermaLink="false">https://medium.com/p/503e51ccb186</guid>
            <dc:creator><![CDATA[김원중]]></dc:creator>
            <pubDate>Fri, 28 Oct 2022 04:14:21 GMT</pubDate>
            <atom:updated>2022-10-28T06:05:09.438Z</atom:updated>
            <content:encoded><![CDATA[<p>Cartoonist Jeon Seon-wook’s webtoon ‘Free Draw’ is gaining popularity due to its solid storyline and excellent drawing.</p><p>The reason he was able to draw such a realistic background was because he used real photos. he was drawing the background by first taking an actual photo, creating a line drawing for the background, and then retouching it using Photoshop.</p><p><a href="https://youtu.be/YhCNnj9xjTs">https://youtu.be/YhCNnj9xjTs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*0M2frBzBnXnriSmUQjRF5g.png" /><figcaption>출처: <a href="https://ekessy.tistory.com/185">https://ekessy.tistory.com/185</a></figcaption></figure><p>Referring to the work method of the cartoonist, we introduced a line drawing service so that users of Tooning can create a background similar to the real background. Tooning’s line drawing service is implemented using openCV and converts images into line drawing with one click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTPn4n5vBeZfY9o5kjR3Tw.jpeg" /><figcaption>Line of Tooning</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RC5-LOnuC-jzaz4X9RPtAw.jpeg" /><figcaption>Line of Tooning</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbiVv5qyxWFPJxVBtOhHYQ.jpeg" /><figcaption>Line of Tooning</figcaption></figure><p>Because the line drawing service is done through a computer, it is not yet possible to draw lines as precisely as Jeon Seon-wook’s work method. Since it is currently version 1.0, there are various issues. However, features such as drawing a line according to the user’s choice or adjusting the thickness of the line are functions that should be provided additionally as the version is upgraded.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=503e51ccb186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction of ffmpeg.wasm for GIF]]></title>
            <link>https://medium.com/toonsquare-tech/introduction-of-ffmpeg-wasm-31fb057293ba?source=rss-25d830e41467------2</link>
            <guid isPermaLink="false">https://medium.com/p/31fb057293ba</guid>
            <category><![CDATA[toonsquare]]></category>
            <category><![CDATA[tooning]]></category>
            <category><![CDATA[gif]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[wasm]]></category>
            <dc:creator><![CDATA[김원중]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 07:27:01 GMT</pubDate>
            <atom:updated>2022-10-26T07:26:34.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRupl832SyuFoaYEdgBrGg.gif" /><figcaption>Gif of Tooning</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rcb-pJrvTJG0svd8VhQAw.gif" /><figcaption>GIF of Tooning</figcaption></figure><p>This post will be written in the order of the issues that occurred when ffmpeg.wasm was introduced and the process of solving those issues.</p><p>First of all, ffmpeg is a multimedia framework in C language that helps you easily decode, encode, transform, mux, demux, and stream videos, etc.</p><p>It is ffmpeg.wasm that compiles these ffmpegs into WebAssembly, making ffmpeg easy to use even in your browser.<br><a href="https://github.com/ffmpegwasm/ffmpeg.wasm">https://github.com/ffmpegwasm/ffmpeg.wasm</a></p><p>We decided to introduce ffmpeg.wasm to generate the gif &amp; mp4 file. But in the process of introducing this, three problems arose.</p><ol><li>Cross Origin Isolated Settings</li><li>Transparent background for GIF files</li><li>The first frame combines with the second frame</li></ol><h3>1. Cross Origin Isolated Settings</h3><p>First of all, ffmpeg.wasm has a multi-threaded version and a single-threaded version.</p><p>The multithreaded version requires SharedArrayBuffer. To use it, you must be in Cross Origin Isolated state, which is disabled by default in chrome 92.<br>Shared Array Buffer <a href="https://caniuse.com/sharedarraybuffer">Click here</a> to see available browser-specific versions.</p><p>A more detailed explanation of the Cross Origin policy can be found at the link below.</p><ul><li><a href="https://web.dev/coop-coep/">Making your website &quot;cross-origin isolated&quot; using COOP and COEP</a></li><li><a href="https://web.dev/why-coop-coep/">Why you need &quot;cross-origin isolated&quot; for powerful features</a></li></ul><p>This CrossOriginIsolated state blocked the loading of Iframe on our page and caused a problem preventing social login pop-ups from interacting.</p><h3>Use the single-threaded version of ffmpeg.wasm</h3><p>So we decided to use the single thread version instead of the multi thread version of ffmpeg.wasm. A few manual tasks are required to use the single thread version.<br>The detailed guide for the single thread version is shown in <a href="https://github.com/ffmpegwasm/ffmpeg.wasm/issues/137#issuecomment-1014956114">the link</a>, but I’ll explain it briefly again.</p><p>1. Fork the repository. <a href="https://github.com/ffmpegwasm/ffmpeg.wasm-core">https://github.com/ffmpegwasm/ffmpeg.wasm-core</a><br>2. Activate the github action by pushing the dummy commit. (It takes about an hour and 10 minutes.)<br>3. After the action is finished, artifacts are created and you can download it. (The single thread version is indicated in the action.)</p><p>After unzipping, the single thread version has core files and wasm files, and the multi-thread version has three files up to worker.<br>Specify the path of the downloaded core and enter “mainName”.</p><pre>const ffmpeg = createFFmpeg({<br>  corePath: &#39;./&lt;path-to-ffmpeg-core-dist&gt;/ffmpeg-core.js&#39;,<br>  mainName: &#39;main&#39;<br>});</pre><h3>2. Transparent background for GIF files</h3><p>I thought it was over, but I found an issue where the background appeared black when I created a gif with a png file with an alpha value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2BAb3t_3gpUruSW_mt2Ag.gif" /><figcaption>GIF created with black background</figcaption></figure><p>Unfortunately, it was an issue that appeared because GIF does not have an alpha channel. After many tries, I was able to solve the issue using palette.</p><h3>Use Palette</h3><p><a href="http://underpop.online.fr/f/ffmpeg/help/palettegen.htm.gz">“palettegen</a>” and “<a href="http://underpop.online.fr/f/ffmpeg/help/paletteuse.htm.gz">paletteuse</a>” and <a href="https://stackoverflow.com/questions/53566442/ffmpeg-gif-with-transparency-from-png-image-sequence">stackOverFlow</a> with help are at that link.</p><p>Here’s a brief explanation of how to fix it.<br>1. Execute ffmpeg run to receive png files to make a gif as input.<br>2. Create palette.png file using “palettegen”.<br>(Here, use the palettegen=reserve_transparent=1 option.)<br>3. Execute ffmpeg run to receive png files and the previously created palette file as inputs.<br>4. Use paletteuse=alpha_threshold=128 option.<br>5. Create a gif</p><p>There is also a slight problem here, that is, it ends when you run ffmpeg once. Therefore, there is a hassle of having to init every time you run ffmpeg run. I’m guessing that this problem occurs because it uses a single thread.</p><h3>3. The first frame combines with the second frame</h3><p>The last problem I encountered is that the first frame is combined with the second frame to create a gif.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMGiqrTokWhHAc0hmhAE4g.gif" /><figcaption>A gif created by combining the first and second frames</figcaption></figure><p>I googled the cause of the issue in various ways and found <a href="https://trac.ffmpeg.org/ticket/7902">the same issue</a> in the ffmpeg community.<br>The code in question is the “gif_image_write_imag”e function in the “libavcodec/gif.c” file, pointing out that the problem is that the processing of the first frame is unconditionally set to combine. Therefore, when you generate a transparent gif, you explain that the first frame is not disposed, but is created by combining.</p><p>This code has already been modified and merged into the ffmpeg code, so there was no problem when using ffmpeg. However, the ffmpeg version used to build the core in ffmpeg.wasm was <a href="https://github.com/ffmpegwasm/ffmpeg.wasm-core/blob/n4.3.1-wasm/libavcodec/gif.c">the version before</a> the above code was modified, so this issue occurred.</p><h3>After modifying the code, build ffmpeg.wasm-core</h3><ol><li>Fork the repository. <a href="https://github.com/ffmpegwasm/ffmpeg.wasm-core">https://github.com/ffmpegwasm/ffmpeg.wasm-core</a></li><li>Modify the code in the gif_image_write_image function in the libavcodec/gif.c file.</li></ol><pre><strong>-</strong>    if (!s-&gt;image &amp;&amp; <strong>avctx-&gt;frame_number &amp;&amp;</strong> is_image_translucent(avctx, buf, linesize)) {</pre><pre><strong>+ </strong>   if (!s-&gt;image &amp;&amp; is_image_translucent(avctx, buf, linesize)) {</pre><p>3. Activate the github action by commit &amp; push.</p><p>4. After the action is finished, artifacts are created and download. (The single thread version is indicated in the action.)</p><p>5. As described above, you can specify the path of the core and enter mainName.</p><p>If you want to skip this process and receive the modified core file, you can download it from the action tab of <a href="https://github.com/monkeykim111/ffmpeg.wasm-core/actions">the repository.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixhDkBLeppRzRqwznXcdiw.gif" /><figcaption>GIF with issue resolved</figcaption></figure><p>While introducing ffmpeg.wasm, I faced various problems, but I learned a lot while solving them.<br>Even though single thread was used, I was impressed by the unique speed of WebAssembly and I wanted to introduce multi-threading as soon as possible. <br>Now I’m only using gif among the many functions of ffmpeg, but I’m planning to introduce more various functions, and I’ll post it again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31fb057293ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/introduction-of-ffmpeg-wasm-31fb057293ba">Introduction of ffmpeg.wasm for GIF</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate images by using StyleGAN2]]></title>
            <link>https://medium.com/toonsquare-tech/generate-images-by-using-stylegan2-bc09ea284c65?source=rss-25d830e41467------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc09ea284c65</guid>
            <dc:creator><![CDATA[김원중]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 02:49:22 GMT</pubDate>
            <atom:updated>2022-10-19T02:12:22.709Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“GAN은 최근 10년간 머신러닝 분야에서 가장 멋진 아이디어다 -Yann LeCun”</blockquote><p>2014년 이안 굿펠로우가 GAN(Generative Adversarial Network, 적대적 생성 네트워크)을 발표하여 세상을 놀라게 한 후, 현재까지 이 기술은 다양하고 빠른 속도로 발전해왔습니다.</p><p>이번 포스팅에선 2020년 NVIDIA에서 발표한 StyleGAN2에 대해 알아보도록 하겠습니다.</p><blockquote>Index</blockquote><ol><li>GAN</li><li>PGGAN</li><li>StyleGAN</li><li>StyleGAN2-ada</li></ol><p>StyleGAN2를 알아보기 앞서 초기 모델인 GAN에서부터 StyleGAN의 기반이 되는 PGGAN에 대해 간략하게 알아보고, StyleGAN과 StyleGAN 2에 대해 자세히 알아보도록 하겠습니다.</p><blockquote>GAN(Generative Adversarial Neural network)</blockquote><p>GAN은 Generator(생성자)와 Discriminator(식별자) 두 개의 네트워크를 활용한 생성 모델입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*1ZJX6U2C-QpZhbhWs7ORUQ.png" /><figcaption>GAN 이미지 출처: <a href="http://mrkim.cloudy.so/board_KBEq62/175378">http://mrkim.cloudy.so/board_KBEq62/175378</a></figcaption></figure><p>위의 이미지는 GAN에 대해 설명을 할 때 많이 사용되는 경찰과 위조지폐범 예시입니다. 이 예시에서는 Generator가 위조지폐범이 될 것이고, Discriminator는 경찰이 될 것입니다.<br>위조지폐범은 지폐를 위조할 때 경찰이 속을 만한 지폐를 위조를 해야합니다. 그리고 경찰은 위조지폐범이 위조한 지폐를 진짜 지폐와 구별을 할 줄 알아야 합니다. 이러한 상황에서 위조지폐범은 경찰을 속이기 위해 더욱 더 정교하게 위조 지폐를 만들어 낼 것이고 반대로 경찰은 더욱 더 정교해지는 위조지폐를 구별하기 위해 각별한 주의를 기울여 구별을 할 것입니다. <br>이처럼 서로가 적대적인(Adversarial) 관계에서 경쟁을 하면서 학습을 진행해 나가는 것, 이것이 GAN에 대한 기본적인 개념입니다.</p><p>그렇다면 위의 예시를 Generator와 Discriminator에 대입하여 그 프로세스에 대해 알아보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*zIKkzUW7P1DA24WVA4ZOoA.jpeg" /><figcaption>GAN 출처: <a href="https://paperswithcode.com/method/gan">https://paperswithcode.com/method/gan</a></figcaption></figure><ol><li>Latent space에서 random하게 sampling된 noize vector가 Generator 네트워크에 들어가 이미지를 생성합니다.</li><li>Fake 이미지와 real 이미지는 Discriminator 네트워크에 들어가고 Discriminator는 해당 이미지가 real distribution(real data set)에서 왔는지를 1 ~ 0(real과 fake) 사이의 값으로 판단합니다.</li><li>Loss값을 구한 뒤에 backpropagation(역전파)을 통해 Generator와 Discriminator 네트워크 파라미터를 업데이트 합니다.</li></ol><blockquote>PGGAN(Progressive Growing GAN)</blockquote><p>다음으로는 PGGAN에 대해 간략하게 알아보도록 하겠습니다. 이름에서 알 수 있듯이 PGGAN의 핵심 idea는 점진적으로 네트워크에 layer를 붙여 나가면서 학습을 진행한다는 것입니다. 즉, 한 번에 전체 네트워크를 구성한 뒤 학습을 진행해 나가는 Feed forward 방식이 아니라, 초기 부분의 레이어(low resolution)에서 학습이 완료가 되면 레이어를 붙여 나가면서 높은 해상도(high resolution)까지 학습을 진행하는 방식입니다. 이러한 네트워크를 통해 1024 x 1024의 고해상도의 이미지도 생성할 수 있게 되었습니다.</p><p>PGGAN 네트워크를 보며 조금 더 자세히 알아보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*uI4cHkbwxROwiVYrexcZbQ.png" /><figcaption>PGGAN (PROGRESSIVE GROWING OF GANS FOR IMPROVED QUALITY, STABILITY, AND VARIATION)</figcaption></figure><ol><li>Latent space에서 noise vector가 random하게 sampling되어 Generator에 들어갑니다.</li><li>맨 처음 Generator는 4 x 4의 낮은 해상도의 이미지를 생성하는 네트워크로 학습이 진행됩니다.</li><li>Discriminator에 들어갈 real 이미지는 down sampling되어 4 x 4의 낮은 해상도로 바뀌게 됩니다.</li><li>Generator에 의해 생성된 4 x 4 fake 이미지와 down sampling된 4 x 4의 real 이미지는 Discriminator에 들어가며, 두 이미지를 비교하며 loss 값을 도출하게 됩니다.</li><li>Loss 값은 다시 Generator와 Discriminator로 back propagation되어 네트워크를 업데이트합니다.</li><li>이러한 방식으로 계속 학습이 이루어지며 Generator는 그럴 듯한 4 x 4 이미지를 생성할 수 있게 됩니다. 그 후에 8 x 8 이미지를 생성할 수 있는 네트워크로 학습이 진행되며, 궁극적으로 1024 x 1024의 높은 해상도의 이미지를 생성할 수 있게 됩니다.</li></ol><p>이러한 네트워크는 처음부터 1024 x 1024의 고해상도의 이미지 대신 4 x 4의 간단하고 생성하기 쉬운 네트워크부터 학습을 진행할 수 있다는 점에서 학습의 부담이 적어 좋은 성능을 낼 수 있다는 장점이 있습니다.</p><p>그러나 이미지의 특징 제어가 어렵다는 한계점이 있습니다. 고해상도의 이미지를 그럴듯하게 잘 만들어 낼 수 있었지만, 이미지의 특징들이 적절하게 분리 되어 있지 않았기 때문에, 여러 특징을 입히는 과정에서 좋은 성능을 보이지 못했습니다.<br>고해상도의 이미지를 생성하면서 여러 특징들을 적절히 분리하고, 자연스럽게 여러 특징을 입히기 위한 방안으로 StyleGAN이 등장하였습니다.</p><blockquote>StyleGAN(A Style-Based Generator Architecture for Generative Adversarial Networks)</blockquote><p>StyleGAN의 핵심 아이디어는 ‘고해상도의 이미지를 생성하면서 이미지의 특징들 까지 제어하자.’ 입니다. 이를 위해 StyleGAN은 특징들을 적절히 분리(disentanglement)시켜야 했고 이를 위해 Mapping network라는 개념을 사용합니다.</p><ul><li>Mapping network</li></ul><p>Mapping network는 특정한 space vector를 다른 space vector로 mapping하는 것을 의미합니다. 앞서 설명한 GAN 모델들은 일반적으로 latent space에서 random vector 를 sampling 한 뒤 그것을 Generator 네트워크에 넣어서 이미지를 생성하였습니다. 이렇게 되면 논문에서는 여러 특징들이 entanglement하게 되고 이미지의 특징들을 제어하기 어렵다고 설명하고 있습니다. 아래의 그림을 보며 자세히 알아보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ey8VqLiqzxNPFAY3NWjf_Q.png" /></figure><p>(a)는 training data set에 있는 특징들의 분포를 도식화 한 것이라고 하겠습니다. 이때 세로 축을 남성과 여성으로, 가로 축을 머리가 길고 짧은 특징의 분포라고 가정하겠습니다. 이렇게 되면 data set에는 머리가 길고 짧은 여성과 머리가 짧은 남성만이 존재하고 머리가 긴 남성의 data는 존재하지 않는다는 것을 알 수 있습니다.</p><p>(b)는 이러한 (a)data set을 가우시안 분포(정규분포)를 따르는 하나의 random vector z를 sampling 해서 Generator의 입력으로 넣을 때를 도식화 한 것입니다. 그림을 보아도 쉽게 알 수있듯이 (b)는 linear하지 않고 곡선형으로 이루어져 있습니다. 이것으로 인해 latent vector에서 다른 vector로 interpolation진행할 때 급격하게 특징들이 바뀌는 것을 경험하기 쉬워집니다. 이것을 특징들이 서로 disentanglement하게 되어있지 않고 서로 entanglement하다고 표현합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*OvDTQwLnomtZMPtiKOCDjg.png" /></figure><p>따라서 latent vector z를 sampling 한 뒤에 바로 Generator network를 거치는 것이 아니라 Mapping network를 거친 후에 latent vector w로 바꾼 후에 w space에 존재하는 vector를 이용해 이미지를 생성하는 방식을 채택합니다. (c)의 그림을 통해 쉽게 알 수 있듯이 (b)에서 나타난 곡선형은 사라지고 더욱 linear하고 덜 entanglement하게 바뀐 것을 확인할 수 있습니다. 이렇게 되면 interpolation을 수행할 때 특징들이 급격하게 변경되지 않고 더욱 부드럽게 변경될 수 있습니다.</p><p>그렇다면 style 정보는 어떻게 주입하는 것일까요? 먼저 Generator network의 architecture를 보며 큰 흐름에 대해 알아보겠습니다.</p><ul><li>Style-based generator architecture</li></ul><ol><li>앞서 설명 드렸듯이 mapping network를 거치기 위해 Latent vector z를 sampling한 뒤 normalize를 적용하고 FC(Fully Connected layer)를 거쳐 w space로 mapping 시킵니다.</li><li>w space에서의 latent vector w는 별도의 affine transformation을 거치며, 블록의 AdaIN(Adaptive instance normalization)을 거쳐 style 값을 입력하게 됩니다.</li><li>여기서 하나의 블록은 H와 W를 증가시키기기 위해 Upsampling이 있고 convolution 연산을 수행합니다.</li><li>Convolution layer의 output은 AdaIN을 거쳐 statistics 값을 변경하는 방식으로 style 정보를 주입할 수 있습니다. 여기서 B는 Noise 정보로 이는 추후에 자세히 알아보겠습니다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*pzNIVO57uc-C42HnkwLKFw.png" /><figcaption>Style-based generator</figcaption></figure><p>그렇다면 style 정보를 주입하는 데 사용되는 AdaIN 레이어의 구성에 대해 한 번 알아보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*1O-gTBljR2Lgx7G9qOnPxA.png" /><figcaption>Adaptive Instance Normalization(출처: Rani Horev’s blog)</figcaption></figure><ol><li>1 x 512 차원의 vector w가 있고, 이것이 Affine transformation을 거쳐 Generator network의 블록에 2번씩 들어가게 됩니다.</li><li>Generator network에 들어온 style 정보는 y의 값으로 표현됩니다.</li><li>이것은 convolution의 연산으로 나온 feature map의 정규화된 값에 대해 얼마나 y<em>s</em>,<em>i(scale)</em>을 곱하고 얼마나 <em>yb</em>,<em>i(bias)</em>​를 더할지 설정해주는 방식으로 동작합니다.</li><li>이를 통해 feature에 대해 mean과 variance 값을 바꿔주며, style 정보를 주입할 수 있습니다.</li></ol><ul><li>Stochastic variation</li></ul><p>앞서 잠깐 언급했던 Noise 값에 대해 알아보도록 하겠습니다. Stochastic variation이란 하나의 이미지에 포함될 수 있는 다양한 확률적인 측면들을 제어할 수 있도록 하는 것입니다. <br>Style 정보는 얼굴형, 표정, 안경 등을 변경할 수 있었다면, noise 정보는 주근깨, 피부의 모공, 머리의 곱슬거림, 배경 등을 변경할 수 있습니다. <br>style값과 마찬가지로 noise값도 각각의 블록에 affine transformation을 거쳐 나온 noise 값을 feature map의 statistics를 변경하는 식으로 정보를 반영합니다.</p><blockquote>StyleGAN의 한계점</blockquote><p>뛰어난 성능을 보였던 styleGAN이었음에도 2가지의 한계점이 있었습니다.</p><ol><li>Blob like artifact</li><li>Phase artifact</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZf0DW4ZKiphCTcCU3GCVg.png" /><figcaption>Blob like artifact</figcaption></figure><p>위의 그림과 같이 blob like artifact는 만들어진 이미지에 물방울 모양의 얼룩( Droplet, blob) artifact가 생기는 것입니다. styleGAN2에서는 이것의 원인을 style 정보를 주입할 때 사용했던 AdaIN때문으로 지목했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*lcb0xhYlmSDo3gQ2KB9OIQ.png" /><figcaption>Phase artifact</figcaption></figure><p>Phase artifact는 얼굴 이미지가 생성되었을 때 얼굴의 특정 부분(치아, 눈동자의 위치)이 고정되는 것입니다. 위의 그림에서 확인할 수 있듯이 얼굴의 각도가 움직임에도 치아는 정면에 고정되어 있습니다. styleGAN2에서는 이것의 원인을 progressive growing network 때문이라고 지목했습니다.</p><p>StyleGAN의 한계점을 해결함과 더불어 StyleGAN2 에서는 성능을 더 높은 방법을 설명합니다. 이번엔 StyleGAN2에 대해 자세히 한 번 알아보도록 하겠습니다.</p><blockquote>StyleGAN 2 (Analyzing and Improving the Image Quality of StyleGAN)</blockquote><p>styleGAN 2에서는 styleGAN 1에서 발생했던 문제들을 개선하는 방향으로 논문이 진행됩니다.</p><ul><li>Blob like artifact</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*R5mWlRDiC__p0r18EfR34g.png" /></figure><p>기존의 styleGAN architecture는 convolution 연산을 거쳐서 나온 feature map이 AdaIN을 거쳐, statistics를 변경해주면서 style 정보가 반영이 됩니다. 이 과정에서 AdaIN은 각각의 채널별로 normalization을 진행하기 때문에, 서로 연관된 feature들의 정보가 손실될 수가 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*Cw_5AW45WGTviZQGxftpnA.png" /></figure><p>StyleGAN 2 논문에서는 mean 값은 변경할 필요가 없이 standard deviation(std, 표준편차)만 변경해주어도 괜찮다는 것을 발견하여, (c)에서 볼 수 있듯이 std값만 변경해주었습니다. 또한 bias와 noise를 블록 밖에서 그 값을 변경하여 style이나 noise의 영향력을 독립시키고자 하였습니다.<br>(d)에서는 convolution 연산을 거쳐 나온 feature map에 대해서 modulation을 바로 진행하지 않고, weight 값에 대해서 modulation을 진행합니다. 다시말해 feature map의 statistics를 예측하여 정규화를 진행한다는 것입니다. feature map을 직접적으로 건드리지 않고 weight 값만 바꾸기 때문에 feature들의 간의 연관된 정보들이 손실될 위험이 줄어듭니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*5y84LgQJN7wcrG2-9iZGlQ.png" /><figcaption>droplet artifact 제거</figcaption></figure><ul><li>Phase artifact</li></ul><p>StyleGAN 2에선 Phase artifact가 발생하는 원인을 PGGAN architecture 때문으로 보았습니다. PGGAN은 각 resolution(해상도)마다 충분한 학습을 하고 난 후, 다음 resolution 레이어를 붙이면서 학습이 진행됩니다. 만약 low resolution에서 학습을 진행할 때, 치아나 눈동자 같은 부분에 대해 feature를 고정시켜 놓는 high frequency detail을 유발하면, 다음 resolution에서 그 부분을 고정시켜 놓고 다른 feature들에 대한 부분을 학습하게 됩니다. 이렇게 학습이 진행이 되기 때문에 결과 이미지에 phase artifact문제가 발생하게 된다는 것입니다. <br>그래서 styleGAN 2에서는 PGGAN을 채택하지 않고 MSG-GAN, skip connection, residual net 3가지의 Generator와 Discriminator에 대해 실험을 진행하였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*zLSmU_g5jtpWmIPA9vboBg.png" /></figure><p>결과적으로 본 논문에서 Generator는 skip connection이, Discriminator는 residual net을 사용하였을 때 가장 결과가 좋았으며, 이러한 방식으로 architecture를 구성하여 phase artifact를 해결하였습니다.</p><p>StyleGAN은 이러한 문제를 해결하면서 모델의 성능을 높였습니다.</p><ul><li>Inversion</li></ul><p>일반적으로 latent vector에서 Generator network를 거쳐 이미지를 생성하지만, inversion은 한 장의 이미지를 가질 때 그 이미지를 생성하기 위한 noise vector를 찾는 과정입니다. inversion이 어떻게 수행이 되는지 한 번 알아보겠습니다.</p><ol><li>latent vector w가 Generator를 거쳐 이미지를 생성합니다.</li><li>생성된 이미지는 vgg와 같은 feature extractor를 거쳐 feature가 추출됩니다.</li><li>input으로 들어온 target 이미지도 feature extractor를 거쳐 feature가 추출됩니다.</li><li>MSE(Mean Squared Error, 평균 제곱 오차) 손실 함수를 통해 backpropagation(역전파)를 진행합니다.</li><li>latent vector w는 업데이트가 진행되어 target image와 가까워지게 됩니다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S60IuXuFG8VBtEIBDfUtBw.png" /><figcaption>Projection of images to latent space</figcaption></figure><p>마지막으로 styleGAN에서 사용된 측정지표들에 대해 간략하게 설명하고 마무리하겠습니다.</p><ul><li>PPL(Perceptual Path Length)</li></ul><p>PPL은 latent vector가 변경됨에 따라서 생성된 image가 얼마나 부드럽게 바뀔 수 있는 가를 수치적으로 나타낸 측정 방법입니다. PPL이 낮아지는 방향으로 학습이 진행된다면, 더 그럴듯한 이미지를 생성할 수 있다고 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*gDq0DmTkdBv3h2aWXvHnVA.png" /><figcaption>PPL 설명 이미지 출처(<a href="https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2">https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2</a><a href="https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2">)</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*zLaWeMeMOEG-wirRrmD6Ug.png" /></figure><p>수식을 보며 조금 더 자세히 알아보겠습니다. 먼저 latent vector z1과 z2는 mapping network인 f()를 거쳐 style vector w1과 w2가 되고 linear interpolation을 수행합니다. 그리고 t지점과 t+ε 지점이 있고, 그 두 개의 지점(t와 t+ε지점)에 대해서 linear interpolation을 하면서 Generator에 들어가 각각 결과 이미지를 만들어 냅니다. 생성된 결과 이미지들을 pretrained VGG net에 넣어서 특징간의 거리가 얼마나 먼지를 구하는 방식으로 PPL을 계산할 수 있습니다.</p><p>다음으로 지표들에 대해 알아보도록 하겠습니다.</p><ul><li>Discriminator loss<br>D_loss는 real loss와 fake loss의 합으로 이루어져 있습니다. 그리고 이것은 이상적으로 생성된 이미지가 real인지 fake인지를 추측하는 정도의 수준(p=0.5)에 머무르게 됩니다.</li><li>Fake score<br>fake score의 값이 높을수록 Discriminator에 들어오는 fake 이미지를 real 이미지로 판단합니다. fake score가 높은 값이면 discriminator가 잘못 판단하고 있다는 것이고 반대로 fake score가 낮은 값이면 discriminator가 잘 판단하고 있다고 볼 수 있습니다.</li><li>Real score<br>real score의 값이 높을수록 Discriminator에 들어오는 real 이미지를 real 이미지로 판단합니다. real score가 높은 값이면 discriminator가 잘 판단하고 있다는 것이고 반대로 real score가 낮은 값이면 discriminator가 잘못 판단하고 있다는 것입니다.</li><li>Generator loss<br>G_loss는 epoch가 진행됨에 따라 점점 줄어들어야 합니다. 또한 Generator가 과적합이 일어나지 않는 epoch를 잘 선택해야합니다.</li></ul><blockquote>참고</blockquote><p><a href="https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2">StyleGAN / StyleGAN2</a></p><p><a href="https://study-grow.tistory.com/entry/pytorch-stylegan2-%EC%97%AC%EB%9F%AC-%EC%A7%80%ED%91%9C%EB%93%A4-%EC%9A%A9%EC%96%B4-%EC%A0%95%EB%A6%AC-real-score-fake-score">https://study-grow.tistory.com/entry/pytorch-stylegan2-%EC%97%AC%EB%9F%AC-%EC%A7%80%ED%91%9C%EB%93%A4-%EC%9A%A9%EC%96%B4-%EC%A0%95%EB%A6%AC-real-score-fake-score</a><br><a href="https://youtu.be/HXgfw3Z5zRo">https://youtu.be/HXgfw3Z5zRo</a><br><a href="https://youtu.be/5UlTdngEdas">https://youtu.be/5UlTdngEdas</a><br><a href="https://study-grow.tistory.com/entry/Deep-learning-%EB%85%BC%EB%AC%B8-%EC%9D%BD%EA%B8%B0-StyleGAN2">https://study-grow.tistory.com/entry/Deep-learning-%EB%85%BC%EB%AC%B8-%EC%9D%BD%EA%B8%B0-StyleGAN2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc09ea284c65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/generate-images-by-using-stylegan2-bc09ea284c65">Generate images by using StyleGAN2</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DVC(Data Version Control)를 활용하여 Version관리하기]]></title>
            <link>https://medium.com/toonsquare-tech/dvc-data-version-control-%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%98%EC%97%AC-version%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0-8c972f6d0177?source=rss-25d830e41467------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c972f6d0177</guid>
            <dc:creator><![CDATA[김원중]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 07:26:41 GMT</pubDate>
            <atom:updated>2021-12-28T05:55:44.070Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Model 중심의 AI가 아닌 DATA 중심의 AI시대가 도래할 것이다. 따라서 체계적인 데이터 관리를 위해 MLOps가 중요하다. — Andrew Ng”</blockquote><p>최근들어 ML/DL에 대한 관심이 뜨거워지면서 ‘MLOps’라는 개념이 생겨났습니다. 기존의 DevOps의 흐름에 ML만의 특징을 적용한 개념인데요, MLOps가 무엇인지 DevOps와 비교를 통해 간략하게 알아보겠습니다.</p><blockquote><strong>DevOps &amp; MLOps</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcDx_MmR4VLeqvRCODJ6aA.png" /><figcaption>DevOps</figcaption></figure><p>DevOps는 소프트웨어의 개발(Dev)과 운영(Ops)을 합성하여 만든 소프트웨어 개발 방법론입니다. 이것은 CI/CD(Continuous Integration / Continuous Development, Deployment)를 핵심으로 하여 build, test, deploy의 과정을 자동화하여 신속하게 개발을 하고 지속적이고 안정적으로 배포를 할 수 있도록 돕습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tNOJ3KYO-AieuSPBMZN_DA.png" /><figcaption>MLOps — nvidia 공식 블로그</figcaption></figure><p>반면 MLOps는 ML모델 개발(ML)과 ML모델 운영(Ops)을 통합한 용어로, ML개발과 운영 과정에서 발생되는 문제를 최소화하고, 일관성있는 인프라를 구축하여 안정적이고 효율적으로 서비스를 운영하는 것을 목표로 합니다.</p><p>DevOps와 MLOps는 비슷한 맥락을 가지지만 여러 차이점이 있습니다. ML 시스템을 개발한다는 점, CI/CD외에도 CT(Continuous Training)라는 개념이 추가가 되는 점, Data 관리를 해야 한다는 점 등이 있습니다.</p><figure><img alt="MLOps 요소" src="https://cdn-images-1.medium.com/max/1024/1*1rL7RkZ7_jEQOlXAbufamA.png" /><figcaption>MLOps 요소 Hidden Technical Debt in Machine Learning Systems</figcaption></figure><p>여기서 특히 Data를 다룬다는 점에 주목을 할 필요가 있습니다. ML model의 성능은 data의 품질에 따라 좌우된다는 사실은 이미 모두가 알고 있을 것입니다. 그래서 MLOps는 data 수집, 전처리, 모니터링, 검증 등을 하여 data를 관리하기 위한 많은 노력을 합니다. 이에 따라 데이터를 체계적으로 관리하는 것을 도와주는 다양한 open source tool들이 존재하며, 오늘 포스팅할 DVC도 이 tool들 가운데 하나입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*INY_VvGbKouqcWxrlei0hA.png" /><figcaption>관리 tool 비교</figcaption></figure><p>이러한 tool들의 자세한 비교는 아래의 링크에서 찾아보실 수 있습니다.</p><p><a href="https://dagshub.com/blog/data-version-control-tools/">Comparing Data Version Control Tools - 2020</a></p><p>지금부터 DVC에 대해 자세하게 알아 보겠습니다.</p><blockquote><strong>DVC(Data Version Control)는 무엇인가요?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGKqxynouGlkC25Z_3Z_sQ.gif" /><figcaption>DVC flow</figcaption></figure><p>DVC는 많은 분들에게 익숙한 Git 을 기반으로 하여 data version관리, workflow 및 실험관리 기능을 지원해주는 소프트웨어입니다. 그래서 팀원들은 Git과 DVC를 활용하여 version을 공유하여 checkout할 수 있으며, 대규모 dataset을 관리 및 reproduce(재생산)할 수 있습니다.</p><p><strong>DVC 용어</strong></p><ul><li><strong>.dvc</strong> 파일은 dvc add 명령어로 생성 되며, 로컬 또는 외부에 위치한 실제 파일 또는 디렉토리를 추적하는 역할을 합니다. 이 파일에는 대상 데이터를 추적하는 데 필요한 정보가 포함되어 있어 포인터(?)정도로 생각을 하면 이해하기 쉬우실 겁니다. 또한 github에는 실제 파일이 아닌 실제 파일을 추적하는 .dvc파일이 push됩니다.</li><li><strong>.gitignore</strong> 파일은 .dvc 파일과 함께 dvc add 명령어로 자동 생성 되며, 실제 file이 .gitignore 파일에 자동 업데이트가 됩니다. github에 실제 파일이 push되는 것을 방지합니다.</li><li><strong>.dvc/config</strong> 파일은 dvc remote add 명령어로 remote storage를 등록했을 때 그 정보가 자동으로 입력이 됩니다.</li><li><strong>.dvc/config.local</strong> 파일은 사용자의 민감한 정보가 들어갑니다. 예를 들어, s3를 remote storage로 지정한 경우 s3 bucket에 접근할 수 있는 secret key와 id가 필요합니다. <br>dvc remote modify --local storage access_key_id &#39;myID&#39; <br>dvc remote modify --local storage secret_access_key &#39;myKey&#39; 로 id와 key를 등록합니다. 이 외에도 민감한 정보는 --local 을 통해 입력할 수 있으며, config.local은 .gitignore에 있어 push가 되지 않습니다.</li><li><strong>remote storage</strong>는 실제 데이터들이 저장이 될 저장소입니다. DVC는 Amazon S3, Google Drive, Google Cloud Storage, Microsoft Azure, SSH 등 다양한 저장소를 등록할 수 있습니다. 자세한 내용은 링크를 참조해 주세요. <a href="https://dvc.org/doc/command-reference/remote/modify#example-some-azure-authentication-methods">https://dvc.org/doc/command-reference/remote/modify#example-some-azure-authentication-methods</a></li><li><strong>data registry</strong>는 dvc가 포함된 git repository라고 생각하시면 됩니다. 사용자는 data registry를 통해 data들의 변경사항을 확인 할 수 있고, dvc get 과 dvc import 명령어를 통해 데이터들을 쉽게 재생산할 수 있습니다. 자세한 내용은 링크를 참조해 주세요. <a href="https://dvc.org/doc/use-cases/data-registries#data-registries">https://dvc.org/doc/use-cases/data-registries#data-registries</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2b7rZbhDEZp77-tZgouokg.png" /></figure><p><strong>DVC 명령어</strong></p><ul><li><strong>dvc add</strong>는 사용자가 version 관리를 하고 싶은 파일이나 디렉토리를 추적하고 싶을 때 사용합니다. 이 명령어를 통해 .dvc 파일이 생성됩니다.</li><li><strong>dvc remote add</strong>는 사용자가 실제 데이터들을 저장할 원격 저장소를 지정해줄 때 사용합니다. 예를 들어 s3 bucket을 등록하고자 할 때는 <br>dvc remote add -d storage s3://mybucket/path 로 사용합니다. -d 옵션은 원격 저장소의 이름을 지정해주는 것이고, s3 path는 bucket의 uri를 복사하여 사용합니다.</li><li><strong>dvc push</strong>는 사용자가 현재 .dvc로 추적되는 파일이나 디렉토리를 원격 저장소에 업로드 하고자 할 때 사용합니다.</li><li><strong>dvc get</strong>은 사용자가 data registry에 있는 파일이나 디렉토리를 다운로드 할 때 사용합니다.<br>dvc get https://github.com/iterative/example-get-started model.pkl</li><li><strong>dvc import</strong>도 dvc get 과 비슷하지만 .dvc 파일도 함께 다운로드 한다는 점이 차이점입니다.</li><li><strong>dvc pull</strong>은 사용자가 .dvc로 추적되는 파일이나 디렉토리를 원격 저장소에서 data를 다운로드 할 때 사용합니다. 하나의 데이터만 가지고 오고 싶을 경우에는 dvc pull data.pth 와 같이 dvc로 추적되는 파일명을 적어주면 됩니다.</li><li><strong>dvc doctor</strong>는 프로젝트의 정보 및 환경과 함께 dvc의 버전을 보여줍니다.</li></ul><blockquote><strong>DVC를 사용해 봅시다!</strong></blockquote><h4>DVC push</h4><ol><li>pip install 로 dvc를 설치하고, git &amp; dvc init을 통해 초기화해줍니다. dvc init 을 하게 되면 .dvc 폴더와 .dvcignore가 만들어 집니다.</li></ol><pre>pip install dvc</pre><pre>git init</pre><pre>dvc init</pre><p>2. Version 관리를 하고싶은 파일이 bigdata.txt이고 굉장히 큰 파일이라고 가정을 해보겠습니다.</p><pre>dvc add bigdata.txt</pre><pre>git add bigdata.txt.dvc .gitignore</pre><p>dvc add bigdata.txt를 하면, bigdata.txt의 정보가 들어있는 bigdata.txt.dvc파일이 생성이 되며 .gitignore에는 bigdata.txt가 입력되어 git repository에 push되는 것을 방지합니다. 그리고 git에 bigdata.txt.dvc 와 .gitignore를 추가해줍니다.</p><p>3. Remote storage를 설정해 줍니다.</p><pre>dvc remote add -d storage s3://mybucket/path</pre><pre>git add .dvc/config</pre><pre>git commit -m &quot;This is my first DVC, version 1.0&quot;</pre><p>dvc remote add 명령어로 원격 저장소를 지정해줍니다. 그러면 .dvc/config파일에 원격 저장소에 대한 정보가 담기게 됩니다.<br>git에 추가해주고, 현재까지 add된 것들을 commit해줍니다.</p><p>4. tag를 달고 push를 합니다. (data registry는 이미 지정되었다고 가정하겠습니다)</p><pre>git tag -a &quot;v1.0&quot; -m &quot;This is my first DVC, version 1.0&quot;</pre><pre>git push</pre><pre>git push --tags</pre><pre>dvc push</pre><p>git push 와 git push --tags 명령어로 data registry에 bigdata.txt.dvc 파일과 “v1.0” 태그를 push해줍니다. 그리고 dvc push 명령어로 bigdata.txt 파일을 지정한 원격 저장소에 push해줍니다.</p><p><strong>여기서 잠깐!</strong><br>remote storage를 지정해주고 push나 pull을 할 경우 그곳에 접근할 수 있도록 필요 라이브러리를 install해주어야 하고 보안상의 이유로 key나 password가 필요합니다. 저는 google drive와 aws s3를 실습했기 때문에 이 두 가지에 대해 말씀드리겠습니다.</p><ol><li>AWS S3</li></ol><pre># boto3 &amp; s3fs install</pre><pre>pip install boto3</pre><pre>pip install s3fs</pre><pre># s3 bucket에 접근할 수 있도록 aws_access_key_id &amp; aws_secret_access_key가 필요하며 이를 등록해주어야 합니다.(.dvc/config.local에 입력됨)</pre><pre>dvc remote modify --local storage access_key_id &#39;myId&#39;</pre><pre>dvc remote modify --local storage secret_access_key &#39;myKey&#39;</pre><p>2. Google drive</p><pre>pip install &quot;dvc[gdrive]&quot;</pre><pre>gdrive의 경우 push나 pull을 할 경우 token이 들어있는 링크를 주며, 발급된 token을 입력해주면 인증이 완료된다.</pre><p>여기까지가 dvc push를 하는 기본적인 흐름이었습니다! <br>그렇다면 만약에 bigdata.txt 파일에 무언가가 추가되어 version up 시켜주어야 한다면 어떻게 해야 할까요?</p><h4>Version up</h4><p>이미 init이나 원격 저장소 및 key &amp; id를 다 설정해 주었기 때문에 굉장히 간단합니다.</p><pre>dvc add bigdata.txt</pre><pre>git add bigdata.txt.dvc</pre><pre>git commit -m &quot;This is bigdata.txt version up, version 2.0&quot;</pre><pre>git tag -a &quot;v2.0&quot; -m &quot;This is bigdata.txt version up, version 2.0&quot;</pre><pre>git push</pre><pre>git push --tags</pre><pre>dvc push</pre><p>dvc add명령어를 사용하여 추가된 bigdata.txt 파일의 bigdata.txt.dvc 파일을 만들어 줍니다. 그리고 git add 명령어로 bigdata.txt.dvc 파일을 추가해줍니다. 이미 .gitignore 파일에 bigdata.txt가 있으므로 이것은 추가하지 않습니다.<br>그리고 git commit 과 git tag 를 달아주고 git push 및 dvc push 를 진행해줍니다.</p><p>그렇다면 bigdata.txt 파일을 어떻게 가져올 수 있을까요? <br>데이터를 가지고 오는 방법은 3가지가 있습니다. dvc pull dvc get dvc import자세히 알아보도록 하겠습니다.</p><h4>DVC pull</h4><p>dvc pull은 .dvc 파일이 있어야 실제 데이터를 가지고 올 수 있습니다. <br>현재 아무것도 없는 상황이라고 가정하고 진행하겠습니다.</p><pre># 주소는 dvc git repo주소입니다.(push한 bigdata.txt.dvc가 있는 repo라 가정)<br>git clone <a href="https://github.com/iterative/dvc.git">https://github.com/iterative/dvc.git</a></pre><pre>dvc pull</pre><p>bigdata.txt.dvc 가 있는 data registry를 git clone 해주어 .dvc 파일을 가지고 옵니다. 그리고 dvc pull 명령어로 실제 데이터를 가지고 옵니다.</p><p>만약 다른 버전의 데이터를 가지고 오고 싶을 땐 어떻게 해야 할까요? 알아봅시다!</p><pre># tag 목록 보기<br>git tag</pre><pre># 원하는 tag로 checkout<br>git checkout v1.0</pre><pre># 해당 version의 data 가져오기<br>dvc pull</pre><p>bigdata.txt.dvc를 push할 때 저희가 “v1.0”, “v2.0” 태그도 함께 push를 했기 때문에 git clone을 해서 가져 올 때 이 tag들도 가지고 옵니다. tag의 목록은 git tag 명령어로 확인할 수 있습니다. <br>원하는 tag로 HEAD를 이동하기 위해서 git checkout 명령어를 사용합니다. 저는 이전 버전으로 가기 위해 git checkout v1.0 을 했습니다.<br>그리고 dvc pull 을 하면, 해당 버전에 push를 했던 데이터가 pull됩니다.</p><h4>DVC get &amp; DVC import</h4><p>그렇다면 Data registry를 통해 data를 가져와보도록 하겠습니다. 여기에선 dvc get 과 dvc import 가 사용되며 data registry의 주소가 필요합니다.</p><p>dvc get과 import는 dvc docs의 예제를 참조하였습니다.</p><pre>dvc get https://github.com/iterative/dataset-registry \<br>          tutorials/versioning/data.zip</pre><p>해당 data registry에 업로드 된 data.zip.dvc를 통해 현재 경로에 data.zip 파일을 다운로드합니다.</p><pre>dvc import https://github.com/iterative/dataset-registry \<br>          use-cases/cats-dogs</pre><p>해당 경로에 실제 데이터인 cats-dogs 폴더와 cats-dogs.dvc 파일이 함께 다운로드 됩니다.</p><blockquote><strong>Github action과 DVC</strong></blockquote><p>Github action으로 workflow를 진행하면서 DVC를 적용하여 모델 파일과, data set, codes들의 version관리도 함께 진행할 수 있습니다. 이때 필요한 것이 바로 ‘<strong>Setup DVC Action</strong>’입니다.<br>자세한 내용은 링크를 참조해주세요. <a href="https://github.com/iterative/setup-dvc">https://github.com/iterative/setup-dvc</a></p><p>사용법은 간단합니다. 아래의 code를 .yml 파일에 적어주면 됩니다. ex) aws S3</p><pre>steps:<br>  - uses: actions/checkout@v2<br>  - uses: iterative/setup-dvc@v1<br>    env:<br>        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} </pre><p>Github →Settings → Secrets 탭에서 aws_access_key_id와 aws_secret_access_key를 환경변수로 지정해 주면 Github action에서 사용할 수 있습니다.</p><blockquote><strong>끝 맺는 말</strong></blockquote><p>지금까지 MLOps의 많은 요소 중 data 관리를 도와주는 tool인 DVC에 대한 내용을 포스팅해 보았습니다. DVC를 학습하고 적용하면서, 사용성이 좋으면서 굉장히 강력한 기능을 가지고 있다는 것을 느꼈습니다. <br>이번 포스팅에서는 DVC의 핵심 기능인 version관리에 대해서만 다루었지만 이 외에도 ML을 돕는 많은 기능들이 있으니 흥미가 있으시면 한 번 찾아보시는 것을 추천합니다. 긴 글 읽어주셔서 감사하며, 이번 포스팅이 도움이 되었길 바랍니다.</p><blockquote><strong>참조 문서</strong></blockquote><p><a href="https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning?hl=ko">https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning?hl=ko</a> <a href="https://pebpung.github.io/mlops/2021/01/14/MLOps1.html">https://pebpung.github.io/mlops/2021/01/14/MLOps1.html</a><br><a href="https://speakerdeck.com/mlopskr/mlops-cuncu-jeongug-sidae-jeongri-byeonseongyun?slide=24">https://speakerdeck.com/mlopskr/mlops-cuncu-jeongug-sidae-jeongri-byeonseongyun?slide=24</a><br><a href="https://dvc.org/doc">https://dvc.org/doc</a><br>https://github.com/iterative/dataset-registry<br>https://devocean.sk.com/blog/techBoardDetail.do?ID=163379<br>https://lsjsj92.tistory.com/573</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c972f6d0177" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/dvc-data-version-control-%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%98%EC%97%AC-version%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0-8c972f6d0177">DVC(Data Version Control)를 활용하여 Version관리하기</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>