-
Notifications
You must be signed in to change notification settings - Fork 80
feat: reduce nb experts per token in moe architectures #450
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
eb9a911
feat: draft rednoe
llcnt 592174b
feat: use tmpdir to save load with modified config
llcnt 855d328
feat: add unit test
llcnt 3aea1ec
feat: make check fn more general and fix device
llcnt 8964d9b
feat: del uv.lock to avoid transformers pined version
llcnt 3e71ec6
feat: upd numpydoc version to avoid sphinx version errors
llcnt f0e48b0
fix: add _apply for pipeleines
llcnt 69389d9
feat: change name to reduceNOE
llcnt 04ee0cf
feat: simplify usage with unconstrained hyperparameters
llcnt 61a954a
fix: adapt path to new name
llcnt a405337
fix: adjust name and singular vs plural
llcnt 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| # Copyright 2025 - Pruna AI GmbH. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import tempfile | ||
| from collections.abc import Iterable | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from ConfigSpace import UniformIntegerHyperparameter | ||
| from transformers import AutoModelForCausalLM | ||
|
|
||
| from pruna.algorithms.base.pruna_base import PrunaAlgorithmBase | ||
| from pruna.algorithms.base.tags import AlgorithmTag as tags | ||
| from pruna.config.hyperparameters import UnconstrainedHyperparameter | ||
| from pruna.config.smash_config import SmashConfigPrefixWrapper | ||
| from pruna.engine.model_checks import is_moe_lm, is_transformers_pipeline_with_moe_lm | ||
| from pruna.engine.utils import get_device_map, move_to_device, safe_memory_cleanup | ||
|
|
||
|
|
||
| class ReduceNOE(PrunaAlgorithmBase): | ||
| """ | ||
| Implement ReduceNOE for LMs and diffusers pipelines with MoE blocks. | ||
|
|
||
| ReduceNOE is a method to Reduce the Number Of Experts per token. | ||
| """ | ||
|
|
||
| algorithm_name: str = "reduce_noe" | ||
| group_tags: list[str] = [tags.PRUNER] | ||
| references: dict[str, str] = {} | ||
| tokenizer_required: bool = False | ||
| processor_required: bool = False | ||
| dataset_required: bool = False | ||
| runs_on: list[str] = ["cuda", "accelerate"] | ||
| save_fn: None = None | ||
| compatible_after: Iterable[str] = ["*"] | ||
|
|
||
| def get_hyperparameters(self) -> list: | ||
| """ | ||
| Configure all algorithm-specific hyperparameters with ConfigSpace. | ||
|
|
||
| Returns | ||
| ------- | ||
| list | ||
| The hyperparameters. | ||
| """ | ||
| return [ | ||
| UniformIntegerHyperparameter( | ||
| name="num_experts_per_token", | ||
| lower=1, | ||
| upper=256, | ||
| default_value=2, | ||
| meta=dict(desc="Number of experts triggered per token."), | ||
| ), | ||
| UnconstrainedHyperparameter( | ||
| name="target_name", | ||
| default_value="num_experts_per_tok", | ||
| meta=dict( | ||
| desc="Name of of the parameter in the config.json file to be modified, " | ||
| "e.g. 'num_experts_per_tok' for mixtral models. " | ||
| ), | ||
| ), | ||
| ] | ||
|
|
||
| def model_check_fn(self, model: Any) -> bool: | ||
| """ | ||
| Check if the model is a causal language model or a diffusers pipeline with a MoE block. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model to check. | ||
|
|
||
| Returns | ||
| ------- | ||
| bool | ||
| True if the model is a MoE LM or a transformers pipeline with a MoE block, False otherwise. | ||
| """ | ||
| # Hunyuan3-image is a MoE model, but not depending on mixtral | ||
| if model.__class__.__name__ == "HunyuanImage3ForCausalMM": | ||
| return True | ||
| else: | ||
| return is_moe_lm(model) or is_transformers_pipeline_with_moe_lm(model) | ||
|
|
||
| def _apply(self, model: Any, smash_config: SmashConfigPrefixWrapper) -> Any: | ||
| """ | ||
| Reduce the number of experts per token in the config. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model to reduce the number of experts per token in. | ||
| smash_config : SmashConfigPrefixWrapper | ||
| The configuration for the reduction of the number of experts per token. | ||
|
|
||
| Returns | ||
| ------- | ||
| Any | ||
| The model with the reduced number of experts per token. | ||
| """ | ||
| if is_transformers_pipeline_with_moe_lm(model): | ||
| return self._apply_to_model_within_transformers_pipeline(model, smash_config) | ||
|
|
||
| device_map = get_device_map(model) | ||
| # we need to save and reload with the new config, because immutable object. | ||
| with tempfile.TemporaryDirectory() as temp_dir: | ||
| move_to_device(model, "cpu") | ||
| model.save_pretrained(temp_dir) | ||
| config_path = Path(temp_dir) / "config.json" | ||
| if not config_path.exists(): | ||
| raise FileNotFoundError(f"Config file not found at {config_path}") | ||
| else: | ||
| with config_path.open("r", encoding="utf-8") as f: | ||
| config_json = json.load(f) | ||
| target_name = smash_config["target_name"] | ||
| if target_name not in config_json: | ||
| raise KeyError(f"Target name '{target_name}' not found in config file at {config_path}") | ||
| config_json[target_name] = smash_config["num_experts_per_token"] | ||
| with config_path.open("w", encoding="utf-8") as f: | ||
| json.dump(config_json, f, indent=2) | ||
| safe_memory_cleanup() | ||
| model = AutoModelForCausalLM.from_pretrained(temp_dir, device_map=device_map) | ||
llcnt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return model | ||
llcnt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| from pruna.algorithms.reduce_noe import ReduceNOE | ||
|
|
||
| from .base_tester import AlgorithmTesterBase | ||
|
|
||
|
|
||
| class TestReduceNOE(AlgorithmTesterBase): | ||
| """Test the ReduceNOE algorithm.""" | ||
|
|
||
| models = ["qwen3_next_moe_tiny_random"] | ||
| reject_models = ["sd_tiny_random"] | ||
| allow_pickle_files = False | ||
| algorithm_class = ReduceNOE | ||
| metrics = ["perplexity"] |
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.
Uh oh!
There was an error while loading. Please reload this page.