Skip to content

Accept torch.device as map_location for safetensors in load_state_dict - #15489

Open
mertkayacs wants to merge 1 commit into
huggingface:mainfrom
mertkayacs:fix/load-state-dict-device
Open

mertkayacs wants to merge 1 commit into
huggingface:mainfrom
mertkayacs:fix/load-state-dict-device

Conversation

@mertkayacs

Copy link
Copy Markdown
Contributor

What does this PR do?

load_state_dict raises an OSError for a valid .safetensors file when map_location is a torch.device. The signature accepts str | torch.device, and the same argument works for .bin files. safetensors.safe_open only takes the device as a string, so torch.device("cpu") is rejected.

The fix converts a torch.device to its string form at the safe_open call. Strings pass through unchanged.

The new test loads a small checkpoint with "cpu" and torch.device("cpu"), with mmap enabled and disabled, and checks the tensor values and metadata.

Fixes #15459

Tests

# without the fix
pytest tests/others/test_utils.py::TestTorchStateDict::test_load_state_dict_safetensors_map_location
OSError: Unable to load weights from checkpoint file ...
2 failed, 2 passed

# with the fix
same command: 4 passed
pytest tests/others/test_utils.py: 37 passed, 1 skipped
ruff check and ruff format --check (0.9.10) on the two changed files: clean

Self-review notes

I ran the self-review rubric over the diff. No blocking issues and no dead code. The change adds no comments or docstrings, and the map_location type was already documented in the signature, so no docs needed updating. Nothing was left unfixed.

Before submitting

Who can review?

@sayakpaul @DN6

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Safetensors checkpoint loading fails with a torch.device map_location

1 participant