使用声明式自动化捆绑包提供 Feature View

Important

此功能以个人预览版提供。 若要试用,请联系 Azure Databricks 联系人。

声明式自动化捆绑包(前称 Databricks 资产捆绑包)使您能够通过程序化验证、部署和运行 Azure Databricks 资源,如功能视图及其服务端点。 请参阅什么是声明性自动化捆绑包?

本教程构建了一个捆绑包,声明两个流式 功能视图,将它们实体化到在线商店,并通过 FeatureSpec 和功能服务端点提供服务。 然后你查询该端点,改变它所服务的特征,然后把所有东西拆解。

有关特征视图及其物化的内容,请参见 “使用声明式自动化捆绑管理特征视图”,其中有详细说明。 如需改为使用 Python API 创建 FeatureSpec 和端点,请参见“提供功能视图”。

每一步都显示了YAML和Python的配置。 选择一种语言,页面会跟随你的选择。

Requirements

若要完成本教程,需要满足以下条件:

  • Databricks CLI 版本 1.26.0 或更高。 运行 databricks --version 以检查。 请参阅安装或更新 Databricks CLI。
  • 启用 Unity Catalog 的工作区。 请参阅 要求。
  • 允许创建特征并将其物化。 请参阅 权限。
  • 创建模型服务端点的权限。 请参阅 标识和访问权限。
  • 一个现有的在线商店。 参见 创建在线商店。
  • 一个现有的 Stream。 流不是捆绑资源,因此先创建它,并在捆绑中按名称引用它。 参见 创建流。
  • Python 3.10 或更高版本,用于在 Python 中声明资源。

在 bundle 中提供服务资源

一个包通过两种资源类型提供 Feature Views:

  • FeatureSpec:一个列出要提供服务的特征的 Unity 目录函数。 它不包含任何特征值。 为其服务的端点会从特征视图所具现的在线表中读取这些数据。 请参阅“使用FeatureSpec提供特征”,以及配置参考 feature_spec。
  • 功能服务端点:提供 FeatureSpec 而不是模型的模型服务端点。 捆绑包将其声明为 model_serving_endpoints 资源。 有关配置参考,请参见 model_serving_endpoint。

从捆绑包中提供功能视图

以下步骤包括构建和部署该捆绑包、查询端点、更改其提供的内容以及进行清理。

设置身份验证

首先,在你的开发机器上的Databricks CLI和你的Azure Databricks工作区之间设置身份验证。 此页假定你想要使用 OAuth 用户到机器(U2M)身份验证,以及一个名为 DEFAULT 的相应 Azure Databricks 配置文件进行身份验证。

注意

U2M 身份验证适用于实时尝试这些步骤。 对于完全自动化的工作流,Databricks 建议改用 OAuth 计算机到计算机 (M2M) 身份验证。 请参阅 授权服务主体使用 OAuth 访问 Azure Databricks 中的 M2M 身份验证设置说明。

  1. 通过对每个目标工作区运行以下命令,使用 Databricks CLI 在本地启动 OAuth 令牌管理。

    在以下命令中,将 <workspace-url> 替换为 Azure Databricks per-workspace URL,例如 https://adb-1234567890123456.7.azuredatabricks.net。

    databricks auth login --host <workspace-url>
    
  2. Databricks CLI 会提示您将输入的信息另存为 Azure Databricks 配置文件。 按 Enter 确认建议的配置文件名称,或输入新配置文件或已有配置文件的名称。 使用输入的信息覆盖同名的任何现有配置文件。 可以使用个人资料在多个工作区之间快速切换身份验证上下文。

    若要获取任何现有配置文件的列表,请在单独的终端或命令提示符中使用 Databricks CLI 来运行 databricks auth profiles 命令。 要查看特定配置文件的现有设置,请运行命令 databricks auth env --profile <profile-name>。

  3. 在 Web 浏览器中,按照屏幕上的说明登录到 Azure Databricks 工作区。

  4. 要查看个人资料的当前 OAuth 令牌值和令牌即将到期的时间戳,请运行以下命令之一:

    • databricks auth token --host <workspace-url>
    • databricks auth token -p <profile-name>
    • databricks auth token --host <workspace-url> -p <profile-name>

    如果你有多个配置文件具有相同的--host 值,则可能会需要同时指定 --host 和 -p 选项,以帮助 Databricks CLI 找到正确的匹配的 OAuth 令牌信息。

创建捆绑包

为捆绑包创建一个空目录,根目录 databricks.yml 有一个文件,旁边有一个 resources 目录。

YAML

以下每一步都会在 resources/ 下添加一个文件:

databricks.yml
resources/
  streaming_features.yml
  feature_spec.yml
  serving_endpoint.yml

databricks.yml 包含捆绑包名称、 include 加载所有文件的 resources/条目,以及资源引用的变量:

bundle:
  name: feature-serving-quickstart

include:
  - resources/*.yml

variables:
  catalog:
    description: The catalog that the Feature Views and the FeatureSpec are written to.
    default: main
  schema:
    description: The schema that the Feature Views and the FeatureSpec are written to.
    default: features_demo
  stream:
    description: The three-level name of a Stream registered in Unity Catalog.
    default: main.features_demo.events
  online_store:
    description: The online store that serves the features.
    default: my_online_store
  endpoint_name:
    description: The name of the Feature Serving endpoint.
    default: event-features

Python

Python 中声明的资源只能通过databricks.yml中的python映射找到。 没有它,捆绑包可以成功验证并部署,但没有资源,所以现在就添加它:

bundle:
  name: feature-serving-quickstart

python:
  venv_path: .venv
  resources:
    - 'resources:load_resources'

variables:
  catalog:
    description: The catalog that the Feature Views and the FeatureSpec are written to.
    default: main
  schema:
    description: The schema that the Feature Views and the FeatureSpec are written to.
    default: features_demo
  stream:
    description: The three-level name of a Stream registered in Unity Catalog.
    default: main.features_demo.events
  online_store:
    description: The online store that serves the features.
    default: my_online_store
  endpoint_name:
    description: The name of the Feature Serving endpoint.
    default: event-features

创建项目及其虚拟环境,并添加该包:

uv init --bare
uv venv .venv
uv add databricks-bundles

用命名resources/__init__.py的函数创建databricks.yml:

from databricks.bundles.core import Bundle, Resources


def load_resources(bundle: Bundle) -> Resources:
    resources = Resources()
    # The following steps add resources here.
    return resources

声明特征视图及其物化

两个功能视图都读取同一个流,并在最近滚动的 90 分钟窗口内按键进行汇总。 events_90m 计数事件,并 amount_sum_90m 对 value.amount进行求和。 一个实体化集以流式模式写入在线商店。 有关每个配置键的含义,请参阅 功能视图教程的第 4 步。

流式特征视图将输入列作为进入流记录的路径,因此请在示例显示 value.*的位置替换流模式所使用的名称。

YAML

创建 resources/streaming_features.yml:

resources:
  features:
    events_90m:
      full_name: ${var.catalog}.${var.schema}.events_90m
      description: Events per key over a trailing 90 minutes
      source:
        stream_source:
          full_name: ${var.stream}
      function:
        aggregation_function:
          count_function:
            input: value.amount
          time_window:
            rolling:
              window_duration: 5400s
      entities:
        - name: value.key
      timeseries_column:
        name: value.event_timestamp

    amount_sum_90m:
      full_name: ${var.catalog}.${var.schema}.amount_sum_90m
      description: Sum of amount per key over a trailing 90 minutes
      source:
        stream_source:
          full_name: ${var.stream}
      function:
        aggregation_function:
          sum:
            input: value.amount
          time_window:
            rolling:
              window_duration: 5400s
      entities:
        - name: value.key
      timeseries_column:
        name: value.event_timestamp

  materialization_sets:
    serving_online:
      materialized_features:
        - feature_name: ${resources.features.events_90m.full_name}
          online_store_config:
            online_store_name: ${var.online_store}
            catalog_name: ${var.catalog}
            schema_name: ${var.schema}
            table_name_prefix: serving_online
          streaming_mode:
            mode: STREAMING_MODE_TYPE_RTM
        - feature_name: ${resources.features.amount_sum_90m.full_name}
          online_store_config:
            online_store_name: ${var.online_store}
            catalog_name: ${var.catalog}
            schema_name: ${var.schema}
            table_name_prefix: serving_online
          streaming_mode:
            mode: STREAMING_MODE_TYPE_RTM

Python

将导入添加到 resources/__init__.py:

from databricks.bundles.features import (
    AggregationFunction,
    CountFunction,
    DataSource,
    EntityColumn,
    Feature,
    Function,
    RollingWindow,
    StreamSource,
    SumFunction,
    TimeseriesColumn,
    TimeWindow,
)
from databricks.bundles.materialization_sets import (
    MaterializationSet,
    MaterializedFeature,
    OnlineStoreConfig,
    StreamingMode,
    StreamingModeStreamingModeType,
)

然后将此加到正 load_resources文中:

resources.add_feature(
    'events_90m',
    Feature(
        full_name='${var.catalog}.${var.schema}.events_90m',
        description='Events per key over a trailing 90 minutes',
        source=DataSource(stream_source=StreamSource(full_name='${var.stream}')),
        function=Function(
            aggregation_function=AggregationFunction(
                count_function=CountFunction(input='value.amount'),
                time_window=TimeWindow(rolling=RollingWindow(window_duration='5400s')),
            )
        ),
        entities=[EntityColumn(name='value.key')],
        timeseries_column=TimeseriesColumn(name='value.event_timestamp'),
    ),
)

resources.add_feature(
    'amount_sum_90m',
    Feature(
        full_name='${var.catalog}.${var.schema}.amount_sum_90m',
        description='Sum of amount per key over a trailing 90 minutes',
        source=DataSource(stream_source=StreamSource(full_name='${var.stream}')),
        function=Function(
            aggregation_function=AggregationFunction(
                sum=SumFunction(input='value.amount'),
                time_window=TimeWindow(rolling=RollingWindow(window_duration='5400s')),
            )
        ),
        entities=[EntityColumn(name='value.key')],
        timeseries_column=TimeseriesColumn(name='value.event_timestamp'),
    ),
)

resources.add_materialization_set(
    'serving_online',
    MaterializationSet(
        materialized_features=[
            MaterializedFeature(
                feature_name='${resources.features.events_90m.full_name}',
                online_store_config=OnlineStoreConfig(
                    online_store_name='${var.online_store}',
                    catalog_name='${var.catalog}',
                    schema_name='${var.schema}',
                    table_name_prefix='serving_online',
                ),
                streaming_mode=StreamingMode(
                    mode=StreamingModeStreamingModeType.STREAMING_MODE_TYPE_RTM
                ),
            ),
            MaterializedFeature(
                feature_name='${resources.features.amount_sum_90m.full_name}',
                online_store_config=OnlineStoreConfig(
                    online_store_name='${var.online_store}',
                    catalog_name='${var.catalog}',
                    schema_name='${var.schema}',
                    table_name_prefix='serving_online',
                ),
                streaming_mode=StreamingMode(
                    mode=StreamingModeStreamingModeType.STREAMING_MODE_TYPE_RTM
                ),
            ),
        ]
    ),
)

添加功能规范

FeatureSpec 列出了该端点提供的功能。 features 中的每个条目都指定一个 Feature View,并带有 declarative_feature。

FeatureSpec 只能在它命名的每个功能视图被实体化到在线商店后才会创建。 ${resources.features...}中的declarative_feature引用使规范依赖于特征视图events_90m和 amount_sum_90m,并lifecycle.depends_on添加了无参考表示的对实体化集serving_online的依赖。 这个组合包会在这三者都完成之后创建该规格,并在它们之前删除它。 参见 “FeatureSpec必须满足的规则”。

YAML

创建 resources/feature_spec.yml:

resources:
  feature_specs:
    event_features:
      name: ${var.catalog}.${var.schema}.event_features
      features:
        - declarative_feature:
            feature: ${resources.features.events_90m.full_name}
        - declarative_feature:
            feature: ${resources.features.amount_sum_90m.full_name}
      lifecycle:
        depends_on:
          - resource: materialization_sets.serving_online

Python

将导入添加到 resources/__init__.py:

from databricks.bundles.feature_specs import (
    DeclarativeFeature,
    DependsOn,
    FeatureSpec,
    Features,
    Lifecycle,
)

然后将此加到正 load_resources文中:

resources.add_feature_spec(
    'event_features',
    FeatureSpec(
        name='${var.catalog}.${var.schema}.event_features',
        features=[
            Features(
                declarative_feature=DeclarativeFeature(
                    feature='${resources.features.events_90m.full_name}'
                )
            ),
            Features(
                declarative_feature=DeclarativeFeature(
                    feature='${resources.features.amount_sum_90m.full_name}'
                )
            ),
        ],
        lifecycle=Lifecycle(depends_on=[DependsOn(resource='materialization_sets.serving_online')]),
    ),
)

添加功能服务端点

该端点为 entity_name 命名的 FeatureSpec 提供服务。 由于 entity_name 引用了规范的 name,捆绑包会在规范之后创建端点,如 Deploy 中的输出所示,并在规范之前将其删除。启用 scale_to_zero_enabled 时,端点在未收到请求时会将其计算资源缩减至零。

YAML

创建 resources/serving_endpoint.yml:

resources:
  model_serving_endpoints:
    event_endpoint:
      name: ${var.endpoint_name}
      config:
        served_entities:
          - entity_name: ${resources.feature_specs.event_features.name}
            workload_size: Small
            scale_to_zero_enabled: true

Python

将导入添加到 resources/__init__.py:

from databricks.bundles.model_serving_endpoints import (
    EndpointCoreConfigInput,
    ModelServingEndpoint,
    ServedEntityInput,
)

然后将此加到正 load_resources文中:

resources.add_model_serving_endpoint(
    'event_endpoint',
    ModelServingEndpoint(
        name='${var.endpoint_name}',
        config=EndpointCoreConfigInput(
            served_entities=[
                ServedEntityInput(
                    entity_name='${resources.feature_specs.event_features.name}',
                    workload_size='Small',
                    scale_to_zero_enabled=True,
                )
            ]
        ),
    ),
)

部署

检查配置,然后查看部署执行的具体操作:

databricks bundle validate
databricks bundle plan

首次部署时,所有五个资源均报告 create:

create feature_specs.event_features
create features.amount_sum_90m
create features.events_90m
create materialization_sets.serving_online
create model_serving_endpoints.event_endpoint

Plan: 5 to add, 0 to change, 0 to delete, 0 unchanged

将捆绑包部署到工作区:

databricks bundle deploy

部署按依赖顺序创建资源,并在端点准备好时返回,这需要几分钟时间:

Uploading bundle files to /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default/files...
Created features.events_90m
Created features.amount_sum_90m
Created materialization_sets.serving_online
Created feature_specs.event_features
Created model_serving_endpoints.event_endpoint
Files: 4 uploaded, 0 deleted
Resources: 5 created, 0 changed, 0 deleted, 0 unchanged

查询终结点

将要查找的键作为 dataframe_records 发送。 记录以特征视图实体路径的最后一段来命名每个键,因此 value.key 变为 key:

databricks serving-endpoints query event-features --json '{"dataframe_records": [{"key": 1280}, {"key": 1188}, {"key": 42}, {"key": 10001}]}'

响应为每个记录包含一个对象,按请求顺序排列。 每个对象对每个功能视图包含一个值,以功能视图的名称为键,但不含其目录和架构:

{
  "outputs": [
    {
      "events_90m": 10,
      "amount_sum_90m": 10
    },
    {
      "events_90m": 11,
      "amount_sum_90m": 11
    },
    {
      "events_90m": 9,
      "amount_sum_90m": 10
    },
    {
      "events_90m": 0,
      "amount_sum_90m": null
    }
  ]
}

窗口中没有事件的键会返回 0 计数和 null 和,就像键 10001 一样。 每个键都会返回这些值,直到物质化流水线写入第一批行,而这可能发生在 databricks bundle deploy 返回后的几分钟之后。 有关查询端点的其他方式,请参见 “查询端点”。

从 FeatureSpec 中移除特征视图

对 FeatureSpec 的任何更改都会删除并重新创建它。 一个正在运行的端点会继续提供其构建时所基于的 FeatureSpec 中的特征,所以保留规范名称的更改不会影响端点。 参见 更新实时功能服务端点的依赖项。

要查看这一点,请从规范中移除 amount_sum_90m 并保留其名称:

YAML

   feature_specs:
     event_features:
       name: ${var.catalog}.${var.schema}.event_features
       features:
         - declarative_feature:
             feature: ${resources.features.events_90m.full_name}
-        - declarative_feature:
-            feature: ${resources.features.amount_sum_90m.full_name}
       lifecycle:

Python

         features=[
             Features(
                 declarative_feature=DeclarativeFeature(
                     feature='${resources.features.events_90m.full_name}'
                 )
             ),
-            Features(
-                declarative_feature=DeclarativeFeature(
-                    feature='${resources.features.amount_sum_90m.full_name}'
-                )
-            ),
         ],

databricks bundle plan 仅报告将重新创建规范:

recreate feature_specs.event_features

Plan: 1 to add, 0 to change, 1 to delete, 4 unchanged

databricks bundle deploy 在重新创建规格前要求确认:

Uploading bundle files to /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default/files...

This action will result in the deletion or recreation of the following feature specs.
Grants on them that are not declared in the bundle are lost:
  recreate resources.feature_specs.event_features

Would you like to proceed? [y/N]: y
Recreated feature_specs.event_features
Files: 1 uploaded, 0 deleted
Resources: 1 created, 0 changed, 1 deleted, 4 unchanged

端点仍然返回这两种特性:

databricks serving-endpoints query event-features --json '{"dataframe_records": [{"key": 1188}, {"key": 42}]}'
{
  "outputs": [
    {
      "events_90m": 16,
      "amount_sum_90m": 20
    },
    {
      "events_90m": 12,
      "amount_sum_90m": 11
    }
  ]
}

重命名 FeatureSpec

要更改端点提供的内容,请给其 FeatureSpec 一个新名称。 端点 entity_name 引用了名称,所以部署也会更新该端点,端点会持续用原 FeatureSpec 功能回复请求,直到更新完成。

YAML

   feature_specs:
     event_features:
-      name: ${var.catalog}.${var.schema}.event_features
+      name: ${var.catalog}.${var.schema}.event_features_v2

Python

     FeatureSpec(
-        name='${var.catalog}.${var.schema}.event_features',
+        name='${var.catalog}.${var.schema}.event_features_v2',

databricks bundle plan 报告规范的重建和端点的更新:

recreate feature_specs.event_features
update model_serving_endpoints.event_endpoint

Plan: 1 to add, 1 to change, 1 to delete, 3 unchanged

databricks bundle deploy 请求确认,重新创建规范,并在端点更新后返回:

Uploading bundle files to /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default/files...

This action will result in the deletion or recreation of the following feature specs.
Grants on them that are not declared in the bundle are lost:
  recreate resources.feature_specs.event_features

Would you like to proceed? [y/N]: y
Recreated feature_specs.event_features
Updated model_serving_endpoints.event_endpoint
Files: 1 uploaded, 0 deleted
Resources: 1 created, 1 changed, 1 deleted, 3 unchanged

端点现在只返回 events_90m:

databricks serving-endpoints query event-features --json '{"dataframe_records": [{"key": 1188}]}'
{
  "outputs": [
    {
      "events_90m": 68
    }
  ]
}

清理

实体化管线会继续运行,端点也会继续服务,直到你删除它们为止。 完成后拆除 bundle:

databricks bundle destroy

databricks bundle destroy 列出它删除的内容并要求确认:

The following resources will be deleted:
  delete resources.feature_specs.event_features
  delete resources.features.amount_sum_90m
  delete resources.features.events_90m
  delete resources.materialization_sets.serving_online
  delete resources.model_serving_endpoints.event_endpoint

This action will result in the deletion of the following Feature Views.
Deleting a Feature View that a FeatureSpec serves is not blocked, and leaves the FeatureSpec stale:
  delete resources.features.amount_sum_90m
  delete resources.features.events_90m

This action will result in the deletion of the following feature specs.
Feature Serving endpoints and training code that use them can no longer load them:
  delete resources.feature_specs.event_features

All files and directories at the following location will be deleted: /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default

Would you like to proceed? [y/N]: y
Destroy: 5 deleted

只有创建实体化功能的用户才能删除它,所以要用部署捆绑包的同一身份来运行 databricks bundle destroy 。 请参阅 delete_materialized_feature()。

Limitations

  • 当特征视图以批处理模式物化时,其在线表仅在物化集首次运行后才存在,因此在同一模式下 databricks bundle deploy 部署的端点会失败。 第一次跑完再跑 databricks bundle deploy 一次。
  • 删除由 FeatureSpec 提供服务的功能视图不会被阻止,并会导致 FeatureSpec 过时。

后续步骤