バッチコード予測を取得する

レスポンスの一括取得は、レスポンスのレイテンシが重要でない場合に、大量のコード リクエストを効率的に送信する方法です。オンライン レスポンスの取得では一度に 1 つの入力リクエストに制限されますが、バッチ予測では多数のコード生成モデルのリクエストが 1 つのバッチ リクエストで送信されます。Vertex AI の表形式データのバッチ予測と同様に、出力場所を決定して入力を追加すると、レスポンスが出力場所に非同期で入力されます。

バッチ リクエストを送信して結果を確認したら、コード生成基盤モデルをチューニングして、特定のタスクに対する結果を改善できます。チューニングしたら、チューニング済みモデルを送信してバッチ生成できます。モデルのチューニングの詳細については、言語基盤モデルをチューニングするをご覧ください。

バッチ予測をサポートするコードモデル

  • code-bison

入力を準備する

バッチ リクエストの入力は、BigQuery テーブルまたは Cloud Storage の JSON Lines(JSONL)ファイルとして保存可能なプロンプトのリストです。1 つのリクエストには最大 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 テーブルを示しています。

接頭辞
"ある年がうるう年かどうかを判断する Python 関数を記述:"
"文字列を反転する Python コードの単体テストを作成:"

BigQuery 出力の例

接頭辞 予測 ステータス
"ある年がうるう年かどうかを判断する 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 コンソールまたは Vertex AI SDK for Python を使用して作成できます。送信する入力アイテムが多いほど、バッチ生成プロセスの完了にかかる時間が長くなります。

REST

Vertex AI API を使用してコード プロンプトをテストするには、パブリッシャー モデル エンドポイントに POST リクエストを送信します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: Google Cloud Platform プロジェクトの名前です。
  • BP_JOB_NAME: ジョブ名。
  • MODEL_PARAM: モデル パラメータとその値を指定する Key-Value ペアのリスト。たとえば、モデルの maxOutputTokenstemperature を指定できます。詳細については、コード生成パラメータをご覧ください。
  • INPUT_URI: 入力ソース URI。入力ソースは、BigQuery テーブルまたは Cloud Storage バケット内の JSONL ファイルです。
  • OUTPUT_URI: 出力ターゲット URI。

HTTP メソッドと URL:

POST http://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 \
"http://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 "http://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" \
http://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID

Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、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 テーブルに出力が保存されます。

次のステップ