-
Notifications
You must be signed in to change notification settings - Fork 6.3k
[wip][quantization] incorporate nunchaku
#12207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
8e1ea00
start nunchaku.
sayakpaul 7022169
up
sayakpaul f4262b8
up
sayakpaul ac1aa8b
up
sayakpaul 269813f
up
sayakpaul 9e0caa7
up
sayakpaul 5d08150
up
sayakpaul d35e77e
up
sayakpaul 2a827ec
up
sayakpaul df58c80
up
sayakpaul 4af534b
up
sayakpaul 8e07445
up
sayakpaul 3295c6a
up
sayakpaul File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
src/diffusers/loaders/single_file_utils_nunchaku.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
import re | ||
|
||
import torch | ||
|
||
|
||
_QKV_ANCHORS_NUNCHAKU = ("to_qkv", "add_qkv_proj") | ||
_ALLOWED_SUFFIXES_NUNCHAKU = { | ||
"bias", | ||
"proj_down", | ||
"proj_up", | ||
"qweight", | ||
"smooth_factor", | ||
"smooth_factor_orig", | ||
"wscales", | ||
} | ||
|
||
_QKV_NUNCHAKU_REGEX = re.compile( | ||
rf"^(?P<prefix>.*)\.(?:{'|'.join(map(re.escape, _QKV_ANCHORS_NUNCHAKU))})\.(?P<suffix>.+)$" | ||
) | ||
|
||
|
||
def _pick_split_dim(t: torch.Tensor, suffix: str) -> int: | ||
""" | ||
Choose which dimension to split by 3. Heuristics: | ||
- 1D -> dim 0 | ||
- 2D -> prefer dim=1 for 'qweight' (common layout [*, 3*out_features]), | ||
otherwise prefer dim=0 (common layout [3*out_features, *]). | ||
- If preferred dim isn't divisible by 3, try the other; else error. | ||
""" | ||
shape = list(t.shape) | ||
if len(shape) == 0: | ||
raise ValueError("Cannot split a scalar into Q/K/V.") | ||
|
||
if len(shape) == 1: | ||
dim = 0 | ||
if shape[dim] % 3 == 0: | ||
return dim | ||
raise ValueError(f"1D tensor of length {shape[0]} not divisible by 3.") | ||
|
||
# len(shape) >= 2 | ||
preferred = 1 if suffix == "qweight" else 0 | ||
other = 0 if preferred == 1 else 1 | ||
|
||
if shape[preferred] % 3 == 0: | ||
return preferred | ||
if shape[other] % 3 == 0: | ||
return other | ||
|
||
# Fall back: any dim divisible by 3 | ||
for d, s in enumerate(shape): | ||
if s % 3 == 0: | ||
return d | ||
|
||
raise ValueError(f"None of the dims {shape} are divisible by 3 for suffix '{suffix}'.") | ||
|
||
|
||
def _split_qkv(t: torch.Tensor, dim: int): | ||
return torch.tensor_split(t, 3, dim=dim) | ||
|
||
|
||
def _unpack_qkv_state_dict( | ||
state_dict: dict, anchors=_QKV_ANCHORS_NUNCHAKU, allowed_suffixes=_ALLOWED_SUFFIXES_NUNCHAKU | ||
): | ||
""" | ||
Convert fused QKV entries (e.g., '...to_qkv.bias', '...qkv_proj.wscales') into separate Q/K/V entries: | ||
'...to_q.bias', '...to_k.bias', '...to_v.bias' '...to_q.wscales', '...to_k.wscales', '...to_v.wscales' | ||
Returns a NEW dict; original is not modified. | ||
|
||
Only keys with suffix in `allowed_suffixes` are processed. Keys with non-divisible-by-3 tensors raise a ValueError.: | ||
""" | ||
anchors = tuple(anchors) | ||
allowed_suffixes = set(allowed_suffixes) | ||
|
||
new_sd: dict = {} | ||
sd_keys = list(state_dict.keys()) | ||
for k in sd_keys: | ||
m = _QKV_NUNCHAKU_REGEX.match(k) | ||
v = state_dict.pop(k) | ||
if m: | ||
suffix = m.group("suffix") | ||
if suffix not in allowed_suffixes: | ||
# keep as-is if it's not one of the targeted suffixes | ||
new_sd[k] = v | ||
continue | ||
|
||
prefix = m.group("prefix") # everything before .to_qkv/.qkv_proj | ||
# Decide split axis | ||
split_dim = _pick_split_dim(v, suffix) | ||
q, k_, vv = _split_qkv(v, dim=split_dim) | ||
|
||
# Build new keys | ||
base_q = f"{prefix}.to_q.{suffix}" | ||
base_k = f"{prefix}.to_k.{suffix}" | ||
base_v = f"{prefix}.to_v.{suffix}" | ||
|
||
# Write into result dict | ||
new_sd[base_q] = q | ||
new_sd[base_k] = k_ | ||
new_sd[base_v] = vv | ||
else: | ||
# not a fused qkv key | ||
new_sd[k] = v | ||
|
||
return new_sd |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.