快捷方式

⚠️ 注意:有限維護

本專案不再積極維護。現有版本仍然可用,但沒有計劃的更新、錯誤修復、新功能或安全補丁。使用者應注意,漏洞可能得不到解決。

TorchServe 指標

目錄

介紹

TorchServe 指標大致可分為前端指標和後端指標。

前端指標:

  • API 請求狀態指標

  • 推理請求指標

  • 系統利用率指標

注意: 系統利用率指標會定期收集(預設:每分鐘一次)

後端指標:

  • 預設模型指標

  • 自定義模型指標

注意: TorchServe 提供了一個 API 來收集自定義模型指標。

預設前端和後端指標顯示在預設指標部分。

指標模式

支援三種指標模式,即 logprometheuslegacy,預設模式為 log。可以透過 config.properties 中的 metrics_mode 配置選項或 TS_METRICS_MODE 環境變數來配置指標模式。有關 config.properties 和基於環境變數的配置的更多詳細資訊,請參閱TorchServe 配置文件。

日誌模式

log 模式下,指標會被記錄到日誌中,並可由指標代理進行聚合。在 log 模式下,指標預設在以下位置收集:

  • 前端指標 - log_directory/ts_metrics.log

  • 後端指標 - log_directory/model_metrics.log

日誌檔案和指標檔案的位置可以在 log4j2.xml 檔案中配置。

Prometheus 模式

prometheus 模式下,指標透過指標 API 端點以 Prometheus 格式提供。

舊版模式

legacy 模式提供與 TorchServe <= 0.7.1 版本的向後相容性,在這種模式下:

  • ts_inference_requests_totalts_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. 在正在使用的 config.properties 中,將 metrics_config 引數設定為 yaml 檔案路徑

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

    如果未指定 metrics_config 引數,將使用預設的 metrics.yaml 配置檔案。

  3. 使用 config.properties 中的 metrics_mode 配置選項或 TS_METRICS_MODE 環境變數設定您想要的指標模式。如果未設定,預設將使用 log 模式。

  4. 處理程式 (handler) 中,如果有任何自定義指標,請使用自定義指標 API 來發出。

  5. 執行 TorchServe 並在 ts-config 標誌後指定 config.properties 檔案的路徑

    torchserve --ncs --start --model-store model_store --models my_model=model.mar --ts-config /<路徑>/<到>/<配置>/<檔案>/config.properties

  6. 根據選擇的模式收集指標

    如果是 log 模式,請檢查

    • 前端指標 - log_directory/ts_metrics.log

    • 後端指標 - log_directory/model_metrics.log

    否則,如果使用 prometheus 模式,請使用指標 API 端點

指標配置

TorchServe 在 yaml 檔案中定義指標配置,包括前端指標(即 ts_metrics)和後端指標(即 model_metrics)。當 TorchServe 啟動時,會載入指標定義,並根據 metrics_mode 配置,將相應的指標以日誌或透過指標 API 端點提供。

不支援對指標配置檔案的動態更新。為了使對指標配置檔案的更新生效,需要重新啟動 TorchServe。

模型指標自動檢測

預設情況下,未在指標配置檔案中定義的指標不會被記錄到指標日誌檔案中,也不會透過指標 API 端點提供。可以透過在 config.properties 中將 model_metrics_auto_detect 設定為 true 或使用 TS_MODEL_METRICS_AUTO_DETECT 環境變數來自動檢測後端模型指標。預設情況下,模型指標自動檢測是停用的。

警告: 使用後端指標自動檢測會對效能產生影響,表現為延遲開銷,通常在模型載入和給定模型的首次推理時出現。這種冷啟動行為是由於新指標通常在模型載入和首次推理期間由後端發出,並由前端檢測和註冊。如果新指標首次更新,後續推理也可能會受到效能影響。對於經常載入/解除安裝多個模型的使用案例,可以透過提前在指標配置檔案中指定已知指標來減輕延遲開銷。

指標配置格式

指標配置 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]

注意: 在指標配置檔案中新增自定義 model_metrics 時,請確保將 ModelNameLevel 維度名稱包含在維度列表的末尾,因為以下自定義指標 API 預設會包含它們:add_metricadd_counteradd_timeadd_sizeadd_percent

預設指標配置

預設指標在預設指標配置檔案 metrics.yaml 中提供。

指標型別

TorchServe 指標使用與Prometheus 指標型別一致的指標型別

指標型別是 Metric 物件的屬性。使用者在新增自定義指標時將受限於現有的指標型別。

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

預設指標

預設前端指標

指標名稱 型別 單位 維度 語義
Requests2XX counter 計數 Level, Hostname 響應狀態碼在 200-300 範圍內的總請求數
Requests4XX counter 計數 Level, Hostname 響應狀態碼在 400-500 範圍內的總請求數
Requests5XX counter 計數 Level, Hostname 響應狀態碼高於 500 的總請求數
ts_inference_requests_total counter 計數 model_name, model_version, hostname 收到的推理請求總數
ts_inference_latency_microseconds counter 微秒 model_name, model_version, hostname 總推理延遲(微秒)
ts_queue_latency_microseconds counter 微秒 model_name, model_version, hostname 總佇列延遲(微秒)
QueueTime gauge 毫秒 Level, Hostname 作業在請求佇列中花費的時間(毫秒)
WorkerThreadTime gauge 毫秒 Level, Hostname worker 執行緒中花費的時間,不包括後端響應時間(毫秒)
WorkerLoadTime gauge 毫秒 WorkerName, Level, Hostname worker 載入模型所需的時間(毫秒)
CPUUtilization gauge 百分比 Level, Hostname 主機上的 CPU 利用率
MemoryUsed gauge 兆位元組 Level, Hostname 主機上已使用的記憶體
MemoryAvailable gauge 兆位元組 Level, Hostname 主機上可用記憶體
MemoryUtilization gauge 百分比 Level, Hostname 主機上的記憶體利用率
DiskUsage gauge 千兆位元組 Level, Hostname 主機上已使用的磁碟空間
DiskUtilization gauge 百分比 Level, Hostname 主機上已使用的磁碟空間
DiskAvailable gauge 千兆位元組 Level, Hostname 主機上可用磁碟空間
GPUMemoryUtilization gauge 百分比 Level, DeviceId, Hostname 主機上的 GPU 記憶體利用率,DeviceId
GPUMemoryUsed gauge 兆位元組 Level, DeviceId, Hostname 主機上已使用的 GPU 記憶體,DeviceId
GPUUtilization gauge 百分比 Level, DeviceId, Hostname 主機上的 GPU 利用率,DeviceId

預設後端指標

指標名稱 型別 單位 維度 語義
HandlerTime gauge ms ModelName, Level, Hostname 後端處理程式中花費的時間
PredictionTime gauge ms ModelName, Level, Hostname 後端預測時間

自定義指標 API

TorchServe 支援處理程式 (handler) 發出自定義指標,然後根據配置的 metrics_mode 使其可用。

帶有自定義處理程式的示例,展示了自定義指標 API 的使用.

自定義處理程式 (handler) 程式碼提供了一個包含 metrics 物件的當前請求的上下文

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

注意: 自定義指標 API 不應與用於以 Prometheus 格式獲取指標的 HTTP API 的指標 API 端點混淆。

預設維度

如果未指定,指標將包含幾個預設維度

  • 模型名稱 (ModelName): {name_of_model}

  • 級別 (Level): 模型 (Model)

建立維度物件

指標的維度可以定義為物件。

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
        """

用於更新指標的 CachingMetric 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=[...])

注意: 呼叫 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
        """

注意: 預設單位是 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
        """

注意: 預設單位是 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 的全面開發者文件

檢視文件

教程

獲取針對初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並獲得解答

檢視資源