Repository navigation
feat: add pt-snap import to ingest PyTorch memory snapshot pickles via MemSnapDump #66
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
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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
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,119 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import pickle | ||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from pt_snap_cli.core.errors import ( | ||
| ImportExecutionError, | ||
| ImportToolMissingError, | ||
| SnapshotFileInvalidError, | ||
| ) | ||
| from pt_snap_cli.core.models import ImportOptions, ImportResult | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pt_snap_cli.core.focus_service import FocusService | ||
|
|
||
| VALID_SUFFIXES = {".pkl", ".pickle"} | ||
|
|
||
| try: | ||
| from memsnapdump.tools.adaptors.snapshot2db import ( # pyright: ignore[reportMissingImports] | ||
| run_dump_to_db as _upstream_run_dump_to_db, | ||
| ) | ||
| except ImportError: | ||
| _upstream_run_dump_to_db: Any = None | ||
|
|
||
|
|
||
| class ImportService: | ||
| """Import PyTorch snapshot pickle files through the source-integrated MemSnapDump API. | ||
|
|
||
| The upstream tool is imported lazily at module load so this package can still be | ||
| imported without the optional dependency. All upstream execution goes through a | ||
| single private call point for testability. There is intentionally no subprocess | ||
| fallback because this PR integrates against MemSnapDump source directly, not a | ||
| published PyPI command contract. | ||
| """ | ||
|
|
||
| def __init__(self, focus_service: FocusService | None = None) -> None: | ||
| self._focus_service = focus_service | ||
|
|
||
| def import_snapshot(self, options: ImportOptions) -> ImportResult: | ||
| self._validate_snapshot_file(options.snapshot_file) | ||
| output_dir = self._resolve_output_dir(options.snapshot_file, options.output_dir) | ||
|
|
||
| if _upstream_run_dump_to_db is None: | ||
| raise ImportToolMissingError( | ||
| "memsnapdump package is required; install with pip install -e .[memsnapdump] " | ||
| "(or pip install /tmp/MemSnapDump)" | ||
| ) | ||
|
|
||
| try: | ||
| self._run_dump_to_db( | ||
| snapshot_file=str(options.snapshot_file), | ||
| dump_dir=str(output_dir), | ||
| device=options.device, | ||
| ) | ||
| except TypeError as exc: | ||
| # Monkeypatched / misconfigured call point -> treat as missing tool. | ||
| if "NoneType" in str(exc) and "not callable" in str(exc): | ||
| raise ImportToolMissingError( | ||
| "memsnapdump call point is unavailable; install with " | ||
| "pip install -e .[memsnapdump]" | ||
| ) from exc | ||
| raise ImportExecutionError(f"memsnapdump run_dump_to_db failed: {exc}") from exc | ||
| except Exception as exc: | ||
| raise ImportExecutionError(f"memsnapdump run_dump_to_db failed: {exc}") from exc | ||
|
|
||
| db_path = output_dir / (options.snapshot_file.name + ".db") | ||
| if not db_path.is_file(): | ||
| raise ImportExecutionError(f"Expected database not produced: {db_path}") | ||
|
|
||
| focus_state = None | ||
| if options.set_focus: | ||
| if self._focus_service is None: | ||
| from pt_snap_cli.core.focus_service import FocusService | ||
|
|
||
| self._focus_service = FocusService() | ||
| focus_state = self._focus_service.set_project_focus( | ||
| db_path=db_path, | ||
| device_id=options.device, | ||
| base_dir=output_dir, | ||
|
Owner
Author
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. 这里把 |
||
| ) | ||
|
|
||
| return ImportResult(db_path=db_path, device_id=options.device, focus_state=focus_state) | ||
|
|
||
| def _run_dump_to_db( | ||
| self, | ||
| snapshot_file: str, | ||
| dump_dir: str, | ||
| device: int | None, | ||
| ) -> bool: | ||
| kwargs: dict[str, Any] = {"snapshot_file": snapshot_file, "dump_dir": dump_dir} | ||
| if device is not None: | ||
| kwargs["device"] = device | ||
| assert _upstream_run_dump_to_db is not None # checked by import_snapshot | ||
| return _upstream_run_dump_to_db(**kwargs) | ||
|
|
||
| @staticmethod | ||
| def _validate_snapshot_file(path: Path) -> None: | ||
| if not path.exists(): | ||
| raise SnapshotFileInvalidError(f"Snapshot file does not exist: {path}") | ||
| if not path.is_file(): | ||
| raise SnapshotFileInvalidError(f"Snapshot path is not a file: {path}") | ||
| if path.suffix.lower() not in VALID_SUFFIXES: | ||
| raise SnapshotFileInvalidError( | ||
| f"Snapshot suffix must be .pkl or .pickle, got {path.suffix!r}" | ||
| ) | ||
| try: | ||
| with path.open("rb") as file: | ||
| obj = pickle.load(file) | ||
| except Exception as exc: | ||
| raise SnapshotFileInvalidError(f"Cannot unpickle snapshot file: {exc}") from exc | ||
| if not isinstance(obj, dict): | ||
| raise SnapshotFileInvalidError( | ||
| f"Snapshot top-level must be a dict, got {type(obj).__name__}" | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _resolve_output_dir(snapshot_file: Path, output_dir: Path | None) -> Path: | ||
| return output_dir.resolve() if output_dir is not None else snapshot_file.resolve().parent | ||
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
Empty file.
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,18 @@ | ||
| from pt_snap_cli.core import ( | ||
| ImportExecutionError, | ||
| ImportToolMissingError, | ||
| PtSnapCoreError, | ||
| SnapshotFileInvalidError, | ||
| ) | ||
|
|
||
|
|
||
| def test_import_tool_missing_error_is_pt_snap_core(): | ||
| assert issubclass(ImportToolMissingError, PtSnapCoreError) | ||
|
|
||
|
|
||
| def test_snapshot_file_invalid_error_is_pt_snap_core(): | ||
| assert issubclass(SnapshotFileInvalidError, PtSnapCoreError) | ||
|
|
||
|
|
||
| def test_import_execution_error_is_pt_snap_core(): | ||
| assert issubclass(ImportExecutionError, PtSnapCoreError) |
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.
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.
这里用的是
@master,但 PR 描述和文档里写的是@main。如果上游默认分支已经是main,这个 optional dependency 会直接安装失败。建议统一pyproject.toml、文档和 PR 描述中的分支名。