llmcompressor.utils
LLM Compressor 中使用的通用实用函数。
模块
-
dev– -
fsdp– -
helpers–通用实用助手函数。
-
metric_logging–用于指标日志记录和 GPU 内存监控的实用函数。
-
pytorch– -
transformers–
类
-
NumpyArrayBatcher–Batcher 实例,用于处理 numpy 数组字典的输入,将多个项目附加到它们上面以增加批次大小,然后将它们堆叠成所有字典键的单个批处理 numpy 数组。
函数
-
DisableQuantization–在应用量化配置后,在前向传递期间禁用量化。
-
bucket_iterable–将可迭代对象分桶到子数组中,该子数组由前 top 百分比的元素组成。
-
calibration_forward_context–所有校准前向传递应发生的上下文。
-
clean_path–:param path: 要清理的目录或文件路径。
-
convert_to_bool–:param val: 要转换为布尔值的参数。
-
create_dirs–:param path: 要尝试创建的目录路径。
-
create_parent_dirs–:param path: 要为其尝试创建父目录的文件路径。
-
create_unique_dir–:param path: 要创建唯一版本的路径。
-
disable_cache–暂时禁用 Transformer 模型的键值缓存。用于防止在仅执行预填充阶段而不执行生成阶段的一次性情况下占用过多内存。
-
disable_hf_kernels–在 transformers>=4.50.0 中,某些模块的前向方法可能会被 hf hub 内核调用替换。这可能会绕过 LLM Compressor 添加的钩子。
-
disable_lm_head–通过将 lm_head 移动到 meta 设备来禁用模型的 lm_head。此函数不会解开参数,并在退出时恢复模型的正确加载。
-
dispatch_for_generation–分派模型的自回归生成。这意味着模块将被平均分派到可用设备上,并尽可能保持加载状态。移除任何先前可能存在的 HF 钩子。
-
eval_context–禁用给定模块的 PyTorch 训练模式。
-
flatten_iterable–:param li: 要展平的可能嵌套的可迭代对象。
-
get_embeddings–返回模型的输入和输出嵌入。如果
get_input_embeddings/。 -
getattr_chain–链式调用多个 getattr 调用,用
.分隔。 -
import_from_path–导入由 . 分隔的模块和函数/类名。
-
interpolate–注意,将值限制在 x0 的最小值和 x1 的最大值,
-
interpolate_list_linear–线性插值测量值列表内的输入值。
-
interpolated_integral–计算一组形式为 [(x0, y0), (x1, y1), ...] 的测量的插值积分。
-
is_package_available–检查包是否可用的辅助函数。
-
is_url–:param val: 要检查的值是否为 url。
-
json_to_jsonl–将 json 列表文件转换为 jsonl 文件格式(用于分片效率)。
-
load_labeled_data–从磁盘或内存加载标签和数据并将它们组合在一起。假定磁盘上的排序顺序。当为 data 和/或 labels 提供文件 glob 时,它们将匹配。
-
load_numpy–将 numpy 文件加载到 ndarray 或 OrderedDict 中,表示 npz 文件中的内容。
-
patch_attr–修补对象属性的值。原始值在退出时恢复。
-
patch_transformers_logger_level–修改 transformers 日志记录器级别的上下文。
-
path_file_count–返回给定路径下匹配给定模式的文件数。
-
path_file_size–返回文件系统上给定路径的总大小(以字节为单位)。
-
save_numpy–将 numpy 数组或 numpy 数组集合保存到磁盘。
-
skip_weights_download–在此上下文中初始化模型,而无需下载。
-
targets_embeddings–返回给定目标是否针对模型词嵌入。
-
tensor_export–:param tensor: 要导出到已保存 numpy 数组文件的张量。
-
tensors_export–:param tensors: 要导出到已保存 numpy 数组文件的张量。
-
untie_word_embeddings–如果可能,解绑词嵌入。如果模型定义中找不到嵌入,此函数将发出警告。
-
validate_str_iterable–:param val: 要验证的值,检查它是否是列表(并将其展平)。
NumpyArrayBatcher
Bases: object
Batcher 实例,用于处理 numpy 数组字典的输入,将多个项目附加到它们上面以增加批次大小,然后将它们堆叠成所有字典键的单个批处理 numpy 数组。
方法
Source code in llmcompressor/utils/helpers.py
append
将新项目附加到当前批次中。所有键和形状必须与当前状态匹配。
参数
-
(itemUnion[ndarray, Dict[str, ndarray]]) –要添加到批次的项。
Source code in llmcompressor/utils/helpers.py
stack
将当前项目堆叠成一个批次,沿着新的、零填充的维度。
返回
-
Dict[str, ndarray]–堆叠的项。
Source code in llmcompressor/utils/helpers.py
DisableQuantization
在应用量化配置后,在前向传递期间禁用量化。
Source code in llmcompressor/utils/helpers.py
bucket_iterable
bucket_iterable(
val: Iterable[Any],
num_buckets: int = 3,
edge_percent: float = 0.05,
sort_highest: bool = True,
sort_key: Callable[[Any], Any] = None,
) -> List[Tuple[int, Any]]
将可迭代对象分桶到子数组中,该子数组由前 top 百分比的元素组成,然后将可迭代对象的其余部分切分成相等大小的块。
参数
-
(验证Iterable[Any]) –要分桶的可迭代对象。
-
(num_bucketsint, default:3) –要将可迭代对象分组的桶数,不包括 top 桶。
-
(edge_percentfloat, default:0.05) –将前百分比的元素放入自己的桶中。如果 sort_highest 为 True,则这是 top 百分比;否则是 bottom 百分比。如果 <= 0,则不会创建边缘桶。
-
(sort_highestbool, 默认值:True) –True 表示按降序排序,使最高百分比的元素在前,并按降序创建桶。False 表示按升序排序,使最低百分比的元素在前,并按升序创建桶。
-
(sort_keyCallable[[Any], Any], default:None) –用于对可迭代对象进行排序的 sort_key,如果已将其转换为列表。
返回
-
List[Tuple[int, Any]]–一个列表,其中每个值都映射到它被排序到的桶。
Source code in llmcompressor/utils/helpers.py
calibration_forward_context
所有校准前向传递应发生的上下文。
- 移除梯度计算。
- 禁用 KV 缓存。
- 禁用训练模式并启用评估模式。
- 禁用 hf 内核,这可能会绕过钩子。
- 禁用 lm head(输入和权重仍可校准,输出将为 meta)。
Source code in llmcompressor/utils/helpers.py
clean_path
参数
-
(路径str) –要清理的目录或文件路径。
返回
-
str–一个清理后的版本,它会展开用户路径并创建绝对路径。
Source code in llmcompressor/utils/helpers.py
convert_to_bool
参数
-
(验证Any) –要转换为布尔值的值,支持字符串形式的逻辑值,例如 True、t、false、0。
返回
- –
值的布尔表示形式,如果无法确定,则回退为返回 True。
Source code in llmcompressor/utils/helpers.py
create_dirs
参数
-
(路径str) –要尝试创建的目录路径。
Source code in llmcompressor/utils/helpers.py
create_parent_dirs
create_unique_dir
参数
-
(路径str) –要创建唯一版本的文件路径(附加数字直到其中一个不存在)。
-
(check_numberint, 默认值:0) –开始检查唯一版本的数字。
返回
-
str–唯一的目录路径。
Source code in llmcompressor/utils/helpers.py
disable_cache
暂时禁用 Transformer 模型的键值缓存。用于防止在仅执行预填充阶段而不执行生成阶段的一次性情况下占用过多内存。
示例
model = AutoModel.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0") input = torch.randint(0, 32, size=(1, 32)) with disable_cache(model): ... output = model(input)
Source code in llmcompressor/utils/helpers.py
disable_hf_kernels
在 transformers>=4.50.0 中,某些模块的前向方法可能会被 hf hub 内核调用替换。这可能会绕过 LLM Compressor 添加的钩子。
Source code in llmcompressor/utils/helpers.py
disable_lm_head
通过将 lm_head 移动到 meta 设备来禁用模型的 lm_head。此函数不会解开参数,并在退出时恢复模型的正确加载。
Source code in llmcompressor/utils/helpers.py
dispatch_for_generation
分派模型的自回归生成。这意味着模块将被平均分派到可用设备上,并尽可能保持加载状态。移除任何先前可能存在的 HF 钩子。
参数
-
(modelPreTrainedModel) –要分发的模型
返回
-
PreTrainedModel–要分派的模型。
Source code in llmcompressor/utils/dev.py
eval_context
禁用给定模块的 PyTorch 训练模式。
Source code in llmcompressor/utils/helpers.py
flatten_iterable
参数
-
(liIterable) –要展平的可能嵌套的可迭代对象。
返回
- –
一个展平后的列表,所有元素都按深度优先模式放在一个列表中。
Source code in llmcompressor/utils/helpers.py
get_embeddings
返回模型的输入和输出嵌入。如果 get_input_embeddings/ get_output_embeddings 在模型上未实现,则返回 None。
参数
-
(modelPreTrainedModel) –要从中获取嵌入的模型。
返回
-
tuple[Module | None, Module | None]–包含嵌入模块或 None 的元组。
源代码位于 llmcompressor/utils/transformers.py
getattr_chain
链式调用多个 getattr 调用,用 . 分隔。
参数
-
(objAny) –正在检索属性的基础对象。
-
(chain_strstr) –用
.分隔的属性名。 -
–default默认值,否则抛出错误。
Source code in llmcompressor/utils/helpers.py
import_from_path
导入由 : 分隔的模块和函数/类名。示例:path = "/path/to/file.py:func_or_class_name" path = "/path/to/file:focn" path = "path.to.file:focn"
参数
-
(路径str) –包含文件路径和对象名的路径。
Source code in llmcompressor/utils/helpers.py
interpolate
interpolate(
x_cur: float,
x0: float,
x1: float,
y0: Any,
y1: Any,
inter_func: str = "linear",
) -> Any
注意,将值限制在 x0 的最小值和 x1 的最大值,设计为不在此范围外工作,出于实现原因。
参数
-
(x_curfloat) –x 的当前值,应介于 x0 和 x1 之间。
-
(x0float) –x 插值之间的最小值。
-
(x1float) –x 插值之间的最大值。
-
(y0Any) –y 插值之间的最小值。
-
(y1Any) –y 插值之间的最大值。
-
(inter_funcstr, default:'linear') –用于插值函数的类型:linear、cubic、inverse_cubic。
返回
-
Any–将 x 映射到 y 的插值值,用于给定的插值函数。
Source code in llmcompressor/utils/helpers.py
interpolate_list_linear
interpolate_list_linear(
measurements: List[Tuple[float, float]],
x_val: Union[float, List[float]],
) -> List[Tuple[float, float]]
线性插值测量值列表内的输入值。
参数
-
(measurementsList[Tuple[float, float]]) –要从中插值的测量值列表。
-
(x_valUnion[float, List[float]]) –要插值到第二个维度的目标值。
返回
-
List[Tuple[float, float]]–包含目标值和插值值的元组列表。
Source code in llmcompressor/utils/helpers.py
interpolated_integral
计算一组形式为 [(x0, y0), (x1, y1), ...] 的测量的插值积分。
参数
-
(measurementsList[Tuple[float, float]]) –要计算积分的测量值。
返回
- –
给定测量值的积分或曲线下的面积。
Source code in llmcompressor/utils/helpers.py
is_package_available
is_package_available(
package_name: str, return_version: bool = False
) -> Union[Tuple[bool, str], bool]
一个辅助函数,用于检查包是否可用,并可选择返回其版本。此函数强制检查包是否可用,而不仅仅是名称与包相同的目录/文件。
参数
-
(package_namestr) –要检查的包名。
-
(return_versionbool, 默认值:False) –如果可用,则返回包版本,设置为 True。
返回
-
Union[Tuple[bool, str], bool]–如果包可用,则返回 True,否则返回 False;如果 return_version 为 True,则返回 (bool, version) 的元组。
Source code in llmcompressor/utils/helpers.py
is_url
参数
-
(验证str) –要检查的值是否为 url。
返回
- –
如果值为 URL,则返回 True,否则返回 False。
Source code in llmcompressor/utils/helpers.py
json_to_jsonl
将 json 列表文件转换为 jsonl 文件格式(用于分片效率)。例如:[{"a": 1}, {"a": 1}] 将转换为:{"a": 1}
参数
-
(json_file_pathstr) –包含 json 对象列表的 json 文件路径。
-
(overwritebool, 默认值:True) –如果为 True,将覆盖现有 json 文件;如果为 False,文件将具有相同的名称,但扩展名为 .jsonl。
Source code in llmcompressor/utils/helpers.py
load_labeled_data
load_labeled_data(
data: Union[
str,
Iterable[Union[str, ndarray, Dict[str, ndarray]]],
],
labels: Union[
None,
str,
Iterable[Union[str, ndarray, Dict[str, ndarray]]],
],
raise_on_error: bool = True,
) -> List[
Tuple[
Union[numpy.ndarray, Dict[str, numpy.ndarray]],
Union[
None, numpy.ndarray, Dict[str, numpy.ndarray]
],
]
]
从磁盘或内存加载标签和数据并将它们组合在一起。假定磁盘上的排序顺序。当为 data 和/或 labels 提供文件 glob 时,它们将匹配。
参数
-
(dataUnion[str, Iterable[Union[str, ndarray, Dict[str, ndarray]]]]) –用于数据的 glob 文件、tar 包文件路径或数组列表。
-
(labelsUnion[None, str, Iterable[Union[str, ndarray, Dict[str, ndarray]]]]) –用于标签的 glob 文件、tar 包文件路径或数组列表,如果有的话。
-
(raise_on_errorbool, 默认值:True) –如果为 True,则在发生任何错误时引发;如果为 False,则记录警告、忽略并继续。
返回
-
List[Tuple[Union[ndarray, Dict[str, ndarray]], Union[None, ndarray, Dict[str, ndarray]]]]–一个列表,包含数据和标签的元组。如果 labels 为 None,则在每个元组的第二个索引处包含 None。
Source code in llmcompressor/utils/helpers.py
load_numpy
将 numpy 文件加载到 ndarray 或 OrderedDict 中,表示 npz 文件中的内容。
参数
-
(文件路径str) –要加载的文件路径。
返回
-
Union[ndarray, Dict[str, ndarray]]–从文件中加载的值。
Source code in llmcompressor/utils/helpers.py
patch_attr
修补对象属性的值。原始值在退出时恢复。
参数
-
(baseobject) –拥有要修补的属性的对象。
-
(attrstr) –要修补的属性的名称。
-
(值Any) –用于替换原始值。用法:>>> from types import SimpleNamespace >>> obj = SimpleNamespace() >>> with patch_attr(obj, "attribute", "value"): ... assert obj.attribute == "value" >>> assert not hasattr(obj, "attribute")
Source code in llmcompressor/utils/helpers.py
patch_transformers_logger_level
修改 transformers 日志记录器级别的上下文。
可以与 skip_weights_download 一起使用,以抑制与检查点中缺失参数相关的警告。
参数
-
(级别int, default:ERROR) –transformers 日志记录器的新日志级别。低于此级别的日志将不会被记录。
Source code in llmcompressor/utils/dev.py
path_file_count
返回给定路径下匹配给定模式的文件数。
参数
-
(路径str) –要在其下查找文件的目录路径。
-
(patternstr, default:'*') –文件必须匹配的模式才能被计数。
返回
-
int–目录中匹配模式的文件数。
Source code in llmcompressor/utils/helpers.py
path_file_size
返回文件系统上给定路径的总大小(以字节为单位)。
参数
-
(路径str) –要获取大小的路径(目录或文件)。
返回
-
int–存储在磁盘上的路径大小(以字节为单位)。
Source code in llmcompressor/utils/helpers.py
save_numpy
save_numpy(
array: Union[
ndarray, Dict[str, ndarray], Iterable[ndarray]
],
export_dir: str,
name: str,
npz: bool = True,
)
将 numpy 数组或 numpy 数组集合保存到磁盘。
参数
-
(arrayUnion[ndarray, Dict[str, ndarray], Iterable[ndarray]]) –要保存的数组或数组集合。
-
(export_dirstr) –要导出 numpy 文件的目录。
-
(名称str) –要导出到的文件名(不带扩展名)。
-
(npzbool, 默认值:True) –True 表示保存为 npz 压缩文件,False 表示标准 npy。注意,npy 只能用于单个 numpy 数组。
返回
- –
保存的路径。
Source code in llmcompressor/utils/helpers.py
skip_weights_download
在此上下文中初始化模型,而无需下载模型权重文件。这与 init_empty_weights 不同,后者将权重分配到 meta 设备上,而此处权重被分配到指定的设备上并用随机值填充。
参数
-
(model_classType[PreTrainedModel], default:AutoModelForCausalLM) –要修补的类,默认为
AutoModelForCausalLM。
Source code in llmcompressor/utils/dev.py
targets_embeddings
targets_embeddings(
model: PreTrainedModel,
targets: NamedModules,
check_input: bool = True,
check_output: bool = True,
) -> bool
返回给定目标是否针对模型词嵌入。
参数
-
(modelPreTrainedModel) –包含词嵌入。
-
(targetsNamedModules) –要检查的命名模块。
-
(check_inputbool, 默认值:True) –是否检查输入嵌入是否被目标。
-
(check_outputbool, 默认值:True) –是否检查输出嵌入是否被目标。
返回
-
bool–如果嵌入被目标,则返回 True,否则返回 False。
源代码位于 llmcompressor/utils/transformers.py
tensor_export
tensor_export(
tensor: Union[
ndarray, Dict[str, ndarray], Iterable[ndarray]
],
export_dir: str,
name: str,
npz: bool = True,
) -> str
参数
-
(tensorUnion[ndarray, Dict[str, ndarray], Iterable[ndarray]]) –要导出到已保存 numpy 数组文件的张量。
-
(export_dirstr) –要在其中导出文件的目录。
-
(名称str) –文件名,将附加 .npy。
-
(npzbool, 默认值:True) –True 表示导出为 npz 文件,否则为 False。
返回
-
str–张量被导出到的 numpy 文件的路径。
Source code in llmcompressor/utils/helpers.py
tensors_export
tensors_export(
tensors: Union[
ndarray, Dict[str, ndarray], Iterable[ndarray]
],
export_dir: str,
name_prefix: str,
counter: int = 0,
break_batch: bool = False,
) -> List[str]
参数
-
(tensorsUnion[ndarray, Dict[str, ndarray], Iterable[ndarray]]) –要导出到已保存 numpy 数组文件的张量。
-
(export_dirstr) –要在其中导出文件的目录。
-
(name_prefixstr) –要保存为张量的前缀名称,将附加有关张量在列表或字典中的位置的信息,此外还有 .npy 文件格式
-
(counterint, 默认值:0) –当前保存张量的计数器
-
(break_batchbool, 默认值:False) –将张量视为一个批次并拆分为多个张量
返回
-
List[str]–导出的路径
Source code in llmcompressor/utils/helpers.py
untie_word_embeddings
如果可能,解绑词嵌入。如果模型定义中找不到嵌入,此函数将发出警告。
模型配置将更新以反映嵌入现已解绑
参数
-
(modelPreTrainedModel) –包含词嵌入的 transformers 模型
源代码位于 llmcompressor/utils/transformers.py
validate_str_iterable
validate_str_iterable(
val: Union[str, Iterable[str]], error_desc: str = ""
) -> Union[str, Iterable[str]]
参数
-
(验证Union[str, Iterable[str]]) –要验证的值,检查它是否为列表(并将其展平),否则检查它是否为 **ALL** 或 **ALL_PRUNABLE** 字符串,否则引发 ValueError
-
(error_descstr, 默认值:'') –在 val 无效时用于引发错误的描述
返回
-
Union[str, Iterable[str]]–参数的已验证版本