WandaSparsifier¶
- class torchao.sparsity.WandaSparsifier(sparsity_level: float = 0.5, semi_structured_block_size: Optional[int] = None)[來源]¶
Wanda 稀疏器
Wanda (透過權重和激活進行剪枝),在 https://arxiv.org/abs/2306.11695 中提出,是一種激活感知的剪枝方法。該稀疏器基於輸入激活範數和權重幅度的乘積來移除權重。
此稀疏器由三個變數控制:1. sparsity_level 定義了被歸零的稀疏區塊的數量;
- 參數:
sparsity_level – 目標稀疏度;
model – 要稀疏化的模型;
- prepare(model: Module, config: List[Dict]) None [來源]¶
透過添加參數化來準備模型。
注意
The model is modified inplace. If you need to preserve the original model, use copy.deepcopy.
- squash_mask(params_to_keep: Optional[Tuple[str, ...]] = None, params_to_keep_per_layer: Optional[Dict[str, Tuple[str, ...]]] = None, *args, **kwargs)[source]¶
將稀疏遮罩壓縮到適當的張量中。
如果設定了 params_to_keep 或 params_to_keep_per_layer,則該模組將附加一個 sparse_params 字典。
- 參數:
params_to_keep – 要保存在模組中的鍵列表,或表示將保存稀疏參數的模組和鍵的字典
params_to_keep_per_layer – 用於指定應為特定層保存的參數的字典。字典中的鍵應為模組 FQN,而值應為字串列表,其中包含要在 sparse_params 中儲存的變數名稱
範例
>>> # xdoctest: +SKIP("locals are undefined") >>> # Don't save any sparse params >>> sparsifier.squash_mask() >>> hasattr(model.submodule1, 'sparse_params') False
>>> # Keep sparse params per layer >>> sparsifier.squash_mask( ... params_to_keep_per_layer={ ... 'submodule1.linear1': ('foo', 'bar'), ... 'submodule2.linear42': ('baz',) ... }) >>> print(model.submodule1.linear1.sparse_params) {'foo': 42, 'bar': 24} >>> print(model.submodule2.linear42.sparse_params) {'baz': 0.1}
>>> # Keep sparse params for all layers >>> sparsifier.squash_mask(params_to_keep=('foo', 'bar')) >>> print(model.submodule1.linear1.sparse_params) {'foo': 42, 'bar': 24} >>> print(model.submodule2.linear42.sparse_params) {'foo': 42, 'bar': 24}
>>> # Keep some sparse params for all layers, and specific ones for >>> # some other layers >>> sparsifier.squash_mask( ... params_to_keep=('foo', 'bar'), ... params_to_keep_per_layer={ ... 'submodule2.linear42': ('baz',) ... }) >>> print(model.submodule1.linear1.sparse_params) {'foo': 42, 'bar': 24} >>> print(model.submodule2.linear42.sparse_params) {'foo': 42, 'bar': 24, 'baz': 0.1}