-
Notifications
You must be signed in to change notification settings - Fork 697
Add SafeTensors checkpoint loading support #950
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
Open
ryannichols827
wants to merge
2
commits into
PriorLabs:main
Choose a base branch
from
ryannichols827:add-safetensors-support
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.
+194
−5
Open
Changes from all commits
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| """Convert a TabPFN PyTorch checkpoint to SafeTensors plus sidecar metadata.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import json | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import torch | ||
| from safetensors.torch import save_file | ||
|
|
||
|
|
||
| def _json_safe(value: Any) -> Any: | ||
| """Convert common checkpoint values into JSON-safe values.""" | ||
| if isinstance(value, dict): | ||
| return {str(k): _json_safe(v) for k, v in value.items()} | ||
| if isinstance(value, list): | ||
| return [_json_safe(v) for v in value] | ||
| if isinstance(value, tuple): | ||
| return [_json_safe(v) for v in value] | ||
| if isinstance(value, set): | ||
| return sorted(_json_safe(v) for v in value) | ||
| if isinstance(value, Path): | ||
| return str(value) | ||
| if isinstance(value, torch.dtype): | ||
| return str(value) | ||
| if isinstance(value, torch.device): | ||
| return str(value) | ||
| if value is None or isinstance(value, (str, int, float, bool)): | ||
| return value | ||
|
|
||
| try: | ||
| json.dumps(value) | ||
| return value | ||
| except TypeError: | ||
| return { | ||
| "__unsupported_type__": type(value).__name__, | ||
| "__repr__": repr(value), | ||
| } | ||
|
|
||
|
|
||
| def convert_checkpoint( | ||
| input_checkpoint: Path, | ||
| output_safetensors: Path, | ||
| output_metadata: Path, | ||
| ) -> None: | ||
| """Convert a TabPFN checkpoint into SafeTensors plus JSON metadata.""" | ||
| checkpoint = torch.load(input_checkpoint, map_location="cpu", weights_only=False) | ||
|
|
||
| if not isinstance(checkpoint, dict): | ||
| raise TypeError( | ||
| f"Expected checkpoint to be a dict, got {type(checkpoint).__name__}." | ||
| ) | ||
|
|
||
| state_dict = checkpoint.get("state_dict") | ||
|
|
||
| if not isinstance(state_dict, dict): | ||
| raise ValueError("Checkpoint does not contain a dict-valued 'state_dict'.") | ||
|
|
||
| tensors = {} | ||
|
|
||
| for key, value in state_dict.items(): | ||
| if not isinstance(value, torch.Tensor): | ||
| raise TypeError( | ||
| f"Expected all state_dict values to be tensors. " | ||
| f"Key {key!r} has type {type(value).__name__}." | ||
| ) | ||
| tensors[key] = value.detach().cpu().contiguous() | ||
|
|
||
| metadata = { | ||
| key: _json_safe(value) | ||
| for key, value in checkpoint.items() | ||
| if key != "state_dict" | ||
| } | ||
|
|
||
| output_safetensors.parent.mkdir(parents=True, exist_ok=True) | ||
| output_metadata.parent.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| save_file(tensors, str(output_safetensors)) | ||
|
|
||
| with output_metadata.open("w", encoding="utf-8") as f: | ||
| json.dump(metadata, f, indent=2, sort_keys=True) | ||
|
|
||
| print(f"Saved SafeTensors file: {output_safetensors}") | ||
| print(f"Saved metadata file: {output_metadata}") | ||
| print(f"Tensor count: {len(tensors)}") | ||
| print(f"Metadata keys: {sorted(metadata)}") | ||
|
|
||
|
|
||
| def parse_args() -> argparse.Namespace: | ||
| parser = argparse.ArgumentParser( | ||
| description="Convert a TabPFN .ckpt file to .safetensors plus metadata JSON." | ||
| ) | ||
| parser.add_argument("--input-checkpoint", required=True, type=Path) | ||
| parser.add_argument("--output-safetensors", required=True, type=Path) | ||
| parser.add_argument("--output-metadata", required=True, type=Path) | ||
| return parser.parse_args() | ||
|
|
||
|
|
||
| def main() -> None: | ||
| args = parse_args() | ||
| convert_checkpoint( | ||
| input_checkpoint=args.input_checkpoint, | ||
| output_safetensors=args.output_safetensors, | ||
| output_metadata=args.output_metadata, | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
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,47 @@ | ||
| """Utilities for loading TabPFN checkpoints stored as SafeTensors plus metadata.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from safetensors.torch import load_file | ||
|
|
||
|
|
||
| def _metadata_path_for_safetensors(path: Path) -> Path: | ||
| """Return the expected sidecar metadata path for a SafeTensors checkpoint.""" | ||
| return path.with_suffix(".non_tensor_metadata.json") | ||
|
|
||
|
|
||
| def load_safetensors_checkpoint(path: str | Path) -> dict[str, Any]: | ||
| """Load a TabPFN checkpoint from SafeTensors plus sidecar JSON metadata. | ||
|
|
||
| The SafeTensors file stores tensor values. The sidecar JSON file stores | ||
| non-tensor checkpoint metadata such as architecture name, model config, | ||
| and inference config. | ||
|
|
||
| Args: | ||
| path: Path to the ``.safetensors`` file. | ||
|
|
||
| Returns: | ||
| A checkpoint-like dictionary compatible with TabPFN model loading. | ||
| """ | ||
| safetensors_path = Path(path) | ||
| metadata_path = _metadata_path_for_safetensors(safetensors_path) | ||
|
|
||
| if not metadata_path.exists(): | ||
| raise FileNotFoundError( | ||
| "SafeTensors checkpoint metadata file not found. " | ||
| f"Expected sidecar file: {metadata_path}" | ||
| ) | ||
|
|
||
| tensors = load_file(str(safetensors_path), device="cpu") | ||
|
|
||
| with metadata_path.open("r", encoding="utf-8") as f: | ||
| metadata = json.load(f) | ||
|
|
||
| checkpoint: dict[str, Any] = dict(metadata) | ||
| checkpoint["state_dict"] = tensors | ||
|
|
||
| return checkpoint |
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.
The current caching logic in
_load_checkpoint_cached(which uses_file_identity) only tracks the primary checkpoint file. For SafeTensors checkpoints, this means that if the sidecar.non_tensor_metadata.jsonfile is updated but the.safetensorsfile remains unchanged, the cache will not be invalidated, and stale metadata will be returned from the LRU cache.While
_file_identityis not modified in this PR, its implementation should be updated to include the metadata file's stats when a.safetensorspath is provided to ensure cache consistency for this new loading mechanism.