일괄 코드 예측 가져오기

일괄로 응답을 받는 것은 응답 지연 시간이 중요하지 않은 다수의 코드 요청을 효율적으로 전송하기 위한 방법입니다. 한 번에 입력 요청 하나로 제한되는 온라인 응답 가져오기와 달리 일괄 예측은 단일 일괄 요청에서 다수의 코드 생성 모델 요청을 전송합니다. Vertex AI의 테이블 형식 데이터에 대한 일괄 예측과 마찬가지로 출력 위치를 결정하고 입력을 추가하면 응답이 출력 위치에 비동기식으로 채워집니다.

일괄 요청을 제출하고 결과를 검토한 후 코드 생성 기반 모델을 조정하여 특정 태스크에 대한 결과가 잘 작동하도록 개선할 수 있습니다. 조정 후 일괄 생성을 위해 조정된 모델을 제출할 수 있습니다. 모델 조정에 대한 자세한 내용은 언어 기반 모델 조정을 참조하세요.

일괄 예측을 지원하는 코드 모델

  • code-bison

입력 준비

일괄 요청 입력은 BigQuery 테이블에 저장하거나 Cloud Storage의 JSON Lines(JSONL) 파일로 저장할 수 있는 프롬프트 목록입니다. 요청마다 프롬프트가 최대 30,000개까지 포함될 수 있습니다.

JSONL 예시

이 섹션에서는 입력 및 출력 JSONL 파일의 형식을 지정하는 방법의 예시를 보여줍니다.

JSONL 입력 예시

{"prefix":"Write a Python function that determines if a year is a leap year:"}
{"prefix":"Write a unit test for Python code that reverses a string:"}

JSONL 출력 예시

{"instance":{"prefix":"Write..."},"predictions": [{"content":"def is_leap_year(year):...","safetyAttributes":{...}}],"status":""}
{"instance":{"prefix":"Write..."},"predictions": [{"content":"import unittest...", "safetyAttributes":{...}}],"status":""}

BigQuery 예시

이 섹션에서는 BigQuery 입력 및 출력을 포맷하는 방법의 예시를 보여줍니다.

BigQuery 입력 예시

이 예시에서는 단일 열 BigQuery 테이블을 보여줍니다.

프리픽스
'1년이 윤년인지 판단하는 Python 함수를 작성하시오.'
'문자열을 역전하는 Python 코드의 단위 테스트를 작성하시오.'

BigQuery 출력 예시

프리픽스 예측 상태
'1년이 윤년인지 판단하는 Python 함수를 작성하시오.'

{
  "predictions": [
    {
      "safetyAttributes": {
        "scores": [],
        "blocked": false,
        "categories": []
      },
      "content": "```python\ndef is_leap_year(year):\n  \"\"\"\n  Determine if a year is a leap year.\n\n  Args:\n    year: The year to check.\n\n  Returns:\n    True if the year is a leap year, False otherwise.\n  \"\"\"\n\n  if year % 4 != 0:\n    return False\n\n  if year % 100 == 0 and year % 400 != 0:\n    return False\n\n  return True\n```",
      "citationMetadata": {
        "citations": []
      },
      "score": -1.5572503805160522
    }
  ],
}
 
'문자열을 역전하는 Python 코드의 단위 테스트를 작성하시오.'

{
  "predictions": [
    {
      "safetyAttributes": {
        "scores": [],
        "blocked": false,
        "categories": []
      },
      "score": -1.7523338794708252,
      "citationMetadata": {
        "citations": []
      },
      "content": "```python\nimport unittest\n\nclass TestReverseString(unittest.TestCase):\n\n    def test_reverse_string(self):\n        input_string = \"Hello World\"\n        expected_output = \"dlroW olleH\"\n        output = reverse_string(input_string)\n        self.assertEqual(output, expected_output)\n\nif __name__ == '__main__':\n    unittest.main()\n```"
    }
  ],
}

일괄 응답 요청

Google Cloud 콘솔 또는 Python용 Vertex AI SDK를 사용하여 코드 생성 일괄 응답을 만들 수 있습니다. 제출하는 입력 항목이 많을수록 일괄 생성 프로세스를 완료하는 데 시간이 오래 걸립니다.

REST

Vertex AI API를 사용하여 코드 프롬프트를 테스트하려면 POST 요청을 게시자 모델 엔드포인트로 전송합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 이름
  • BP_JOB_NAME: 작업 이름
  • MODEL_PARAM: 모델 매개변수 및 해당 값을 지정하는 키-값 쌍 목록. 예를 들어 모델의 maxOutputTokenstemperature를 지정할 수 있습니다. 자세한 내용은 코드 생성 매개변수를 참조하세요.
  • INPUT_URI: 입력 소스 URI. 입력 소스는 Cloud Storage 버킷의 BigQuery 테이블 또는 JSONL 파일입니다.
  • OUTPUT_URI: 출력 대상 URI

HTTP 메서드 및 URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs

JSON 요청 본문:

{
    "name": "BP_JOB_NAME",
    "displayName": "BP_JOB_NAME",
    "model": "publishers/google/models/text-bison",
    "model_parameters": "MODEL_PARAM"
    "inputConfig": {
      "instancesFormat":"bigquery",
      "bigquerySource":{
        "inputUri" : "INPUT_URI"
      }
    },
    "outputConfig": {
      "predictionsFormat":"bigquery",
      "bigqueryDestination":{
        "outputUri": "OUTPUT_URI"
    }
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/{PROJECT_ID}/locations/us-central1/batchPredictionJobs/{BATCH_JOB_ID}",
  "displayName": "BP_sample_publisher_BQ_20230712_134650",
  "model": "projects/{PROJECT_ID}/locations/us-central1/models/text-bison",
  "inputConfig": {
    "instancesFormat": "bigquery",
    "bigquerySource": {
      "inputUri": "bq://sample.text_input"
    }
  },
  "modelParameters": {},
  "outputConfig": {
    "predictionsFormat": "bigquery",
    "bigqueryDestination": {
      "outputUri": "bq://sample.llm_dataset.embedding_out_BP_sample_publisher_BQ_20230712_134650"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2023-07-12T20:46:52.148717Z",
  "updateTime": "2023-07-12T20:46:52.148717Z",
  "labels": {
    "owner": "sample_owner",
    "product": "llm"
  },
  "modelVersionId": "1",
  "modelMonitoringStatus": {}
}

응답에는 일괄 작업의 고유 식별자가 포함됩니다. 작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다. 예를 들면 다음과 같습니다.

curl \
  -X GET \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 확인하세요.

from vertexai.preview.language_models import CodeGenerationModel
code_model = CodeGenerationModel.from_pretrained("code-bison")
batch_prediction_job = code_model.batch_predict(
  dataset=["gs://BUCKET_NAME/test_table.jsonl"],
  destination_uri_prefix="gs://BUCKET_NAME/tmp/2023-05-25-vertex-LLM-Batch-Prediction/result3",
  # Optional:
  model_parameters={
      "maxOutputTokens": "200",
      "temperature": "0.2",
  },
)
print(batch_prediction_job.display_name)
print(batch_prediction_job.resource_name)
print(batch_prediction_job.state)

일괄 출력 검색

일괄 예측 태스크가 완료되면 출력은 요청에 지정한 Cloud Storage 버킷이나 BigQuery 테이블에 저장됩니다.

다음 단계