跳到内容

llmcompressor.metrics

用于压缩工作流的指标日志记录和监控框架。

提供全面的指标收集、日志记录和监控能力,用于模型压缩操作。包括基础日志记录器、频率管理以及针对压缩过程中训练和推理性能的专门指标跟踪。

模块

  • logger

    包含日志记录器的代码,这些日志记录器有助于可视化每个

  • utils

  • BaseLogger

    所有修饰符日志记录器都必须实现的基类。

  • LambdaLogger

    处理调用 lambda 函数并传递任何日志的日志记录器。

  • LoggerManager

    日志记录器的包装器,负责日志调度并将日志传递给目标

  • PythonLogger

    修饰符指标,负责将值打印到 python 指标实例。

  • SparsificationGroupLogger

    修饰符指标,负责将值输出到其他支持的系统。

  • TensorBoardLogger

    修饰符指标,负责将值输出到 TensorBoard 日志目录

  • WANDBLogger

    修饰符指标,负责将值输出到 Weights and Biases。

BaseLogger

BaseLogger(name: str, enabled: bool = True)

基类:ABC

所有修饰符日志记录器都必须实现的基类。

参数

  • 名称

    (str) –

    用于标识指标的名称

  • enabled

    (bool, 默认值: True ) –

    为 True 时记录,为 False 时不记录

方法

  • log_hyperparams

    :param params: 字典中的每个键值对都是超参数的名称

  • log_scalar

    :param tag: 用于标识值的标签

  • log_scalars

    :param tag: 用于标识值的标签

  • log_string

    :param tag: 用于标识值的标签

  • save

    :param file_path: 要保存的文件路径

属性

  • enabled (bool) –

    :return: 为 True 时记录,为 False 时不记录

  • name (str) –

    :return: 用于标识指标的名称

源代码在 llmcompressor/metrics/logger.py
def __init__(self, name: str, enabled: bool = True):
    self._name = name
    self._enabled = enabled

enabled property writable

enabled: bool

返回

  • bool

    为 True 时记录,为 False 时不记录

name property

name: str

返回

  • str

    用于标识指标的名称

log_hyperparams

log_hyperparams(params: dict[str, float]) -> bool

参数

  • params

    (dict[str, float]) –

    字典中的每个键值对都是超参数的名称及其对应的值。

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_hyperparams(self, params: dict[str, float]) -> bool:
    """
    :param params: Each key-value pair in the dictionary is the name of the
        hyper parameter and it's corresponding value.
    :return: True if logged, False otherwise.
    """
    return False

log_scalar

log_scalar(
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    **kwargs,
) -> bool

参数

  • tag

    (str) –

    用于标识值的标签

  • (float) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录该值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录该值时的全局墙壁时间

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_scalar(
    self,
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    **kwargs,
) -> bool:
    """
    :param tag: identifying tag to log the value with
    :param value: value to save
    :param step: global step for when the value was taken
    :param wall_time: global wall time for when the value was taken
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """
    return False

log_scalars

log_scalars(
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    **kwargs,
) -> bool

参数

  • tag

    (str) –

    用于标识值的标签

  • (dict[str, float]) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录这些值时的全局墙壁时间

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_scalars(
    self,
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    **kwargs,
) -> bool:
    """
    :param tag: identifying tag to log the values with
    :param values: values to save
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """
    return False

log_string

log_string(
    tag: str,
    string: str,
    step: int | None = None,
    wall_time: float | None = None,
    **kwargs,
) -> bool

参数

  • tag

    (str) –

    用于标识值的标签

  • 要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录这些值时的全局墙壁时间

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_string(
    self,
    tag: str,
    string: str,
    step: int | None = None,
    wall_time: float | None = None,
    **kwargs,
) -> bool:
    """
    :param tag: identifying tag to log the values with
    :param values: values to save
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """
    return False

save

save(file_path: str, **kwargs) -> bool

参数

  • 文件路径

    (str) –

    要保存的文件路径

  • kwargs

    特定指标可能使用的其他参数

返回

  • bool

    如果已保存,则为 True,否则为 False

源代码在 llmcompressor/metrics/logger.py
def save(
    self,
    file_path: str,
    **kwargs,
) -> bool:
    """
    :param file_path: path to a file to be saved
    :param kwargs: additional arguments that a specific metrics might use
    :return: True if saved, False otherwise
    """
    return False

LambdaLogger

LambdaLogger(
    lambda_func: Callable[
        [
            str | None,
            float | str | None,
            dict[str, float] | None,
            int | None,
            float | None,
            int | None,
        ],
        bool,
    ],
    name: str = "lambda",
    enabled: bool = True,
)

Bases: BaseLogger

处理调用 lambda 函数并传递任何日志的日志记录器。

参数

  • lambda_func

    (Callable[[str | None, float | str | None, dict[str, float] | None, int | None, float | None, int | None], bool]) –

    回调的 lambda 函数,用于传递任何日志。预期的调用序列是 (tag, value, values, step, wall_time) -> bool 返回 True 表示已记录,否则返回 False。

  • 名称

    (str, default: 'lambda' ) –

    用于标识指标的名称;默认为 lambda

  • enabled

    (bool, 默认值: True ) –

    为 True 时记录,为 False 时不记录

方法

  • log_hyperparams

    :param params: 字典中的每个键值对都是超参数的名称

  • log_scalar

    :param tag: 用于标识值的标签

  • log_scalars

    :param tag: 用于标识值的标签

属性

  • lambda_func (Callable[[str | None, float | str | None, dict[str, float] | None, int | None, float | None, int | None], bool]) –

    :return: 回调的 lambda 函数,用于传递任何日志。

源代码在 llmcompressor/metrics/logger.py
def __init__(
    self,
    lambda_func: Callable[
        [
            str | None,
            float | str | None,
            dict[str, float] | None,
            int | None,
            float | None,
            int | None,
        ],
        bool,
    ],
    name: str = "lambda",
    enabled: bool = True,
):
    super().__init__(name, enabled)
    self._lambda_func = lambda_func
    assert lambda_func, "lambda_func must be set to a callable function"

lambda_func property

lambda_func: Callable[
    [
        str | None,
        float | str | None,
        dict[str, float] | None,
        int | None,
        float | None,
        int | None,
    ],
    bool,
]

返回

  • Callable[[str | None, float | str | None, dict[str, float] | None, int | None, float | None, int | None], bool]

    回调的 lambda 函数,用于传递任何日志。预期的调用序列是 (tag, value, values, step, wall_time)

log_hyperparams

log_hyperparams(
    params: dict[str, float], level: int | str | None = None
) -> bool

参数

  • params

    (dict[str, float]) –

    字典中的每个键值对都是超参数的名称及其对应的值。

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_hyperparams(
    self,
    params: dict[str, float],
    level: int | str | None = None,
) -> bool:
    """
    :param params: Each key-value pair in the dictionary is the name of the
        hyper parameter and it's corresponding value.
    :param level: minimum severity level for the log message
    :return: True if logged, False otherwise.
    """
    if not self.enabled:
        return False

    return self._lambda_func(
        tag=None,
        value=None,
        values=params,
        step=None,
        wall_time=None,
        level=level,
    )

log_scalar

log_scalar(
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
) -> bool

参数

  • tag

    (str) –

    用于标识值的标签

  • (float) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录该值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录值时的全局墙壁时间,默认为 time.time()

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_scalar(
    self,
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
) -> bool:
    """
    :param tag: identifying tag to log the value with
    :param value: value to save
    :param step: global step for when the value was taken
    :param wall_time: global wall time for when the value was taken,
        defaults to time.time()
    :param level: minimum severity level for the log message
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """
    if not wall_time:
        wall_time = time.time()

    return self._lambda_func(
        tag=tag,
        value=value,
        values=None,
        step=step,
        wall_time=wall_time,
        level=level,
    )

log_scalars

log_scalars(
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
) -> bool

参数

  • tag

    (str) –

    用于标识值的标签

  • (dict[str, float]) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录值时的全局墙壁时间,默认为 time.time()

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_scalars(
    self,
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
) -> bool:
    """
    :param tag: identifying tag to log the values with
    :param values: values to save
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken,
        defaults to time.time()
    :param level: minimum severity level for the log message
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """
    if not wall_time:
        wall_time = time.time()

    return self._lambda_func(
        tag=tag,
        value=None,
        values=values,
        step=step,
        wall_time=wall_time,
        level=level,
    )

LoggerManager

LoggerManager(
    loggers: list[BaseLogger] | None = None,
    log_frequency: float | None = 0.1,
    log_python: bool = True,
    name: str = "manager",
    mode: LoggingModeType = "exact",
    frequency_type: FrequencyType = "epoch",
)

基类:ABC

日志记录器的包装器,负责日志调度并将日志传递给目标日志记录器。

参数

  • loggers

    (list[BaseLogger] | None, default: None ) –

    分配给此管理器的日志记录器列表

  • 日志频率

    (float | None, default: 0.1 ) –

    日志之间等待的步数或步数比例

  • 模式

    (LoggingModeType, default: 'exact' ) –

    使用的日志模式,可以是“on_change”或“exact”。“on_change”将在模型自上次日志以来发生更新时记录,“exact”将根据给定频率记录,而不管模型更新。默认为“exact”

  • 频率类型

    (FrequencyType, default: 'epoch' ) –

    要使用的频率类型,可以是 "epoch"、"step" 或 "batch" 来控制频率管理器跟踪的内容,例如,如果频率类型是 "epoch",则频率管理器将跟踪自上次日志记录以来已过的 epoch 数,如果频率类型是 "step",则频率管理器将跟踪优化器步骤数

方法

  • add_logger

    将 BaseLogger 实现添加到此管理器的日志记录器中

  • log_hyperparams

    (注意:此方法已弃用,将在未来版本中删除;

  • log_ready

    检查是否有指标已准备好接受日志

  • log_scalar

    (注意:此方法已弃用,将在未来版本中删除;

  • log_scalars

    (注意:此方法已弃用,将在未来版本中删除;

  • log_string

    (注意:此方法已弃用,将在未来版本中删除;

  • log_written

    使用上次写入的日志步数更新频率管理器

  • model_updated

    使用上次模型更新步数更新频率管理器

  • save

    :param file_path: 要保存的文件路径

  • time

    上下文管理器,用于记录代码块运行所需的时间

属性

  • log_frequency (str | float | None) –

    :return: 日志之间等待的 epoch 数或 epoch 分数

  • loggers (list[BaseLogger]) –

    :return: 分配给此管理器的日志记录器列表

  • name (str) –

    :return: 用于标识指标的名称

  • wandb (ModuleType | None) –

    :return: 如果已初始化,则返回 wandb 模块

源代码在 llmcompressor/metrics/logger.py
def __init__(
    self,
    loggers: list[BaseLogger] | None = None,
    log_frequency: float | None = 0.1,
    log_python: bool = True,
    name: str = "manager",
    mode: LoggingModeType = "exact",
    frequency_type: FrequencyType = "epoch",
):
    self._name = name
    self._loggers = (
        loggers
        or SparsificationGroupLogger(
            python=log_python,
            name=name,
            tensorboard=False,
            wandb_=False,
        ).loggers
    )

    self.frequency_manager = FrequencyManager(
        mode=mode,
        frequency_type=frequency_type,
        log_frequency=log_frequency,
    )

    self.system = SystemLoggingWrapper(
        loggers=self._loggers, frequency_manager=self.frequency_manager
    )
    self.metric = MetricLoggingWrapper(
        loggers=self._loggers, frequency_manager=self.frequency_manager
    )

log_frequency property writable

log_frequency: str | float | None

返回

  • str | float | None

    日志之间等待的 epoch 数或 epoch 分数

loggers property writable

loggers: list[BaseLogger]

返回

  • list[BaseLogger]

    分配给此管理器的日志记录器列表

name property

name: str

返回

  • str

    用于标识指标的名称

wandb property

wandb: ModuleType | None

返回

  • ModuleType | None

    如果已初始化,则返回 wandb 模块

add_logger

add_logger(logger: BaseLogger)

将 BaseLogger 实现添加到此管理器的日志记录器中

参数

  • logger

    (BaseLogger) –

    要添加的指标对象

源代码在 llmcompressor/metrics/logger.py
def add_logger(self, logger: BaseLogger):
    """
    add a BaseLogger implementation to the loggers of this manager

    :param logger: metrics object to add
    """
    if not isinstance(logger, BaseLogger):
        raise ValueError(f"metrics {type(logger)} must be of type BaseLogger")
    self._loggers.append(logger)

log_hyperparams

log_hyperparams(
    params: dict,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
)

(注意:此方法已弃用,将在未来版本中删除,请使用 LoggerManager().metric.log_hyperparams 代替)

参数

  • params

    (dict) –

    字典中的每个键值对都是超参数的名称及其对应的值。

源代码在 llmcompressor/metrics/logger.py
def log_hyperparams(
    self,
    params: dict,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
):
    """
    (Note: this method is deprecated and will be removed in a future version,
    use LoggerManager().metric.log_hyperparams instead)

    :param params: Each key-value pair in the dictionary is the name of the
        hyper parameter and it's corresponding value.
    """

    self.metric.log_hyperparams(
        params=params,
        log_types=log_types,
        level=level,
    )

log_ready

log_ready(
    current_log_step,
    last_log_step=None,
    check_model_update: bool = False,
)

检查是否有指标已准备好接受日志

参数

  • 当前日志步骤

    请求日志的当前步数

  • 上次日志步骤

    上次记录此对象日志的时间。(已弃用)

  • 检查模型更新

    (bool, 默认值: False ) –

    如果为 True,将检查模型是否已更新,如果为 False,则仅检查日志频率

返回

  • 如果指标已准备好接受日志,则为 True。

源代码在 llmcompressor/metrics/logger.py
def log_ready(
    self, current_log_step, last_log_step=None, check_model_update: bool = False
):
    """
    Check if there is a metrics that is ready to accept a log

    :param current_log_step: current step log is requested at
    :param last_log_step: last time a log was recorder for this object. (Deprecated)
    :param check_model_update: if True, will check if the model has been updated,
        if False, will only check the log frequency
    :return: True if a metrics is ready to accept a log.
    """
    log_enabled = any(logger.enabled for logger in self.loggers)
    if last_log_step is not None:
        self.frequency_manager.log_written(step=last_log_step)

    return log_enabled and self.frequency_manager.log_ready(
        current_log_step=current_log_step,
        check_model_update=check_model_update,
    )

log_scalar

log_scalar(
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
)

(注意:此方法已弃用,将在未来版本中删除,请使用 LoggerManager().metric.log_scalar 代替)

参数

  • tag

    (str) –

    用于标识值的标签

  • (float) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录该值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录该值时的全局墙壁时间

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • 如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_scalar(
    self,
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
):
    """
    (Note: this method is deprecated and will be removed in a future version,
    use LoggerManager().metric.log_scalar instead)

    :param tag: identifying tag to log the value with
    :param value: value to save
    :param step: global step for when the value was taken
    :param wall_time: global wall time for when the value was taken
    :param level: minimum severity level for the log message
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """

    self.metric.log_scalar(
        tag=tag,
        value=value,
        step=step,
        wall_time=wall_time,
        log_types=log_types,
        level=level,
    )

log_scalars

log_scalars(
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
)

(注意:此方法已弃用,将在未来版本中删除,请使用 LoggerManager().metric.log_scalars 代替)

参数

  • tag

    (str) –

    用于标识值的标签

  • (dict[str, float]) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录这些值时的全局墙壁时间

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

返回

  • 如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_scalars(
    self,
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
):
    """
    (Note: this method is deprecated and will be removed in a future version,
    use LoggerManager().metric.log_scalars instead)

    :param tag: identifying tag to log the values with
    :param values: values to save
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken
    :param level: minimum severity level for the log message
    :param kwargs: additional logging arguments to support Python and custom loggers
    :return: True if logged, False otherwise.
    """

    self.metric.log_scalars(
        tag=tag,
        values=values,
        step=step,
        wall_time=wall_time,
        log_types=log_types,
        level=level,
    )

log_string

log_string(
    tag: str,
    string: str,
    step: int | None = None,
    wall_time: float | None = None,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
)

(注意:此方法已弃用,将在未来版本中删除,请使用 LoggerManager().system.log_string 代替)

参数

  • tag

    (str) –

    用于标识值的标签

  • 要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录这些值时的全局墙壁时间

  • kwargs

    其他日志参数,以支持 Python 和自定义日志记录器

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

返回

  • 如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_string(
    self,
    tag: str,
    string: str,
    step: int | None = None,
    wall_time: float | None = None,
    log_types: str | list[str] = ALL_TOKEN,
    level: int | str | None = None,
):
    """
    (Note: this method is deprecated and will be removed in a future version,
    use LoggerManager().system.log_string instead)

    :param tag: identifying tag to log the values with
    :param values: values to save
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken
    :param kwargs: additional logging arguments to support Python and custom loggers
    :param level: minimum severity level for the log message
    :return: True if logged, False otherwise.
    """
    self.system.log_string(
        tag=tag,
        string=string,
        step=step,
        wall_time=wall_time,
        log_types=log_types,
        level=level,
    )

log_written

log_written(step: LogStepType)

使用上次写入的日志步数更新频率管理器

参数

  • 步骤

    (LogStepType) –

    上次记录的步数

源代码在 llmcompressor/metrics/logger.py
def log_written(self, step: LogStepType):
    """
    Update the frequency manager with the last log step written

    :param step: step that was last logged
    """
    self.frequency_manager.log_written(step=step)

model_updated

model_updated(step: LogStepType)

使用上次模型更新步数更新频率管理器

参数

  • 步骤

    (LogStepType) –

    上次记录的步数

源代码在 llmcompressor/metrics/logger.py
def model_updated(self, step: LogStepType):
    """
    Update the frequency manager with the last model update step

    :param step: step that was last logged
    """
    self.frequency_manager.model_updated(step=step)

save

save(file_path: str, **kwargs)

参数

  • 文件路径

    (str) –

    要保存的文件路径

  • kwargs

    特定指标可能使用的其他参数

源代码在 llmcompressor/metrics/logger.py
def save(
    self,
    file_path: str,
    **kwargs,
):
    """
    :param file_path: path to a file to be saved
    :param kwargs: additional arguments that a specific metrics might use
    """
    for log in self._loggers:
        if log.enabled:
            log.save(file_path, **kwargs)

time

time(tag: str | None = None, *args, **kwargs)

上下文管理器,用于记录代码块运行所需的时间

用法

with LoggerManager().time("my_block"): time.sleep(1)

参数

  • tag

    (str | None, 默认值: None ) –

    用于标识值的标签

源代码在 llmcompressor/metrics/logger.py
@contextmanager
def time(self, tag: str | None = None, *args, **kwargs):
    """
    Context manager to log the time it takes to run the block of code

    Usage:
    >>> with LoggerManager().time("my_block"):
    >>>    time.sleep(1)

    :param tag: identifying tag to log the values with
    """

    start = time.time()
    yield
    elapsed = time.time() - start
    if not tag:
        tag = f"{DEFAULT_TAG}_time_secs"
    self.log_scalar(tag=tag, value=float(f"{elapsed:.3f}"), *args, **kwargs)

PythonLogger

PythonLogger(name: str = 'python', enabled: bool = True)

Bases: LambdaLogger

修饰符指标,负责将值打印到 python 指标实例。

参数

  • 名称

    (str, default: 'python' ) –

    用于标识指标的名称;默认为 python

  • enabled

    (bool, 默认值: True ) –

    为 True 时记录,为 False 时不记录

方法

  • log_string

    :param tag: 用于标识值的标签

源代码在 llmcompressor/metrics/logger.py
def __init__(
    self,
    name: str = "python",
    enabled: bool = True,
):
    self._create_default_logger()

    super().__init__(
        lambda_func=self._log_lambda,
        name=name,
        enabled=enabled,
    )

log_string

log_string(
    tag: str | None,
    string: str | None,
    step: int | None,
    wall_time: float | None = None,
    level: int | str | None = None,
) -> bool

参数

  • tag

    (str | None) –

    用于标识值的标签

  • string

    (str | None) –

    要记录的字符串

  • 步骤

    (int | None) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录值时的全局墙壁时间,默认为 time.time()

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

返回

  • bool

    如果已记录,则为 True,否则为 False。

源代码在 llmcompressor/metrics/logger.py
def log_string(
    self,
    tag: str | None,
    string: str | None,
    step: int | None,
    wall_time: float | None = None,
    level: int | str | None = None,
) -> bool:
    """
    :param tag: identifying tag to log the values with
    :param string: string to log
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken,
        defaults to time.time()
    :param level: minimum severity level for the log message
    :return: True if logged, False otherwise.
    """
    if not wall_time:
        wall_time = time.time()

    return self._lambda_func(
        tag=tag,
        value=string,
        values=None,
        step=step,
        level=level,
        wall_time=wall_time,
    )

SparsificationGroupLogger

SparsificationGroupLogger(
    lambda_func: Callable[
        [
            str | None,
            float | None,
            dict[str, float] | None,
            int | None,
            float | None,
        ],
        bool,
    ]
    | None = None,
    python: bool = False,
    python_log_level: int | str | None = "INFO",
    tensorboard: bool | str | SummaryWriter = None,
    wandb_: bool | dict | None = None,
    name: str = "sparsification",
    enabled: bool = True,
)

Bases: BaseLogger

修饰符指标,负责将值输出到其他支持的系统。支持的系统包括:- Python 日志- Tensorboard- Weights and Biases- Lambda 回调

所有这些都是可选的,可以由此根对象批量禁用和启用。

参数

  • lambda_func

    (Callable[[str | None, float | None, dict[str, float] | None, int | None, float | None], bool] | None, default: None ) –

    可选的 lambda 函数,用于回调并传递任何日志。预期的调用序列是 (tag, value, values, step, wall_time) -> bool 返回 True 表示已记录,否则返回 False。

  • python

    (bool, 默认值: False ) –

    用于日志记录到 python 指标的布尔参数。如果为 True,则创建指标实例;如果为 False,则不记录任何内容

  • python_log_level

    (int | str | None, default: 'INFO' ) –

    如果 python 为 True,则在 loguru.logger 实例上记录任何传入数据的级别

  • tensorboard

    (bool | str | SummaryWriter, default: None ) –

    用于日志记录到 tensorboard 编写器的可选参数。可以是用于日志记录的 SummaryWriter 实例、表示创建新 SummaryWriter 以用于日志记录的目录的字符串、True(创建新 SummaryWriter),或非真值(False、None)以不记录任何内容

  • wandb_

    (bool | dict | None, default: None ) –

    用于日志记录到 wandb 的可选参数。可以是传递给 wandb.init 的字典、True(用于日志记录到 wandb,不会调用 init),或非真值(False、None)以不记录任何内容

  • 名称

    (str, default: 'sparsification' ) –

    用于标识指标的名称;默认为 sparsification

  • enabled

    (bool, 默认值: True ) –

    为 True 时记录,为 False 时不记录

方法

  • enabled

    :param value: 为 True 时记录,为 False 时不记录

  • log_hyperparams

    :param params: 字典中的每个键值对都是超参数的名称

  • log_scalar

    :param tag: 用于标识值的标签

  • log_scalars

    :param tag: 用于标识值的标签

属性

源代码在 llmcompressor/metrics/logger.py
def __init__(
    self,
    lambda_func: Callable[
        [
            str | None,
            float | None,
            dict[str, float] | None,
            int | None,
            float | None,
        ],
        bool,
    ]
    | None = None,
    python: bool = False,
    python_log_level: int | str | None = "INFO",
    tensorboard: bool | str | SummaryWriter = None,
    wandb_: bool | dict | None = None,
    name: str = "sparsification",
    enabled: bool = True,
):
    super().__init__(name, enabled)
    self._loggers: list[BaseLogger] = []

    if lambda_func:
        self._loggers.append(
            LambdaLogger(lambda_func=lambda_func, name=name, enabled=enabled)
        )

    if python:
        self._loggers.append(
            PythonLogger(
                name=name,
                enabled=enabled,
            )
        )

    if tensorboard and TensorBoardLogger.available():
        self._loggers.append(
            TensorBoardLogger(
                log_path=tensorboard if isinstance(tensorboard, str) else None,
                writer=(
                    tensorboard if isinstance(tensorboard, SummaryWriter) else None
                ),
                name=name,
                enabled=enabled,
            )
        )

    if wandb_ and WANDBLogger.available():
        self._loggers.append(
            WANDBLogger(
                init_kwargs=wandb_ if isinstance(wandb_, dict) else None,
                name=name,
                enabled=enabled,
            )
        )

loggers property

loggers: list[BaseLogger]

返回

  • list[BaseLogger]

    为此指标创建的指标子实例

enabled

enabled(value: bool)

参数

  • (bool) –

    为 True 时记录,为 False 时不记录

源代码在 llmcompressor/metrics/logger.py
@BaseLogger.enabled.setter
def enabled(self, value: bool):
    """
    :param value: True to log, False otherwise
    """
    self._enabled = value

    for log in self._loggers:
        log.enabled = value

log_hyperparams

log_hyperparams(
    params: dict, level: int | str | None = None
)

参数

  • params

    (dict) –

    字典中的每个键值对都是超参数的名称及其对应的值。

源代码在 llmcompressor/metrics/logger.py
def log_hyperparams(self, params: dict, level: int | str | None = None):
    """
    :param params: Each key-value pair in the dictionary is the name of the
        hyper parameter and it's corresponding value.
    """
    for log in self._loggers:
        log.log_hyperparams(params, level)

log_scalar

log_scalar(
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
)

参数

  • tag

    (str) –

    用于标识值的标签

  • (float) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录该值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录值时的全局墙壁时间,默认为 time.time()

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

源代码在 llmcompressor/metrics/logger.py
def log_scalar(
    self,
    tag: str,
    value: float,
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
):
    """
    :param tag: identifying tag to log the value with
    :param value: value to save
    :param step: global step for when the value was taken
    :param wall_time: global wall time for when the value was taken,
        defaults to time.time()
    :param level: minimum severity level for the log message
    """
    for log in self._loggers:
        log.log_scalar(tag, value, step, wall_time, level)

log_scalars

log_scalars(
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
)

参数

  • tag

    (str) –

    用于标识值的标签

  • (dict[str, float]) –

    要保存的值

  • 步骤

    (int | None, 默认值: None ) –

    记录这些值时的全局步数

  • wall_time

    (float | None, 默认值: None ) –

    记录值时的全局墙壁时间,默认为 time.time()

  • 级别

    (int | str | None, default: None ) –

    日志消息的最低严重级别

源代码在 llmcompressor/metrics/logger.py
def log_scalars(
    self,
    tag: str,
    values: dict[str, float],
    step: int | None = None,
    wall_time: float | None = None,
    level: int | str | None = None,
):
    """
    :param tag: identifying tag to log the values with
    :param values: values to save
    :param step: global step for when the values were taken
    :param wall_time: global wall time for when the values were taken,
        defaults to time.time()
    :param level: minimum severity level for the log message
    """
    for log in self._loggers:
        log.log_scalars(tag, values, step, wall_time, level)

TensorBoardLogger

TensorBoardLogger(
    log_path: str = None,
    writer: SummaryWriter = None,
    name: str = "tensorboard",
    enabled: bool = True,
)

Bases: LambdaLogger

修饰符指标,负责将值输出到 TensorBoard 日志目录,以便在 TensorBoard 中查看。

参数

  • log_path

    (str, default: None ) –

    创建 SummaryWriter 的路径。如果未提供,则必须将 writer 设置为 None(如果 writer 为 None),将将在当前工作目录中创建一个 TensorBoard 目录。

  • writer

    (SummaryWriter, default: None ) –

    用于记录结果的编写器;如果未提供,则将在 log_path 处创建一个新的编写器。

  • 名称

    (str, default: 'tensorboard' ) –

    用于标识指标的名称;默认为 tensorboard

  • enabled

    (bool, 默认值: True ) –

    为 True 时记录,为 False 时不记录

方法

  • available

    :return: 如果 tensorboard 可用且已安装,则返回 True;否则返回 False。

属性

  • writer (SummaryWriter) –

    :return: 用于记录结果的编写器。

源代码在 llmcompressor/metrics/logger.py
def __init__(
    self,
    log_path: str = None,
    writer: SummaryWriter = None,
    name: str = "tensorboard",
    enabled: bool = True,
):
    if tensorboard_import_error:
        raise tensorboard_import_error

    if writer and log_path:
        raise ValueError(
            (
                "log_path given:{} and writer object passed in, "
                "to create a writer at the log path set writer=None"
            ).format(log_path)
        )
    elif not writer and not log_path:
        log_path = os.path.join("", "tensorboard")

    if os.environ.get("NM_TEST_MODE"):
        test_log_root = os.environ.get("NM_TEST_LOG_DIR")
        log_path = (
            os.path.join(test_log_root, log_path) if log_path else test_log_root
        )

    if log_path:
        _create_dirs(log_path)

    self._writer = writer if writer is not None else SummaryWriter(log_path)
    super().__init__(
        lambda_func=self._log_lambda,
        name=name,
        enabled=enabled,
    )

writer property

writer: SummaryWriter

返回

  • SummaryWriter

    用于记录结果的编写器;如果未提供,则将在 log_path 处创建一个新的编写器。

available staticmethod

available() -> bool

返回

  • bool

    如果 tensorboard 可用且已安装,则返回 True;否则返回 False。

源代码在 llmcompressor/metrics/logger.py
@staticmethod
def available() -> bool:
    """
    :return: True if tensorboard is available and installed, False, otherwise
    """
    return not tensorboard_import_error

WANDBLogger

WANDBLogger(
    init_kwargs: dict | None = None,
    name: str = "wandb",
    enabled: bool = True,
    wandb_err: Exception | None = wandb_err,
)

Bases: LambdaLogger

修饰符指标,负责将值输出到 Weights and Biases。

参数

  • init_kwargs

    (dict | None, default: None ) –

    传递给 wandb.init 的参数;例如:wandb.init(**init_kwargs)。如果未提供,则不会调用 init。

  • 名称

    (str, default: 'wandb' ) –

    用于标识指标的名称;默认为 wandb

  • enabled

    (bool, 默认值: True ) –

    为 True 时记录,为 False 时不记录

方法

  • available

    :return: 如果 wandb 可用且已安装,则返回 True;否则返回 False。

  • save

    :param file_path: 要保存的文件路径

源代码在 llmcompressor/metrics/logger.py
def __init__(
    self,
    init_kwargs: dict | None = None,
    name: str = "wandb",
    enabled: bool = True,
    wandb_err: Exception | None = wandb_err,
):
    if wandb_err:
        raise wandb_err

    super().__init__(
        lambda_func=self._log_lambda,
        name=name,
        enabled=enabled,
    )

    if os.environ.get("NM_TEST_MODE"):
        test_log_path = os.environ.get("NM_TEST_LOG_DIR")
        _create_dirs(test_log_path)
        if init_kwargs:
            init_kwargs["dir"] = test_log_path
        else:
            init_kwargs = {"dir": test_log_path}

    if wandb_err:
        raise wandb_err

    if init_kwargs:
        wandb.init(**init_kwargs)
    else:
        wandb.init()

    self.wandb = wandb

available staticmethod

available() -> bool

返回

  • bool

    如果 wandb 可用且已安装,则返回 True;否则返回 False。

源代码在 llmcompressor/metrics/logger.py
@staticmethod
def available() -> bool:
    """
    :return: True if wandb is available and installed, False, otherwise
    """
    return wandb_available

save

save(file_path: str) -> bool

参数

  • 文件路径

    (str) –

    要保存的文件路径

源代码在 llmcompressor/metrics/logger.py
def save(
    self,
    file_path: str,
) -> bool:
    """
    :param file_path: path to a file to be saved
    """
    wandb.save(file_path)
    return True