Lightning-AI / Lightning-AI/pytorch-lightning

Add a `dtype` option for `load_from_checkpoint`

Open
#20,833 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
31.4k
Forks
3.8k
Avg merge
6d 7h
Merged PRs (30d)
6

Description

### Description & Motivation

Hi,
It would be nice to have a `dtype` argument for `load_from_checkpoint` along with the very cool `map_location`. It would allow the user to set the `dtype` automatically via `load_from_checkpoint` without the manual need of doing `.to(dtype)`.

### Pitch

The fix is should be pretty straightforward. Currently we have:
```python
def load_from_checkpoint(
cls,
checkpoint_path: Union[_PATH, IO],
map_location: _MAP_LOCATION_TYPE = None,
hparams_file: Optional[_PATH] = None,
strict: Optional[bool] = None,
**kwargs: Any,
) -> Self:
...
```

It would just get one more argument:
```python
def load_from_checkpoint(
cls,
checkpoint_path: Union[_PATH, IO],
map_location: _MAP_LOCATION_TYPE = None,
type:torch.dtype=None,
hparams_file: Optional[_PATH] = None,
strict: Optional[bool] = None,
**kwargs: Any,
) -> Self:
...
```

Given this actually points to `_load_from_checkpoint` https://github.com/Lightning-AI/pytorch-lightning/blob/3d398240d2f62f2ad05e9eff557d2d5cb44f235c/src/lightning/pytorch/core/saving.py#L53

We can add our extra `dtype` argument here too and can easily change this line https://github.com/Lightning-AI/pytorch-lightning/blob/3d398240d2f62f2ad05e9eff557d2d5cb44f235c/src/lightning/pytorch/core/saving.py#L99

to
```python
return model.to(dtype).to(device)
```

Hope this is taken into consideration :)

@Borda @awaelchli @lantiga

### Alternatives

_No response_

### Additional context

_No response_

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/lightning/pytorch/core/saving.py, especially load_from_checkpoint, _load_from_checkpoint, and the return path around the referenced lines. Trace how map_location and kwargs flow through checkpoint loading, then check the surrounding tests for expected loading behavior. Done means the public and internal loading paths accept dtype and loaded models honor it without breaking existing arguments.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
machine-learning
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
66/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.