-
Notifications
You must be signed in to change notification settings - Fork 607
Add proper pt2e calibration #5095
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
10 commits
Select commit
Hold shift + click to select a range
02a2d3c
Add proper pt2e calibration
cccclai bbbd846
distinguish dynamic shape
cccclai c1595bd
remove unnecessary code
cccclai 82c9518
remove unnecessary code
cccclai 638466c
add comments
cccclai ba53b93
Address comments and add template calibration
cccclai e1cbfe6
remove logging
cccclai 85154aa
address comments
cccclai 21d3974
remove cuda
cccclai d4d7cfa
add graph module eval wrapper
cccclai 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 |
---|---|---|
|
@@ -27,6 +27,7 @@ | |
from executorch.exir.passes.sym_shape_eval_pass import ConstraintBasedSymShapeEvalPass | ||
|
||
from executorch.extension.export_util.utils import export_to_edge, save_pte_program | ||
from executorch.extension.llm.tokenizer.utils import get_tokenizer | ||
from torch._export import capture_pre_autograd_graph | ||
from torch.ao.quantization.quantize_pt2e import convert_pt2e, prepare_pt2e | ||
from torch.ao.quantization.quantizer import Quantizer | ||
|
@@ -66,6 +67,11 @@ def __init__( | |
use_kv_cache, | ||
example_inputs, | ||
enable_dynamic_shape: bool = False, | ||
calibration_tasks: Optional[List[str]] = None, | ||
calibration_limit: Optional[int] = None, | ||
calibration_seq_length: Optional[int] = None, | ||
calibration_data: Optional[str] = None, | ||
tokenizer_path: Optional[str] = None, | ||
verbose: bool = False, | ||
metadata: Optional[dict] = None, | ||
dynamic_shapes: Optional[Any] = None, | ||
|
@@ -87,6 +93,11 @@ def __init__( | |
self.output_dir = "." | ||
self.dynamic_shapes = dynamic_shapes | ||
self._saved_pte_filename = None | ||
self.calibration_tasks = calibration_tasks | ||
self.calibration_limit = calibration_limit | ||
self.calibration_seq_length = calibration_seq_length | ||
self.calibration_data = calibration_data | ||
self.tokenizer_path = tokenizer_path | ||
|
||
def set_output_dir(self, output_dir: str) -> "LLMEdgeManager": | ||
""" | ||
|
@@ -167,6 +178,69 @@ def capture_pre_autograd_graph(self) -> "LLMEdgeManager": | |
) | ||
return self | ||
|
||
def pt2e_calibrate( | ||
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. This method should not be part of builder at all. It is meant to produce a model not calibrate. Hence my suggestion was to move the functionality of this method either inside GraphModuleEvalWrapper or soemthing else |
||
self, | ||
prepared_module, | ||
calibration_tasks, | ||
calibration_limit, | ||
calibration_seq_length, | ||
calibration_data, | ||
tokenizer_path, | ||
): | ||
logging.info("Run calibration...") | ||
try: | ||
from executorch.examples.models.llama2.eval_llama_lib import ( | ||
GraphModuleEvalWrapper, | ||
) | ||
from executorch.examples.models.llama2.evaluate import evaluate_model | ||
except ImportError: | ||
raise ImportError( | ||
"Please install the llm eval dependency via examples/models/llama2/install_requirements.sh" | ||
) | ||
|
||
tokenizer = get_tokenizer(tokenizer_path) | ||
|
||
def calibrate_template( | ||
module: torch.fx.GraphModule, tokenizer, prompts: str, max_len: int | ||
): | ||
# TODO: change criteria & support batch inputs if necessary | ||
pos = torch.tensor(0, dtype=torch.int64) | ||
token_list = tokenizer.encode(prompts, bos=True, eos=False) | ||
|
||
with torch.no_grad(): | ||
while token_list[-1] != tokenizer.eos_id and pos < max_len: | ||
logits = module( | ||
torch.full((1, 1), token_list[pos]), | ||
torch.tensor((pos,)), | ||
) | ||
pos += 1 | ||
if pos >= len(token_list): | ||
token_list.append(torch.argmax(logits[:], dim=-1).item()) | ||
|
||
calibrate_template( | ||
module=prepared_module, | ||
tokenizer=tokenizer, | ||
prompts=calibration_data, | ||
max_len=calibration_seq_length, | ||
) | ||
|
||
eval_wrapper = GraphModuleEvalWrapper( | ||
model=prepared_module, | ||
tokenizer=tokenizer, | ||
max_seq_length=calibration_seq_length, | ||
use_kv_cache=self.use_kv_cache, | ||
enable_dynamic_shape=self.enable_dynamic_shape, | ||
) | ||
eval_results = evaluate_model( | ||
eval_wrapper, | ||
calibration_tasks, | ||
calibration_limit, | ||
) | ||
|
||
for task, res in eval_results["results"].items(): | ||
print(f"{task}: {res}") | ||
logging.info("Calibration finish...") | ||
|
||
def pt2e_quantize(self, quantizers: Optional[List[Quantizer]]) -> "LLMEdgeManager": | ||
""" | ||
Quantize the model via pt2e flow and retrieve LLMEdgeManager including the quantized model. | ||
|
@@ -189,8 +263,33 @@ def pt2e_quantize(self, quantizers: Optional[List[Quantizer]]) -> "LLMEdgeManage | |
self.pre_autograd_graph_module is not None | ||
), "Please run capture_pre_autograd_graph first" | ||
m = prepare_pt2e(self.pre_autograd_graph_module, composed_quantizer) | ||
logging.info( | ||
f"Calibrating with tasks: {self.calibration_tasks}, limit: {self.calibration_limit}, calibration_data: {self.calibration_data}, tokenizer_path: {self.tokenizer_path}, seq_length: {self.calibration_seq_length}" | ||
) | ||
# Calibrate | ||
m(*self.example_inputs) | ||
if ( | ||
self.calibration_tasks is not None | ||
and self.calibration_limit is not None | ||
and self.calibration_seq_length is not None | ||
and self.calibration_data is not None | ||
and self.tokenizer_path is not None | ||
): | ||
logging.info( | ||
f"Calibrating with tasks: {self.calibration_tasks}, limit: {self.calibration_limit}, calibration_data: {self.calibration_data}, tokenizer_path: {self.tokenizer_path}, seq_length: {self.calibration_seq_length}" | ||
) | ||
self.pt2e_calibrate( | ||
prepared_module=m, | ||
calibration_tasks=self.calibration_tasks, | ||
calibration_limit=self.calibration_limit, | ||
calibration_seq_length=self.calibration_seq_length, | ||
calibration_data=self.calibration_data, | ||
tokenizer_path=self.tokenizer_path, | ||
) | ||
else: | ||
logging.info( | ||
"No calibration provided, using dummy input to calibrate..." | ||
) | ||
m(*self.example_inputs) | ||
m = convert_pt2e(m) | ||
DuplicateDynamicQuantChainPass()(m) | ||
self.pre_autograd_graph_module = m | ||
|
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.
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.
nit: For future reference, separate out unrelated fixes