目录

TorchServe 指标

内容

介绍

Torchserve 的指标可以大致分为前端和后端指标。

前端指标:

  • API请求状态指标

  • 推理请求指标

  • 系统利用率指标

Note: 系统利用率指标定期收集(默认:每分钟一次)

后端指标:

  • 默认模型指标

  • 自定义模型指标

Note: Torchserve 提供了一个 API 来收集自定义模型指标。

默认前端和后端指标显示在默认指标部分。

度量模式

支持三种指标模式,即logprometheuslegacy,默认模式为 log。 可以通过 metrics_mode 配置选项在 config.propertiesTS_METRICS_MODE 环境变量中配置指标模式。 有关 config.properties 和基于环境变量的配置的更多详细信息,请参阅Torchserve 配置文档。

日志模式

log 模式下,指标会被记录下来,并且可以通过指标代理进行聚合。 默认情况下,在 log 模式下,指标会收集于以下位置:

  • 前端指标 - log_directory/ts_metrics.log

  • 后端指标 - log_directory/model_metrics.log

日志文件和指标文件的位置可以在 log4j2.xml 文件中配置

Prometheus 模式

prometheus模式下,指标通过指标API端点以Prometheus格式提供。

Legacy模式

legacy 模式启用与 Torchserve 版本 <= 0.7.1 的兼容性,其中:

  • ts_inference_requests_total, ts_inference_latency_microsecondsts_queue_latency_microseconds 仅通过 指标 API 端点 以 Prometheus 格式提供。

  • 前端指标被记录到 log_directory/ts_metrics.log

  • 后端指标被记录到 log_directory/model_metrics.log

注意:要与版本 <= 0.7.1 完全向后兼容,请在启用 模型指标自动检测 的情况下使用传统指标模式。

入门

使用示例演示自定义指标作为参考:

  1. 创建自定义 指标配置 文件 使用默认的 metrics.yaml 文件。

  2. metrics_config 个参数设置为正在使用的 config.properties 中的 YAML 文件路径:

    metrics_config=/<path>/<to>/<metrics>/<config>/<file>/metrics.yaml
    

    如果未指定 metrics_config 个参数,将使用默认的 metrics.yaml 配置文件。

  3. 设置您想要的指标模式,使用metrics_mode配置选项在config.propertiesTS_METRICS_MODE环境变量中。如果没有设置,则默认使用log模式。

  4. 使用 自定义指标 API处理器中发出自定义指标(如果有)。

  5. 运行torchserve并在config.properties文件路径后指定ts-config标志:

    torchserve --ncs --start --model-store model_store --models my_model=model.mar --ts-config /<path>/<to>/<config>/<file>/config.properties

  6. 根据选择的模式收集指标:

    如果 log 模式,检查:

    • 前端指标 - log_directory/ts_metrics.log

    • 后端指标 - log_directory/model_metrics.log

    否则,如果使用prometheus模式,请使用Metrics API 端点

配置指标

TorchServe 在 yaml 文件中定义了指标配置,包括前端指标(例如 ts_metrics) 和后端指标(例如 model_metrics)。 当 TorchServe 启动时,会加载指标定义,并根据 metrics_mode 配置将相应的指标作为日志或通过 指标 API 端点 提供。

动态更新指标配置文件不被支持。为了应对对指标配置文件的更新,Torchserve 将需要重新启动。

模型指标自动检测

默认情况下,未在指标配置文件中定义的指标不会记录在指标日志文件中,也无法通过指标API端点获取。 后端模型指标可以通过在config.properties中将model_metrics_auto_detect设置为trueauto-detected, 或者使用TS_MODEL_METRICS_AUTO_DETECT环境变量。默认情况下,模型指标自动检测是禁用的。

Warning: Using auto-detection of backend metrics will have performance impact in the form of latency overhead, typically at model load and first inference for a given model. This cold start behavior is because, it is during model load and first inference that new metrics are typically emitted by the backend and is detected and registered by the frontend. Subsequent inferences could also see performance impact if new metrics are updated for the first time. For use cases where multiple models are loaded/unloaded often, the latency overhead can be mitigated by specifying known metrics in the metrics configuration file, ahead of time.

配置指标格式

指标配置yaml文件使用Prometheus指标类型术语进行格式化:

dimensions: # dimension aliases
  - &model_name "ModelName"
  - &level "Level"

ts_metrics:  # frontend metrics
  counter:  # metric type
    - name: NameOfCounterMetric  # name of metric
      unit: ms  # unit of metric
      dimensions: [*model_name, *level]  # dimension names of metric (referenced from the above dimensions dict)
  gauge:
    - name: NameOfGaugeMetric
      unit: ms
      dimensions: [*model_name, *level]
  histogram:
    - name: NameOfHistogramMetric
      unit: ms
      dimensions: [*model_name, *level]

model_metrics:  # backend metrics
  counter:  # metric type
    - name: InferenceTimeInMS  # name of metric
      unit: ms  # unit of metric
      dimensions: [*model_name, *level]  # dimension names of metric (referenced from the above dimensions dict)
    - name: NumberOfMetrics
      unit: count
      dimensions: [*model_name]
  gauge:
    - name: GaugeModelMetricNameExample
      unit: ms
      dimensions: [*model_name, *level]
  histogram:
    - name: HistogramModelMetricNameExample
      unit: ms
      dimensions: [*model_name, *level]

Note: 当在指标配置文件中添加自定义 model_metrics 时,请确保在列表末尾包含 ModelNameLevel 维度名称,因为它们是默认通过以下自定义指标 API 包含的: add_metric, add_counter, add_time, add_sizeadd_percent

默认指标配置

默认指标在默认指标配置文件 metrics.yaml 中提供。

度量类型

TorchServe指标使用与Prometheus指标类型一致的指标类型

度量类型是Metric对象的属性。当添加自定义度量时,用户将被限制使用现有的度量类型。

class MetricTypes(enum.Enum):
    COUNTER = "counter"
    GAUGE = "gauge"
    HISTOGRAM = "histogram"

默认指标

默认前端指标

指标名称 类型 单元 维度 语义
Requests2XX 计数器 计数 级别,主机名 200-300状态码范围内的请求总数
Requests4XX 计数器 计数 级别,主机名 总共有400-500状态码范围内的请求
Requests5XX 计数器 计数 级别,主机名 总共有超过500个请求的响应状态码
ts_inference_requests_total 计数器 计数 模型名称,模型版本,主机名 接收到的推理请求总数
ts_inference_latency_microseconds 计数器 微秒 模型名称,模型版本,主机名 总推理延迟以微秒为单位
ts_queue_latency_microseconds 计数器 微秒 模型名称,模型版本,主机名 总队列延迟以微秒为单位
QueueTime 量具 毫秒 级别,主机名 在请求队列中花费的时间以毫秒为单位
WorkerThreadTime 量具 毫秒 级别,主机名 在工作线程中花费的时间(不包括后端响应时间)以毫秒为单位
WorkerLoadTime 量具 毫秒 工人名称,级别,主机名 加载模型所需的时间以毫秒为单位
CPUUtilization 量具 百分比 级别,主机名 主机CPU利用率
MemoryUsed 量具 兆字节 级别,主机名 主机上使用的内存
MemoryAvailable 量具 兆字节 级别,主机名 主机可用内存
MemoryUtilization 量具 百分比 级别,主机名 主机内存使用率
DiskUsage 量具 吉字节 级别,主机名 主机上的磁盘使用量
DiskUtilization 量具 百分比 级别,主机名 主机上的磁盘使用量
DiskAvailable 量具 吉字节 级别,主机名 主机可用磁盘空间
GPUMemoryUtilization 量具 百分比 级别, 设备ID, 主机名 主机GPU内存使用率,DeviceId
GPUMemoryUsed 量具 兆字节 级别, 设备ID, 主机名 主机上使用的GPU内存,DeviceId
GPUUtilization 量具 百分比 级别, 设备ID, 主机名 主机上的GPU利用率,DeviceId

默认后端指标

指标名称 类型 单元 维度 语义
HandlerTime 量具 ms 模型名称, 等级, 主机名 后端处理器花费时间
PredictionTime 量具 ms 模型名称, 等级, 主机名 后端预测时间

自定义指标 API

TorchServe 使 处理器 能够发出自定义指标,这些指标将根据配置的 metrics_mode 提供。

示例:使用自定义处理器展示 自定义指标API的使用.

自定义处理程序的代码提供了当前请求的上下文,该上下文包含一个metrics对象:

# Access metrics object in context as follows
def initialize(self, context):
    metrics = context.metrics

注意: 自定义指标API不应与指标API端点混淆,后者是用于以Prometheus格式获取指标的HTTP API。

默认尺寸

如果未指定,度量将具有几个默认维度:

  • ModelName: {name_of_model}

  • Level: Model

创建维度对象(s)

维度 可以定义为对象的指标

from ts.metrics.dimension import Dimension

# Dimensions are name value pairs
dim1 = Dimension(name, value)
dim2 = Dimension(some_name, some_value)
.
.
.
dimN= Dimension(name_n, value_n)

添加通用指标

通用指标默认为COUNTER种指标类型

函数API以添加通用指标,无需默认维度

    def add_metric_to_cache(
        self,
        metric_name: str,
        unit: str,
        dimension_names: list = [],
        metric_type: MetricTypes = MetricTypes.COUNTER,
    ) -> CachingMetric:
        """
        Create a new metric and add into cache. Override existing metric if already present.

        Parameters
        ----------
        metric_name str
            Name of metric
        unit str
            unit can be one of ms, percent, count, MB, GB or a generic string
        dimension_names list
            list of dimension name strings for the metric
        metric_type MetricTypes
            Type of metric Counter, Gauge, Histogram
        Returns
        -------
        newly created Metrics object
        """

缓存指标 API 用于更新指标

    def add_or_update(
        self,
        value: int or float,
        dimension_values: list = [],
        request_id: str = "",
):
    """
    Update metric value, request id and dimensions

    Parameters
    ----------
    value : int, float
        metric to be updated
    dimension_values : list
        list of dimension value strings
    request_id : str
        request id to be associated with the metric
    """
    def update(
        self,
        value: int or float,
        request_id: str = "",
        dimensions: list = [],
):
    """
    BACKWARDS COMPATIBILITY: Update metric value

    Parameters
    ----------
    value : int, float
        metric to be updated
    request_id : str
        request id to be associated with the metric
    dimensions : list
        list of Dimension objects
    """
# Example usage
metrics = context.metrics
# Add metric
distance_metric = metrics.add_metric_to_cache(name='DistanceInKM', unit='km', dimension_names=[...])
# Update metric
distance_metric.add_or_update(value=distance, dimension_values=[...], request_id=context.get_request_id())
# OR
distance_metric.update(value=distance, request_id=context.get_request_id(), dimensions=[...])

Note: 调用 add_metric_to_cache 将不会触发指标,add_or_update 需要在如上所示的指标对象上调用。

函数API以添加通用指标与默认维度

    def add_metric(
        self,
        name: str,
        value: int or float,
        unit: str,
        idx: str = None,
        dimensions: list = [],
        metric_type: MetricTypes = MetricTypes.COUNTER,
    ):
        """
        Add a generic metric
            Default metric type is counter

        Parameters
        ----------
        name : str
            metric name
        value: int or float
            value of the metric
        unit: str
            unit of metric
        idx: str
            request id to be associated with the metric
        dimensions: list
            list of Dimension objects for the metric
        metric_type MetricTypes
            Type of metric Counter, Gauge, Histogram
        """
# Example usage
metrics = context.metrics
metric = metrics.add_metric(name='DistanceInKM', value=10, unit='km', dimensions=[...])

添加基于时间的指标

时间基度量默认为GAUGE种度量类型

    def add_time(self, name: str, value: int or float, idx=None, unit: str = 'ms', dimensions: list = None,
                 metric_type: MetricTypes = MetricTypes.GAUGE):
        """
        Add a time based metric like latency, default unit is 'ms'
            Default metric type is gauge

        Parameters
        ----------
        name : str
            metric name
        value: int
            value of metric
        idx: int
            request_id index in batch
        unit: str
            unit of metric,  default here is ms, s is also accepted
        dimensions: list
            list of Dimension objects for the metric
        metric_type: MetricTypes
           type for defining different operations, defaulted to gauge metric type for Time metrics
        """

Note: 默认单位是 ms

支持单位: ['ms', 's']

# Example usage
metrics = context.metrics
metrics.add_time(name='InferenceTime', value=end_time-start_time, idx=None, unit='ms', dimensions=[...])

添加基于大小的指标

基于大小的指标默认为GAUGE种指标类型

    def add_size(self, name: str, value: int or float, idx=None, unit: str = 'MB', dimensions: list = None,
                 metric_type: MetricTypes = MetricTypes.GAUGE):
        """
        Add a size based metric
            Default metric type is gauge

        Parameters
        ----------
        name : str
            metric name
        value: int, float
            value of metric
        idx: int
            request_id index in batch
        unit: str
            unit of metric, default here is 'MB', 'kB', 'GB' also supported
        dimensions: list
            list of Dimension objects for the metric
        metric_type: MetricTypes
           type for defining different operations, defaulted to gauge metric type for Size metrics
        """

Note: 默认单位是 MB

支持单位: ['MB', 'kB', 'GB', 'B']

# Example usage
metrics = context.metrics
metrics.add_size(name='SizeOfImage', value=img_size, idx=None, unit='MB', dimensions=[...])

添加基于百分比的指标

百分比基的指标默认为一种 GAUGE 类型的指标

    def add_percent(self, name: str, value: int or float, idx=None, dimensions: list = None,
                    metric_type: MetricTypes = MetricTypes.GAUGE):
        """
        Add a percentage based metric
            Default metric type is gauge

        Parameters
        ----------
        name : str
            metric name
        value: int, float
            value of metric
        idx: int
            request_id index in batch
        dimensions: list
            list of Dimension objects for the metric
        metric_type: MetricTypes
           type for defining different operations, defaulted to gauge metric type for Percent metrics
        """

推断单位: percent

# Example usage
metrics = context.metrics
metrics.add_percent(name='MemoryUtilization', value=utilization_percent, idx=None, dimensions=[...])

添加基于计数器的指标

基于计数的指标默认为COUNTER种指标类型

    def add_counter(self, name: str, value: int or float, idx=None, dimensions: list = None):
        """
        Add a counter metric or increment an existing counter metric
            Default metric type is counter
        Parameters
        ----------
        name : str
            metric name
        value: int or float
            value of metric
        idx: int
            request_id index in batch
        dimensions: list
            list of Dimension objects for the metric
        """
# Example usage
metrics = context.metrics
metrics.add_counter(name='CallCount', value=call_count, idx=None, dimensions=[...])

推断单位: count

获取一个指标

用户可以从缓存中获取指标。返回的是 CachingMetric 对象, 因此用户可以访问 CachingMetric 的方法来更新指标:(例如 CachingMetric.add_or_update(value, dimension_values), CachingMetric.update(value, dimensions)

    def get_metric(
        self,
        metric_name: str,
        metric_type: MetricTypes = MetricTypes.COUNTER,
) -> CachingMetric:
    """
    Create a new metric and add into cache

    Parameters
    ----------
    metric_name str
        Name of metric

    metric_type MetricTypes
        Type of metric Counter, Gauge, Histogram

    Returns
    -------
    Metrics object or MetricsCacheKeyError if not found
    """
# Example usage
metrics = context.metrics
# Get metric
gauge_metric = metrics.get_metric(metric_name = "GaugeMetricName", metric_type = MetricTypes.GAUGE)
# Update metric
gauge_metric.add_or_update(value=gauge_metric_value, dimension_values=[...], request_id=context.get_request_id())
# OR
gauge_metric.update(value=gauge_metric_value, request_id=context.get_request_id(), dimensions=[...])

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源