Skip to content

feat: use safetensors prefetch api - #48930

Open
McPatate wants to merge 5 commits into
mainfrom
feat/use_safetensors_prefetch_api
Open

McPatate wants to merge 5 commits into
mainfrom
feat/use_safetensors_prefetch_api

Conversation

@McPatate

@McPatate McPatate commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

CPU CI GPU run-slow

GLM 5.2 fp8 on tp=8 on a b200: 1535s -> ~160s

needs safetensors/safetensors#864 to be merged

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Comment thread src/transformers/modeling_utils.py Outdated
and state_dict is None
and checkpoint_files is not None
and checkpoint_files[0].endswith(".safetensors")
and (load_config.hf_quantizer is None or load_config.hf_quantizer.pre_quantized)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure about this @ArthurZucker, is it possible to apply quantisation directly on device?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its own device allocations
the device allocation of the checkpoint shard? The engine of the process?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, quite te contrary most ops are gpu compatible -> faster on device.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok good to know, because the prefetch engine loads directly on device. for now i've disabled it when quantisation is involved, but we need to think of how to make it compatible in that case!

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ty! I don't understand anything from the code / comments, happy to talk about it more.
Users need to know why they'd opt in on this (our out if we default_

Comment on lines +37 to +40
"""The single CUDA device every entry of `device_map` resolves to, or `None`.

One shard handle loads onto one device, so the prefetch path is used only when the whole model lands on
the same CUDA device (also the case for every rank of a tensor-parallel load).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment is a bit obfuscated.
One shard of what? the checkpoint shard? a Rank?

Whole model on the same CUDA device as what? the shard?
Is this for a single device?

class PrefetchedShard:
"""One open shard whose background load starts the first time a tensor of it is materialised.

`copy_full` makes even whole-tensor reads compact copies. The engine allocates a shard in ranges that

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

copy_full makes even whole-tensor reads compact copies.
Sorry not enough context to understand 🍭

Comment on lines +65 to +67
hold many neighbouring tensors and frees a range only when its last view is gone; on a rank that keeps
just a slice of most tensors (tensor parallelism), a zero-copy view of a small replicated tensor would
pin its whole range, so nothing is kept as a view there.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand much.

Pin where? cpu pinned memory?

Comment thread src/transformers/modeling_utils.py Outdated
and state_dict is None
and checkpoint_files is not None
and checkpoint_files[0].endswith(".safetensors")
and (load_config.hf_quantizer is None or load_config.hf_quantizer.pre_quantized)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its own device allocations
the device allocation of the checkpoint shard? The engine of the process?

Comment thread src/transformers/modeling_utils.py Outdated
and state_dict is None
and checkpoint_files is not None
and checkpoint_files[0].endswith(".safetensors")
and (load_config.hf_quantizer is None or load_config.hf_quantizer.pre_quantized)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, quite te contrary most ops are gpu compatible -> faster on device.

Comment thread src/transformers/modeling_utils.py Outdated
Comment on lines +4416 to +4426
and is_prefetch_available()
):
prefetch_device = prefetch_target_device(load_config.device_map)
if prefetch_device is not None:
logger.info(f"Loading safetensors shards with the CUDA prefetch engine on {prefetch_device}")
if load_config.prefetch and prefetch_device is None:
logger.warning(
"prefetch=True was requested but this checkpoint cannot be loaded with safetensors' CUDA "
"prefetch engine (it needs safetensors >= 0.9.0rc1 on Linux, safetensors files and a single "
"CUDA device); loading with the default loader."
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

everything needs to be in the integration / safetensors with a single validate_prefetch called here as a 1 liner

Comment thread src/transformers/modeling_utils.py Resolved
@McPatate
McPatate force-pushed the feat/use_safetensors_prefetch_api branch from 133d6ce to bc2c1c0 Compare September 23, 2026 16:43
@McPatate
McPatate force-pushed the feat/use_safetensors_prefetch_api branch from 4aaa8fb to f4950da Compare September 30, 2026 08:44

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

starting to look good!

else:
_add_unmatched_checkpoint_key(renamed_key, model, loading_info)

prefetches = []

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if no prefetch keep the spawn meterialize in the loop?

]


class FilePrefetch:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typing + hard follow where the intervals are from, offuscated a bit here!

tensor = tensor.to(device=device, dtype=dtype)
return tensor
@dataclass
class TensorLoad:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any thing we can do in the constructor?

shape = list(tensor.shape) if isinstance(tensor, torch.Tensor) else tensor.get_shape()
if renamed_key not in shard_ops: # e.g. built once for all the experts of a stacked param
shard_ops[renamed_key] = DtensorShardOperation(empty_param)
intervals = shard_ops[renamed_key].intervals(shape, tensor_idx)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

intervals are created here yes!

@github-actions

Copy link
Copy Markdown
Contributor

CI recap

Dashboard: View test results in Grafana
Latest run: 36778905613:1
Result: success | Jobs: 16 | Tests: 192,905 | Failures: 0 | Duration: 16h 34m

@qgallouedec

Copy link
Copy Markdown
Member

Re-ran with safetensors 0.9.0rc1. The global tensor cache is gone but two memory issues are still there (and they matter more now that prefetch is on by default):

  • torch.cuda.memory_allocated() reports 0 GB so anything that reads the caching allocator (Trainer memory metrics, OOM checks) sees nothing.
  • After del model; gc.collect(); torch.cuda.empty_cache(), the X GiB is still on the device 30 s later (only gone once the next from_pretrained has run)

@ArthurZucker

Copy link
Copy Markdown
Collaborator

🫠

@ArthurZucker

Copy link
Copy Markdown
Collaborator

@qgallouedec both memory issues are fixed by safetensors/safetensors#902: prefetch now allocates through torch's caching allocator.

Qwen3-32B, 1×H200, device_map="cuda:0", prefetch=True (this PR):

safetensors load (s) memory_allocated (GiB) left 30 s after del + empty_cache (GiB)
0.9.0rc1 3.3 / 3.5 0.0 61.0
#902 3.2 / 3.3 / 3.1 / 4.2 / 4.7 61.0 0.0

GLM-5.2-FP8, 8×H200, tp_plan="auto": 0.9.0rc1 81.2 / 82.5 s, #902 86.6 s. Same memory_allocated (89.9 GiB), and the memory is released after del with both, since TP copies the weights out of safetensors' buffers. With #902, ~17 GiB of freed loading buffers stay in torch's cache until empty_cache().

@qgallouedec

Copy link
Copy Markdown
Member

Nice! confirmed on my side!

Also:

Comment on lines +4452 to +4453
# skipped with prefetch: weights land in GPU memory safetensors allocates itself, outside torch's caching
# allocator, so warming the allocator up would only double memory use

@qgallouedec qgallouedec Nov 5, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with safetensors/safetensors#902, the weights now go through torch's allocator

Suggested change
# skipped with prefetch: weights land in GPU memory safetensors allocates itself, outside torch's caching
# allocator, so warming the allocator up would only double memory use
# skipped with prefetch: safetensors allocates the weights itself, so the warmed-up block would sit unused
# next to them and double peak memory

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.

4 participants