Gemma 개방형 모델과 ML.GENERATE_TEXT 함수를 사용하여 텍스트 생성

이 튜토리얼에서는 Gemma 모델을 기반으로 하는 원격 모델을 만드는 방법과 이 모델을 ML.GENERATE_TEXT 함수와 함께 사용하여 bigquery-public-data.imdb.reviews 공개 테이블에서 영화 리뷰에서 키워드를 추출하고 감정 분석을 수행하는 방법을 보여줍니다.

필수 권한

이 튜토리얼을 실행하려면 다음 Identity and Access Management (IAM) 역할이 필요합니다.

  • BigQuery 데이터 세트, 연결, 모델을 만들고 사용하려면 BigQuery 관리자 (roles/bigquery.admin)가 필요합니다.
  • 연결의 서비스 계정에 권한 부여: 프로젝트 IAM 관리자(roles/resourcemanager.projectIamAdmin)
  • Vertex AI에서 모델 배포 및 배포 해제: Vertex AI 관리자(roles/aiplatform.admin)

이러한 사전 정의된 역할에는 이 문서의 작업을 수행하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

  • 데이터 세트 만들기: bigquery.datasets.create
  • 연결을 만들고, 위임하고, 사용합니다. bigquery.connections.*
  • 기본 연결 설정: bigquery.config.*
  • 서비스 계정 권한 설정: resourcemanager.projects.getIamPolicyresourcemanager.projects.setIamPolicy
  • Vertex AI 모델 배포 및 배포 해제:
    • aiplatform.endpoints.deploy
    • aiplatform.endpoints.undeploy
  • 모델을 만들고 추론을 실행합니다.
    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
    • bigquery.models.updateMetadata

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

비용

이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소( )를 사용합니다.

  • BigQuery ML: You incur costs for the data that you process in BigQuery.
  • Vertex AI: You incur costs for calls to the Vertex AI model that's represented by the remote model.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용합니다.

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

BigQuery 가격 책정에 대한 자세한 내용은 BigQuery 문서의 BigQuery 가격 책정을 참조하세요.

Vertex AI에 배포하는 개방형 모델은 머신 시간당 요금이 청구됩니다. 즉, 엔드포인트가 완전히 설정되는 즉시 비용이 청구되기 시작하고 배포가 취소될 때까지 계속됩니다. Vertex AI 가격 책정에 대한 자세한 내용은 Vertex AI 가격 책정 페이지를 참조하세요.

시작하기 전에

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the BigQuery, BigQuery Connection, and Vertex AI APIs.

    Enable the APIs

Vertex AI에 Gemma 모델 배포

Model Garden 모델 배포의 안내에 따라 gemma-2-27b-it 모델을 Vertex AI에 배포합니다. 배포 중에 배포 워크플로의 엔드포인트 액세스 필드 값으로 공개 (공유 엔드포인트)를 선택해야 합니다.

데이터 세트 만들기

ML 모델을 저장할 BigQuery 데이터 세트를 만듭니다.

콘솔

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery 페이지로 이동

  2. 탐색기 창에서 프로젝트 이름을 클릭합니다.

  3. 작업 보기 > 데이터 세트 만들기를 클릭합니다.

    데이터 세트 만들기 메뉴 옵션

  4. 데이터 세트 만들기 페이지에서 다음을 수행합니다.

    • 데이터 세트 IDbqml_tutorial를 입력합니다.

    • 위치 유형에 대해 멀티 리전을 선택한 다음 US(미국 내 여러 리전)를 선택합니다.

    • 나머지 기본 설정은 그대로 두고 데이터 세트 만들기를 클릭합니다.

bq

새 데이터 세트를 만들려면 --location 플래그와 함께 bq mk 명령어를 실행합니다. 사용할 수 있는 전체 파라미터 목록은 bq mk --dataset 명령어 참조를 확인하세요.

  1. 데이터 위치가 US로 설정되고 설명이 BigQuery ML tutorial datasetbqml_tutorial 데이터 세트를 만듭니다.

    bq --location=US mk -d \
     --description "BigQuery ML tutorial dataset." \
     bqml_tutorial

    --dataset 플래그를 사용하는 대신 이 명령어는 -d 단축키를 사용합니다. -d--dataset를 생략하면 이 명령어는 기본적으로 데이터 세트를 만듭니다.

  2. 데이터 세트가 생성되었는지 확인합니다.

    bq ls

API

데이터 세트 리소스가 정의된 datasets.insert 메서드를 호출합니다.

{
  "datasetReference": {
     "datasetId": "bqml_tutorial"
  }
}

BigQuery DataFrames

이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

import google.cloud.bigquery

bqclient = google.cloud.bigquery.Client()
bqclient.create_dataset("bqml_tutorial", exists_ok=True)

원격 모델 만들기

호스팅된 Vertex AI 모델을 나타내는 원격 모델을 만듭니다.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 쿼리를 실행합니다.

CREATE OR REPLACE MODEL `bqml_tutorial.gemma_model`
  REMOTE WITH CONNECTION DEFAULT
  OPTIONS (ENDPOINT = 'https://ENDPOINT_REGION-aiplatform.googleapis.com/v1/projects/ENDPOINT_PROJECT_ID/locations/ENDPOINT_REGION/endpoints/ENDPOINT_ID');

다음을 바꿉니다.

  • ENDPOINT_REGION: 개방형 모델이 배포되는 리전
  • ENDPOINT_PROJECT_ID: 개방형 모델이 배포되는 프로젝트
  • ENDPOINT_ID: 개방형 모델에서 사용하는 HTTPS 엔드포인트의 ID. 온라인 예측 페이지에서 개방형 모델을 찾아 ID 필드의 값을 복사하여 엔드포인트 ID를 가져올 수 있습니다.

다음 예시에서는 유효한 HTTP 엔드포인트의 형식을 보여줍니다.

https://us-central1-aiplatform.googleapis.com/v1/projects/myproject/locations/us-central1/endpoints/1234.

쿼리가 완료되는 데 몇 초 정도 걸리며 그 이후에는 gemma_model 모델이 탐색기 창의 bqml_tutorial 데이터 세트에 표시됩니다. 이 쿼리에서는 CREATE MODEL 문을 사용하여 모델을 만들므로 쿼리 결과가 없습니다.

키워드 추출 수행

원격 모델과 ML.GENERATE_TEXT 함수를 사용하여 IMDB 영화 리뷰에서 키워드를 추출합니다.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력하여 영화 리뷰 5개에서 키워드를 추출합니다.

    SELECT
      *
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemma_model`,
        (
          SELECT
            CONCAT('Extract the key words from the movie review below: ', review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 10
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens,
          TRUE AS flatten_json_output));

    출력은 다음과 유사하며 생성되지 않은 열은 명확성을 위해 생략됩니다.

    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | generated_text                               | ml_generate_text_status | prompt                      | ... |
    +----------------------------------------------+-------------------------------------------------------+-----+
    | Here are some key words from the             |                         | Extract the key words from  |     |
    | movie review: * **Romance:**                 |                         | the movie review below:     |     |
    | "romantic tryst," "elope" * **Comedy:**      |                         | Linda Arvidson (as Jennie)  |     |
    | "Contrived Comedy" * **Burglary:**           |                         | and Harry Solter (as Frank) |     |
    | "burglar," "rob," "booty" * **Chase:**       |                         | are enjoying a romantic     |     |
    | "chases," "escape" * **Director:** "D.W.     |                         | tryst, when in walks her    |     |
    | Griffith" * **Actors:** "Linda Arvidson,"... |                         | father Charles Inslee;...   |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | Here are some key words from the             |                         | Extract the key words from  |     |
    | movie review: * **Elderbush Gilch:** The     |                         | the movie review below:     |     |
    | name of the movie being reviewed. *          |                         | This is the second addition |     |
    | **Disappointment:** The reviewer's           |                         | to Frank Baum's personally  |     |
    | overall feeling about the film. *            |                         | produced trilogy of Oz      |     |
    | **Dim-witted:** Describes the story          |                         | films. It's essentially the |     |
    | line negatively. * **Moronic, sadistic,...   |                         | same childishness as the... |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    

    결과에 다음 열이 포함됩니다.

    • generated_text: 생성된 텍스트입니다.
    • ml_generate_text_status: 해당 행의 API 응답 상태입니다. 작업이 성공하면 이 값이 비어 있습니다.
    • prompt: 감정 분석에 사용되는 프롬프트입니다.
    • bigquery-public-data.imdb.reviews 테이블의 모든 열입니다.

감정 분석 수행

원격 모델과 ML.GENERATE_TEXT 함수를 사용하여 IMDB 영화 리뷰에 대한 감정 분석을 수행합니다.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 실행하여 영화 리뷰 5개에 대한 감정 분석을 수행합니다.

    SELECT
      *
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemma_model`,
        (
          SELECT
            CONCAT('Analyze the sentiment of the following movie review and classify it as either POSITIVE or NEGATIVE. \nMovie Review: ', review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 10
        ),
        STRUCT(
          0.2 AS temperature,
          128 AS max_output_tokens,
          TRUE AS flatten_json_output));

    출력은 다음과 유사하며 생성되지 않은 열은 명확성을 위해 생략됩니다.

    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | generated_text                               | ml_generate_text_status | prompt                      | ... |
    +----------------------------------------------+-------------------------------------------------------+-----+
    | **Sentiment:** NEGATIVE **Justification:**   |                         | Analyze the sentiment of    |     |
    | * **Negative Language:** The reviewer uses   |                         | movie review and classify   |     |
    | phrases like "don't quite make it," "come to |                         | it as either POSITIVE or    |     |
    | mind," "quite disappointing," and "not many  |                         | NEGATIVE. Movie Review:     |     |
    | laughs." * **Specific Criticisms:** The      |                         | Although Charlie Chaplin    |     |
    | reviewer points out specific flaws in the    |                         | made some great short       |     |
    | plot and humor, stating that the manager...  |                         | comedies in the late...     |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | **Sentiment:** NEGATIVE **Reasoning:**       |                         | Analyze the sentiment of    |     |
    | * **Negative Language:** The reviewer uses   |                         | movie review and classify   |     |
    | phrases like "poor writing," "static camera- |                         | it as either POSITIVE or    |     |
    | work," "chews the scenery," "all surface and |                         | NEGATIVE. Movie Review:     |     |
    | no depth," "sterile spectacles," which all   |                         | Opulent sets and sumptuous  |     |
    | carry negative connotations. * **Comparison  |                         | costumes well photographed  |     |
    | to a More Successful Film:**...              |                         | by Theodor Sparkuhl, and... |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    

    결과에는 키워드 추출 수행에 대해 설명된 것과 동일한 열이 포함됩니다.

모델 배포 취소

권장되는 대로 프로젝트를 삭제하지 않기로 선택한 경우 비용이 계속 청구되지 않도록 Vertex AI에서 Gemma 모델 배포를 취소해야 합니다.

삭제

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.