Skip to content

Commit 0edc189

Browse files
committed
gguf-py : order safetensors tensors by name
Applies to both local and remote safetensors custom parsing. This matches the behavior of the official safetensors implementation. * convert : rename from_safetensors_meta to from_local_tensor For consistency with from_remote_tensor
1 parent ca8f736 commit 0edc189

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

convert_hf_to_gguf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Call
206206
if is_safetensors:
207207
data: gguf.utility.LocalTensor = model_part[name]
208208
if self.lazy:
209-
data_gen = lambda data=data: LazyTorchTensor.from_safetensors_meta(data) # noqa: E731
209+
data_gen = lambda data=data: LazyTorchTensor.from_local_tensor(data) # noqa: E731
210210
else:
211211
dtype = LazyTorchTensor._dtype_str_map[data.dtype]
212212
data_gen = lambda data=data: torch.from_numpy(data.mmap_bytes()).view(dtype).reshape(data.shape) # noqa: E731
@@ -8860,7 +8860,7 @@ def from_safetensors_slice(cls, st_slice: Any) -> Tensor:
88608860
return cast(torch.Tensor, lazy)
88618861

88628862
@classmethod
8863-
def from_safetensors_meta(cls, t: gguf.utility.LocalTensor) -> Tensor:
8863+
def from_local_tensor(cls, t: gguf.utility.LocalTensor) -> Tensor:
88648864
def load_tensor(tensor: gguf.utility.LocalTensor) -> Tensor:
88658865
dtype = cls._dtype_str_map[tensor.dtype]
88668866
return torch.from_numpy(tensor.mmap_bytes()).view(dtype).reshape(tensor.shape)

gguf-py/gguf/utility.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ def get_list_tensors(cls, url: str) -> dict[str, RemoteTensor]:
179179
except KeyError as e:
180180
raise ValueError(f"Missing key in metadata for tensor '{name}': {e}, meta = {meta}")
181181

182+
# order by name (same as default safetensors behavior)
183+
# ref: https://github.com/huggingface/safetensors/blob/0816a1ae1d6b731cefd67f061d80d1cadd0dd7bb/bindings/python/src/lib.rs#L606
184+
res = dict(sorted(res.items(), key=lambda t: t[0]))
185+
182186
return res
183187

184188
@classmethod
@@ -332,8 +336,9 @@ def __init__(self, filename: Path):
332336
),
333337
)
334338

335-
# order by offset
336-
self.tensors = dict(sorted(tensors.items(), key=lambda t: t[1].data_range.offset))
339+
# order by name (same as default safetensors behavior)
340+
# ref: https://github.com/huggingface/safetensors/blob/0816a1ae1d6b731cefd67f061d80d1cadd0dd7bb/bindings/python/src/lib.rs#L606
341+
self.tensors = dict(sorted(tensors.items(), key=lambda t: t[0]))
337342

338343
def __enter__(self, *args, **kwargs):
339344
del args, kwargs # unused

0 commit comments

Comments
 (0)