建構基於容器的組件

基於容器的組件提供彈性,可將以任何語言編寫的程式碼整合到您的管線中,只要您可以在 Docker 容器中執行該程式碼即可。

如果您是 TFX 管線的新手,請深入瞭解 TFX 管線的核心概念

建立基於容器的組件

基於容器的組件由容器化的命令列程式提供支援。 如果您已擁有容器映像檔,則可以使用 TFX,方法是使用 create_container_component 函式宣告輸入和輸出,藉此從容器映像檔建立組件。 函式參數

  • name:組件的名稱。
  • inputs:將輸入名稱對應至類型的字典。 outputs:將輸出名稱對應至類型的字典 parameters:將參數名稱對應至類型的字典。
  • image:容器映像檔名稱,以及選用的映像檔標籤。
  • command:容器進入點命令列。 不在 Shell 中執行。 命令列可以使用預留位置物件,這些物件在編譯時會替換為輸入、輸出或參數。 預留位置物件可從 tfx.dsl.component.experimental.placeholders 匯入。 請注意,不支援 Jinja 範本。

傳回值:繼承自 base_component.BaseComponent 的 Component 類別,可於管線內部具現化和使用。

預留位置

對於具有輸入或輸出的組件,command 通常需要具有預留位置,這些預留位置會在執行階段替換為實際資料。 系統提供數個預留位置用於此目的

  • InputValuePlaceholder:輸入成品值的預留位置。 在執行階段,此預留位置會替換為成品值的字串表示法。

  • InputUriPlaceholder:輸入成品引數 URI 的預留位置。 在執行階段,此預留位置會替換為輸入成品資料的 URI。

  • OutputUriPlaceholder:輸出成品引數 URI 的預留位置。 在執行階段,此預留位置會替換為組件應儲存輸出成品資料的 URI。

深入瞭解 TFX 組件命令列預留位置

基於容器的組件範例

以下是非 Python 組件的範例,可下載、轉換和上傳資料

import tfx.v1 as tfx

grep_component = tfx.dsl.components.create_container_component(
    name='FilterWithGrep',
    inputs={
        'text': tfx.standard_artifacts.ExternalArtifact,
    },
    outputs={
        'filtered_text': tfx.standard_artifacts.ExternalArtifact,
    },
    parameters={
        'pattern': str,
    },
    # The component code uses gsutil to upload the data to Google Cloud Storage, so the
    # container image needs to have gsutil installed and configured.
    image='google/cloud-sdk:278.0.0',
    command=[
        'sh', '-exc',
        '''
          pattern="$1"
          text_uri="$3"/data  # Adding suffix, because currently the URI are "directories". This will be fixed soon.
          text_path=$(mktemp)
          filtered_text_uri="$5"/data  # Adding suffix, because currently the URI are "directories". This will be fixed soon.
          filtered_text_path=$(mktemp)

          # Getting data into the container
          gsutil cp "$text_uri" "$text_path"

          # Running the main code
          grep "$pattern" "$text_path" >"$filtered_text_path"

          # Getting data out of the container
          gsutil cp "$filtered_text_path" "$filtered_text_uri"
        ''',
        '--pattern', tfx.dsl.placeholders.InputValuePlaceholder('pattern'),
        '--text', tfx.dsl.placeholders.InputUriPlaceholder('text'),
        '--filtered-text', tfx.dsl.placeholders.OutputUriPlaceholder('filtered_text'),
    ],
)