-
Notifications
You must be signed in to change notification settings - Fork 302
[AWQ] use match_modules_set and fix logic #2070
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
HDCharles
wants to merge
6
commits into
main
Choose a base branch
from
96_awq_match_module_set
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+135
−81
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
69cf95b
[AWQ] small refactor to use match_modules_set
HDCharles dc8e3ae
formatting
HDCharles 351568d
fixing logic and test update
HDCharles dea5eab
updates to get_lowest_common_x
HDCharles 728b8c0
format
HDCharles b9d3cea
Merge branch 'main' into 96_awq_match_module_set
HDCharles 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ | |
| from compressed_tensors.utils import ( | ||
| align_modules, | ||
| get_execution_device, | ||
| match_modules_set, | ||
| match_named_modules, | ||
| update_offload_parameter, | ||
| ) | ||
|
|
@@ -319,64 +320,48 @@ def _set_resolved_mappings(self, model: Module) -> None: | |
| repeat for model.layer.1 and so on | ||
| """ | ||
| resolved_mappings: list[ResolvedMapping] = [] | ||
| for mapping_idx, mapping in enumerate(self.mappings): | ||
| num_skipped_mappings = 0 | ||
|
|
||
| for smooth_name, smooth_layer in ( | ||
| pbar := tqdm( | ||
| match_named_modules(model, [mapping.smooth_layer], self.ignore) | ||
| module_to_name = {} | ||
| for name, module in model.named_modules(): | ||
| if module in module_to_name: | ||
| logger.info( | ||
| f"Warning, {name} and {module_to_name[module]} both " | ||
| "share the same module the same module, " | ||
| "may have trouble resolving mappings." | ||
| ) | ||
| module_to_name[module] = name | ||
|
|
||
| for mapping in self.mappings: | ||
| target_patterns = (mapping.smooth_layer, *mapping.balance_layers) | ||
|
|
||
| for smooth_layer, *balance_layers in match_modules_set( | ||
| model, target_patterns, self.ignore | ||
| ): | ||
| pbar.set_description( | ||
| f"Resolving mapping {mapping_idx+1}/{len(self.mappings)}" | ||
| f" ({num_skipped_mappings} skipped)" | ||
| smooth_name = module_to_name.get(smooth_layer) | ||
| balance_names = [ | ||
| module_to_name.get(balance_layer) | ||
| for balance_layer in balance_layers | ||
| ] | ||
|
|
||
| all_compatible = _check_layers_are_compatible( | ||
| smooth_layer, smooth_name, balance_layers, balance_names | ||
| ) | ||
|
|
||
| smooth_parent_name = ".".join(smooth_name.split(".")[:-1]) | ||
| smooth_parent = get_layer_by_name(smooth_parent_name, model) | ||
|
|
||
| balance_layers, balance_names = [], [] | ||
| for balance_regex in mapping.balance_layers: | ||
| # find the submodules that match the activation layer | ||
| for balance_suffix, balance_layer in match_named_modules( | ||
| smooth_parent, [balance_regex], self.ignore | ||
| ): | ||
| balance_name = f"{smooth_parent_name}.{balance_suffix}" | ||
|
|
||
| # exclude v_proj->o_proj mappings whose shapes are incompatible | ||
| # https://github.com/mit-han-lab/llm-awq/pull/67#issuecomment-1681632777 | ||
| if ( | ||
| isinstance(smooth_layer, torch.nn.Linear) | ||
| and isinstance(balance_layer, torch.nn.Linear) | ||
| and balance_name.endswith(".o_proj") | ||
| and ( | ||
| ( | ||
| smooth_name.endswith(".v_proj") | ||
| and smooth_layer.out_features | ||
| != balance_layer.in_features | ||
| ) | ||
| or ( | ||
| smooth_name.endswith(".qkv_proj") | ||
| and smooth_layer.out_features | ||
| != 3 * balance_layer.in_features | ||
| ) | ||
| ) | ||
| ): | ||
| num_skipped_mappings += 1 | ||
| continue | ||
|
|
||
| balance_layers.append(balance_layer) | ||
| balance_names.append(balance_name) | ||
| # skip mapping if any of the balance layers are incompatible | ||
| if not all_compatible or len(balance_layers) == 0: | ||
| logger.info( | ||
| f"skipping AWQ for {smooth_name} for mapping {mapping}" | ||
| + ( | ||
| " because found incompatible balance layers" | ||
| if not all_compatible | ||
| else " because no balance layers were found" | ||
| ) | ||
| ) | ||
|
|
||
| if len(balance_layers) == 0: | ||
| continue | ||
|
|
||
| elif len(balance_layers) == 1: | ||
| # for single balance layer, parent is the balance layer | ||
| parent_name, parent = balance_name, balance_layer | ||
| else: | ||
| # for multiple balance layers, find lowest common parent | ||
|
Comment on lines
362
to
363
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Unnecessary |
||
| parent_name, parent = get_lowest_common_parent(balance_names, model) | ||
| parent_name, parent = get_lowest_common_module(balance_names, model) | ||
|
|
||
| resolved_mappings.append( | ||
| ResolvedMapping( | ||
|
|
@@ -721,6 +706,35 @@ def _assert_all_activations_consumed(self): | |
| raise RuntimeError("Some cached activations were not used") | ||
|
|
||
|
|
||
| def _check_layers_are_compatible( | ||
| smooth_layer, smooth_name, balance_layers, balance_names | ||
| ): | ||
| """ | ||
| returns True if they are all compatible | ||
| returns False if any smooth & balance layers are incompatible | ||
| """ | ||
| for balance_layer, balance_name in zip(balance_layers, balance_names): | ||
| # exclude v_proj->o_proj mappings whose shapes are incompatible | ||
| # https://github.com/mit-han-lab/llm-awq/pull/67#issuecomment-1681632777 | ||
| if ( | ||
| isinstance(smooth_layer, torch.nn.Linear) | ||
| and isinstance(balance_layer, torch.nn.Linear) | ||
| and balance_name.endswith(".o_proj") | ||
| and ( | ||
| ( | ||
| smooth_name.endswith(".v_proj") | ||
| and smooth_layer.out_features != balance_layer.in_features | ||
| ) | ||
| or ( | ||
| smooth_name.endswith(".qkv_proj") | ||
| and smooth_layer.out_features != 3 * balance_layer.in_features | ||
| ) | ||
| ) | ||
| ): | ||
| return False | ||
| return True | ||
|
|
||
|
|
||
| def _pseudo_quantize_tensor( | ||
| w: torch.Tensor, symmetric: bool = False, bit_width: int = 8, group_size: int = -1 | ||
| ): | ||
|
|
@@ -781,29 +795,41 @@ def _accumulate_mean( | |
| return (prev_sum + sum_added) / new_count, new_count | ||
|
|
||
|
|
||
| def get_lowest_common_parent(names: list[str], module: Module) -> tuple[str, Module]: | ||
| def get_lowest_common_module(names: list[str], module: Module) -> tuple[str, Module]: | ||
| """ | ||
| Given a list of names, returns the lowest-scope common parent. | ||
| Given a list of names, returns the lowest-scope common module. | ||
|
|
||
| NOTE: function excludes parents of type ModuleList, which don't play | ||
| NOTE: function excludes modules of type ModuleList, which don't play | ||
| nicely with hooks because their forward method is never directly | ||
| called for MoE models. See Qwen3MoeSparseMoeBlock for example, experts | ||
| are selected based on router output and their forward method is called. | ||
| https://github.com/huggingface/transformers/blob/v4.52.4/src/transformers/models/qwen3_moe/modeling_qwen3_moe.py#L233 | ||
|
|
||
| Returns name of parent and pointer to parent module | ||
| Returns name of module and pointer to module | ||
|
|
||
| Implementation is a small alteration of os.path.commonprefix | ||
| https://docs.python.org/3/library/os.path.html#os.path.commonprefix | ||
| """ | ||
| s1 = min(names) | ||
| s2 = max(names) | ||
| parent_name = "" | ||
| # adding "." before and after allows for handling a lot of corner | ||
| # cases which were previously mishandled ([case]->prefix->result) | ||
| # case 0: single module: [.abc.] -> .abc. -> abc | ||
| # case 1: substring modules: [.abc., .ab.] -> .ab -> "" | ||
| # case 2: parent & child: [.ab., .ab.a.] -> .ab. -> ab | ||
| s1 = min(names) + "." | ||
| s2 = max(names) + "." | ||
|
|
||
| # 1) find longest shared prefix | ||
| parent_name = "." | ||
| for i, c in enumerate(s1): | ||
| if c != s2[i]: | ||
| parent_name = s1[:i].rstrip(".") | ||
| break | ||
| parent_name += c | ||
|
|
||
| # 2) throw away module name fragment and leading dot | ||
| # ".keep.thro" -> "keep" | ||
| parent_name = parent_name[1 : parent_name.rfind(".")] | ||
|
|
||
| # 3) return first common module that is not a module list | ||
| while True: | ||
| if parent_name == "": | ||
| return "", module | ||
|
|
||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
typo