-
Notifications
You must be signed in to change notification settings - Fork 66
[ML] Add quantized model ops to pytorch_inference allowlist #2991
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
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
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 |
|---|---|---|
|
|
@@ -11,13 +11,52 @@ | |
| # | ||
| """Shared utilities for extracting and inspecting TorchScript operations.""" | ||
|
|
||
| import json | ||
| import os | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| import torch | ||
| from transformers import AutoConfig, AutoModel, AutoTokenizer | ||
|
|
||
|
|
||
| def load_model_config(config_path: Path) -> dict[str, dict]: | ||
| """Load a model config JSON file and normalise entries. | ||
|
|
||
| Each entry is either a plain model-name string or a dict with | ||
|
Contributor
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. nit: alternatively we could make the json consistent and drop the normalization all together |
||
| ``model_id`` (required) and optional ``quantized`` boolean. All | ||
| entries are normalised to ``{"model_id": str, "quantized": bool}``. | ||
| Keys starting with ``_comment`` are silently skipped. | ||
|
|
||
| Raises ``ValueError`` for malformed entries so that config problems | ||
| are caught early with an actionable message. | ||
| """ | ||
| with open(config_path) as f: | ||
| raw = json.load(f) | ||
|
|
||
| models: dict[str, dict] = {} | ||
| for key, value in raw.items(): | ||
| if key.startswith("_comment"): | ||
| continue | ||
| if isinstance(value, str): | ||
| models[key] = {"model_id": value, "quantized": False} | ||
| elif isinstance(value, dict): | ||
| if "model_id" not in value: | ||
| raise ValueError( | ||
| f"Config entry {key!r} is a dict but missing required " | ||
| f"'model_id' key: {value!r}") | ||
| models[key] = { | ||
| "model_id": value["model_id"], | ||
| "quantized": value.get("quantized", False), | ||
| } | ||
| else: | ||
| raise ValueError( | ||
| f"Config entry {key!r} has unsupported type " | ||
| f"{type(value).__name__}: {value!r}. " | ||
| f"Expected a model name string or a dict with 'model_id'.") | ||
| return models | ||
|
|
||
|
|
||
| def collect_graph_ops(graph) -> set[str]: | ||
| """Collect all operation names from a TorchScript graph, including blocks.""" | ||
| ops = set() | ||
|
|
@@ -35,9 +74,13 @@ def collect_inlined_ops(module) -> set[str]: | |
| return collect_graph_ops(graph) | ||
|
|
||
|
|
||
| def load_and_trace_hf_model(model_name: str): | ||
| def load_and_trace_hf_model(model_name: str, quantize: bool = False): | ||
| """Load a HuggingFace model, tokenize sample input, and trace to TorchScript. | ||
|
|
||
| When *quantize* is True the model is dynamically quantized (nn.Linear | ||
| layers converted to quantized::linear_dynamic) before tracing. This | ||
| mirrors what Eland does when importing models for Elasticsearch. | ||
|
|
||
| Returns the traced module, or None if the model could not be loaded or traced. | ||
| """ | ||
| token = os.environ.get("HF_TOKEN") | ||
|
|
@@ -53,6 +96,16 @@ def load_and_trace_hf_model(model_name: str): | |
| print(f" LOAD ERROR: {exc}", file=sys.stderr) | ||
| return None | ||
|
|
||
| if quantize: | ||
| try: | ||
| model = torch.quantization.quantize_dynamic( | ||
| model, {torch.nn.Linear}, dtype=torch.qint8) | ||
| print(" Applied dynamic quantization (nn.Linear -> qint8)", | ||
| file=sys.stderr) | ||
| except Exception as exc: | ||
| print(f" QUANTIZE ERROR: {exc}", file=sys.stderr) | ||
| return None | ||
|
|
||
| inputs = tokenizer( | ||
| "This is a sample input for graph extraction.", | ||
| return_tensors="pt", padding="max_length", | ||
|
|
||
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
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: maybe the name
"quantized": true/falseis oversimplified and hides an important nuanceI read this flag as "this model is quantized", while in reality it's "this model has dynamic quantization applied to specific layer types (nn.linear)"
Calling it
dynamic_quantizationwould be a slight improvement - gives a better signal on what this flag controls.Long term, if there is ever a need, we could replace a boolean with: