捷徑

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 模式下,指標會以 prometheus 格式透過 metrics API 端點 提供。

舊版模式

legacy 模式啟用與 Torchserve 版本 <= 0.7.1 的回溯相容性,其中

  • ts_inference_requests_totalts_inference_latency_microsecondsts_queue_latency_microseconds 僅可透過 metrics 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. 使用 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 /<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 設定,以記錄檔或透過 metrics API 端點 提供對應的指標。

不支援對指標設定檔進行動態更新。 為了說明對指標設定檔所做的更新,需要重新啟動 Torchserve。

模型指標自動偵測

預設情況下,未在指標設定檔中定義的指標將不會記錄在指標記錄檔中,也不會透過 metrics API 端點 提供。 透過在 config.properties 中將 model_metrics_auto_detect 設定為 true 或使用 TS_MODEL_METRICS_AUTO_DETECT 環境變數,可以 auto-detected 後端模型指標。 預設情況下,模型指標自動偵測已停用。

警告: 使用 後端 指標的 自動偵測 效能產生 影響, 延遲 額外負荷, 通常在 模型 載入時 以及 給定模型的 首次 推論時。 這種 冷啟動 行為 的原因是, 通常在 模型 載入時 以及 首次 推論時, 後端會 發出 新的 指標, 並且 前端會 偵測並 註冊 這些指標。 如果 首次 更新了 新的 指標, 後續的 推論也可能 會受到 效能 影響。 對於 經常 載入/卸載 多個 模型 的使用案例, 可以 透過 提前 指標 設定檔中 指定 已知的 指標來 減輕 延遲 額外負荷。

指標設定格式

指標設定 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]

注意: 當在 metrics 組態檔中新增自訂 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 (計數器) Count (計數) Level (層級), Hostname (主機名稱) 回應狀態碼在 200-300 範圍內的請求總數
Requests4XX counter (計數器) Count (計數) Level (層級), Hostname (主機名稱) 回應狀態碼在 400-500 範圍內的請求總數
Requests5XX counter (計數器) Count (計數) Level (層級), Hostname (主機名稱) 回應狀態碼高於 500 的請求總數
ts_inference_requests_total counter (計數器) Count (計數) model_name (模型名稱), model_version (模型版本), hostname (主機名稱) 收到的推論請求總數
ts_inference_latency_microseconds counter (計數器) Microseconds (微秒) model_name (模型名稱), model_version (模型版本), hostname (主機名稱) 推論總延遲時間 (微秒)
ts_queue_latency_microseconds counter (計數器) Microseconds (微秒) model_name (模型名稱), model_version (模型版本), hostname (主機名稱) 佇列總延遲時間 (微秒)
QueueTime (佇列時間) gauge (量規) Milliseconds (毫秒) Level (層級), Hostname (主機名稱) 作業在請求佇列中花費的時間 (毫秒)
WorkerThreadTime (工作執行緒時間) gauge (量規) Milliseconds (毫秒) Level (層級), Hostname (主機名稱) 工作執行緒中花費的時間 (不包括後端回應時間,以毫秒為單位)
WorkerLoadTime (工作載入時間) gauge (量規) Milliseconds (毫秒) WorkerName (工作名稱), Level (層級), Hostname (主機名稱) 工作載入模型所花費的時間 (毫秒)
CPUUtilization (CPU 使用率) gauge (量規) Percent (百分比) Level (層級), Hostname (主機名稱) 主機上的 CPU 使用率
MemoryUsed (已用記憶體) gauge (量規) Megabytes (百萬位元組) Level (層級), Hostname (主機名稱) 主機上已使用的記憶體
MemoryAvailable (可用記憶體) gauge (量規) Megabytes (百萬位元組) Level (層級), Hostname (主機名稱) 主機上可用的記憶體
MemoryUtilization (記憶體使用率) gauge (量規) Percent (百分比) Level (層級), Hostname (主機名稱) 主機上的記憶體使用率
DiskUsage (磁碟使用量) gauge (量規) Gigabytes (十億位元組) Level (層級), Hostname (主機名稱) 主機上已使用的磁碟空間
DiskUtilization (磁碟使用率) gauge (量規) Percent (百分比) Level (層級), Hostname (主機名稱) 主機上已使用的磁碟空間
DiskAvailable (可用磁碟空間) gauge (量規) Gigabytes (十億位元組) Level (層級), Hostname (主機名稱) 主機上可用的磁碟空間
GPUMemoryUtilization (GPU 記憶體使用率) gauge (量規) Percent (百分比) Level (層級), DeviceId (設備 ID), Hostname (主機名稱) 主機、設備 ID 上的 GPU 記憶體使用率
GPUMemoryUsed (已用 GPU 記憶體) gauge (量規) Megabytes (百萬位元組) Level (層級), DeviceId (設備 ID), Hostname (主機名稱) 主機、設備 ID 上已使用的 GPU 記憶體
GPUUtilization (GPU 使用率) gauge (量規) Percent (百分比) Level (層級), DeviceId (設備 ID), Hostname (主機名稱) 主機、設備 ID 上的 GPU 使用率

預設後端指標

指標名稱 類型 單位 維度 語意
HandlerTime (處理器時間) gauge (量規) ms (毫秒) ModelName (模型名稱), Level (層級), Hostname (主機名稱) 後端處理器中花費的時間
PredictionTime (預測時間) gauge (量規) ms (毫秒) ModelName (模型名稱), Level (層級), Hostname (主機名稱) 後端預測時間

自訂指標 API

TorchServe 允許 handler 發出自訂指標,然後根據組態的 metrics_mode 提供這些指標。

帶有自訂 handler 的範例,顯示 自訂指標 API 的用法.

自訂 handler 程式碼提供了一個目前請求的 context,其中包含一個 metrics 物件。

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

注意: 自訂指標 API 不應與 指標 API 端點 混淆,後者是一個 HTTP API,用於以 prometheus 格式擷取指標。

預設維度

如果尚未指定,指標將具有幾個預設維度

  • 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 的完整開發者文件

檢視文件

教學

取得針對初學者和進階開發者的深入教學課程

檢視教學

資源

尋找開發資源並獲得您的問題解答

檢視資源