Gemma 是一系列先進的輕量級開放式模型,採用與建立 Gemini 模型時相同的研究成果和技術。您可以在 Apache Beam 推論管道中使用 Gemma 模型。 開放權重是指發布模型的預先訓練參數或權重。不會提供原始資料集、模型架構和訓練程式碼等詳細資料。
如需可用模型清單和各模型的詳細資料,請參閱 Gemma 模型總覽。
如要瞭解如何下載及使用模型,請參閱「使用 KerasNLP 開始使用 Gemma」。
如要下載模型,請參閱 Gemma 模型。
用途
您可以使用 Gemma 模型搭配 Dataflow 進行情緒分析。透過 Dataflow 和 Gemma 模型,您可以處理顧客評論等事件。透過模型分析評論,然後產生建議。結合使用 Gemma 和 Apache Beam,即可順利完成這項工作流程。
支援與限制
Apache Beam 和 Dataflow 支援 Gemma 開放模型,但須符合下列條件:
- 適用於使用 Apache Beam Python SDK 2.46.0 以上版本的批次和串流管道。
- Dataflow 工作必須使用 Runner v2。
- Dataflow 工作必須使用 GPU。 如需 Dataflow 支援的 GPU 類型清單,請參閱適用情形。建議使用 T4 和 L4 GPU 類型。
- 模型必須下載並儲存為
.keras
檔案格式。 - 建議使用 TensorFlow 模型處理常式,但並非必要。
必要條件
- 透過 Kaggle 存取 Gemma 模型。
- 填妥同意聲明表單並接受條款及細則。
- 下載 Gemma 模型。以
.keras
檔案格式儲存至 Dataflow 工作可存取的位置,例如 Cloud Storage 值區。指定模型路徑變數的值時,請使用這個儲存位置的路徑。 - 如要在 Dataflow 上執行工作,請建立自訂容器映像檔。這個步驟可讓您在 Dataflow 服務上使用 GPU 執行管道。
- 如要查看包含建立 Docker 映像檔的完整工作流程,請參閱 GitHub 上的「在 Dataflow 串流上使用 Gemma 執行推論」。
- 如要進一步瞭解如何建構 Docker 映像檔,請參閱「使用 GPU 執行管道」一文中的「建構自訂容器映像檔」一節。
- 如要使用 Docker 將容器推送至 Artifact Registry,請參閱「為 Dataflow 建構自訂容器映像檔」一文中的「建構及推送映像檔」一節。
在管道中使用 Gemma
如要在 Apache Beam 管道中使用 Gemma 模型,請按照下列步驟操作。
在 Apache Beam 程式碼中,匯入管道依附元件後,請加入已儲存模型的路徑:
model_path = "MODEL_PATH"
請將
MODEL_PATH
改成您儲存下載模型的路徑。舉例來說,如果您將模型儲存到 Cloud Storage 值區,路徑格式為gs://STORAGE_PATH/FILENAME.keras
。Gemma 模型在 Keras 中的實作方式具有
generate()
方法,可根據提示生成文字。如要將元素傳遞至generate()
方法,請使用自訂推論函式。def gemma_inference_function(model, batch, inference_args, model_id): vectorized_batch = np.stack(batch, axis=0) # The only inference_arg expected here is a max_length parameter to # determine how many words are included in the output. predictions = model.generate(vectorized_batch, **inference_args) return utils._convert_to_result(batch, predictions, model_id)
執行管道,並指定訓練模型的路徑。這個範例使用 TensorFlow 模型處理常式。
class FormatOutput(beam.DoFn): def process(self, element, *args, **kwargs): yield "Input: {input}, Output: {output}".format(input=element.example, output=element.inference) # Instantiate a NumPy array of string prompts for the model. examples = np.array(["Tell me the sentiment of the phrase 'I like pizza': "]) # Specify the model handler, providing a path and the custom inference function. model_handler = TFModelHandlerNumpy(model_path, inference_fn=gemma_inference_function) with beam.Pipeline() as p: _ = (p | beam.Create(examples) # Create a PCollection of the prompts. | RunInference(model_handler, inference_args={'max_length': 32}) # Send the prompts to the model and get responses. | beam.ParDo(FormatOutput()) # Format the output. | beam.Map(print) # Print the formatted output. )
後續步驟
- 建立使用 RunInference 和 Gemma 的 Dataflow 串流管道。
- 在 Google Colab 中使用 Gemma 開放模型執行推論 (需要 Colab Enterprise)。
- 使用 GPU 執行管道。
- 調整模型。