☁️ 클라우드

Vertex AI

Google Cloud Vertex AI Platform

Google Cloud의 통합 머신러닝 플랫폼. AutoML, 커스텀 모델 학습, Gemini API, Model Garden 등을 제공하며 MLOps 전체 라이프사이클을 지원합니다.

📖 상세 설명

Vertex AI는 2021년 Google Cloud에서 출시한 통합 ML 플랫폼입니다. 기존에 분리되어 있던 AI Platform, AutoML, AI Hub 등을 하나로 통합하여 데이터 준비부터 모델 학습, 배포, 모니터링까지 MLOps 전체 과정을 단일 환경에서 관리할 수 있습니다. BigQuery, Cloud Storage 등 GCP 서비스와 네이티브 통합이 강점입니다.

핵심 기능은 크게 4가지입니다. AutoML은 코드 없이 이미지, 텍스트, 테이블 데이터용 모델을 자동으로 학습합니다. Custom Training은 TensorFlow, PyTorch, scikit-learn 등 원하는 프레임워크로 모델을 직접 개발할 때 사용합니다. Model Garden은 PaLM 2, Gemini, Claude, Llama 등 다양한 파운데이션 모델을 원클릭으로 배포할 수 있는 허브입니다. Vertex AI Studio는 생성형 AI 모델을 UI에서 테스트하고 프롬프트를 관리합니다.

최근에는 Gemini API가 Vertex AI의 핵심으로 자리잡았습니다. Gemini 1.5 Pro/Flash 모델을 API로 호출할 수 있고, 멀티모달(텍스트, 이미지, 오디오, 비디오) 입력을 지원합니다. 100만 토큰의 긴 컨텍스트 윈도우, 함수 호출(Function Calling), 그라운딩(검색 연동) 등 엔터프라이즈 기능이 포함됩니다.

Vertex AI Pipelines는 Kubeflow 기반의 MLOps 오케스트레이션 도구로, 모델 학습과 배포를 자동화합니다. Feature Store는 ML 피처를 중앙에서 관리하고, Model Registry는 모델 버전과 메타데이터를 추적합니다. 이러한 구성요소들이 결합되어 프로덕션급 ML 시스템을 빠르게 구축할 수 있습니다.

💻 코드 예제

# Vertex AI를 활용한 Gemini API 및 MLOps 예제

from google.cloud import aiplatform
from vertexai.generative_models import GenerativeModel, Part
from vertexai.language_models import TextEmbeddingModel
import vertexai

# 프로젝트 초기화
PROJECT_ID = "my-gcp-project"
LOCATION = "us-central1"
vertexai.init(project=PROJECT_ID, location=LOCATION)

# ==========================================
# 1. Gemini API 사용 (멀티모달)
# ==========================================

def chat_with_gemini(prompt: str, image_path: str = None) -> str:
    """Gemini 모델로 대화형 응답 생성"""
    model = GenerativeModel("gemini-1.5-pro")

    if image_path:
        # 이미지와 함께 멀티모달 입력
        image = Part.from_uri(image_path, mime_type="image/jpeg")
        response = model.generate_content([prompt, image])
    else:
        response = model.generate_content(prompt)

    return response.text

# Function Calling 예제
def gemini_with_function_calling():
    """Gemini의 함수 호출 기능"""
    from vertexai.generative_models import FunctionDeclaration, Tool

    # 함수 정의
    get_weather_func = FunctionDeclaration(
        name="get_weather",
        description="지정된 도시의 현재 날씨 정보를 조회합니다",
        parameters={
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "도시 이름"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["city"]
        }
    )

    weather_tool = Tool(function_declarations=[get_weather_func])
    model = GenerativeModel("gemini-1.5-pro", tools=[weather_tool])

    response = model.generate_content("서울 날씨 알려줘")

    # 함수 호출 결과 처리
    if response.candidates[0].content.parts[0].function_call:
        func_call = response.candidates[0].content.parts[0].function_call
        print(f"Function: {func_call.name}, Args: {func_call.args}")

    return response

# ==========================================
# 2. 텍스트 임베딩 생성
# ==========================================

def create_embeddings(texts: list) -> list:
    """텍스트 임베딩 벡터 생성 (RAG 구축용)"""
    model = TextEmbeddingModel.from_pretrained("text-embedding-004")

    embeddings = model.get_embeddings(texts)
    vectors = [emb.values for emb in embeddings]

    return vectors

# ==========================================
# 3. Custom Training Job
# ==========================================

def run_custom_training():
    """커스텀 학습 작업 실행"""
    aiplatform.init(project=PROJECT_ID, location=LOCATION)

    # 커스텀 학습 작업 생성
    job = aiplatform.CustomTrainingJob(
        display_name="my-custom-training",
        script_path="trainer/train.py",  # 학습 스크립트
        container_uri="us-docker.pkg.dev/vertex-ai/training/pytorch-gpu.1-13:latest",
        requirements=["transformers", "datasets"],
        model_serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/pytorch-gpu.1-13:latest"
    )

    # 학습 실행
    model = job.run(
        dataset=None,  # 또는 Vertex AI Dataset 참조
        model_display_name="trained-model",
        machine_type="n1-standard-8",
        accelerator_type="NVIDIA_TESLA_T4",
        accelerator_count=1,
        args=["--epochs", "10", "--batch-size", "32"]
    )

    return model

# ==========================================
# 4. 모델 배포 및 예측
# ==========================================

def deploy_model(model_resource_name: str):
    """학습된 모델을 엔드포인트에 배포"""
    model = aiplatform.Model(model_resource_name)

    # 엔드포인트 생성 및 배포
    endpoint = model.deploy(
        deployed_model_display_name="production-model",
        machine_type="n1-standard-4",
        min_replica_count=1,
        max_replica_count=3,
        accelerator_type="NVIDIA_TESLA_T4",
        accelerator_count=1,
        traffic_split={"0": 100}  # 100% 트래픽
    )

    return endpoint

def predict(endpoint, instances: list):
    """배포된 모델로 예측"""
    predictions = endpoint.predict(instances=instances)
    return predictions.predictions

# ==========================================
# 5. Vertex AI Pipelines (MLOps)
# ==========================================

from kfp import dsl
from kfp.v2 import compiler
from google.cloud.aiplatform import pipeline_jobs

@dsl.component(base_image="python:3.10")
def preprocess_data(input_path: str, output_path: str):
    """데이터 전처리 컴포넌트"""
    import pandas as pd
    df = pd.read_csv(input_path)
    # 전처리 로직
    df.to_csv(output_path, index=False)

@dsl.component(base_image="us-docker.pkg.dev/vertex-ai/training/pytorch-gpu.1-13:latest")
def train_model(data_path: str, model_path: str, epochs: int):
    """모델 학습 컴포넌트"""
    # 학습 로직
    pass

@dsl.pipeline(name="ml-training-pipeline")
def ml_pipeline(input_data: str):
    """ML 파이프라인 정의"""
    preprocess_task = preprocess_data(
        input_path=input_data,
        output_path="gs://my-bucket/processed_data.csv"
    )

    train_task = train_model(
        data_path=preprocess_task.outputs["output_path"],
        model_path="gs://my-bucket/model/",
        epochs=10
    )

# 파이프라인 컴파일 및 실행
compiler.Compiler().compile(
    pipeline_func=ml_pipeline,
    package_path="pipeline.json"
)

job = pipeline_jobs.PipelineJob(
    display_name="training-run-001",
    template_path="pipeline.json",
    parameter_values={"input_data": "gs://my-bucket/raw_data.csv"}
)
job.submit()

🗣️ 실무에서 이렇게 말해요

ML 리드: "RAG 시스템 구축할 건데, 임베딩은 어디서 할까요?"

엔지니어: "Vertex AI의 text-embedding-004 모델 쓰면 어떨까요? BigQuery 벡터 검색이랑 연동도 잘 되고, 768차원이라 성능도 좋아요."

ML 리드: "좋아요. Gemini 1.5 Pro의 그라운딩 기능도 같이 테스트해봐요. Google Search 연동하면 최신 정보도 반영할 수 있을 거예요."

면접관: "AWS SageMaker와 Vertex AI를 비교해주실 수 있나요?"

지원자: "Vertex AI는 BigQuery, Cloud Storage와의 네이티브 통합이 강점입니다. 특히 Model Garden에서 다양한 오픈소스 및 서드파티 모델을 쉽게 배포할 수 있어요. SageMaker는 AWS 생태계와의 통합과 더 다양한 인스턴스 타입을 제공합니다. 이미 GCP를 쓰고 있다면 Vertex AI가, AWS 중심이면 SageMaker가 유리합니다."

리뷰어: "Gemini API 호출할 때 safety_settings 빠졌어요. 프로덕션에서는 필수입니다."

작성자: "아, 맞다. HARM_CATEGORY별로 threshold 설정하고, 필터링된 응답 처리 로직도 추가할게요."

⚠️ 주의사항

📚 더 배우기