Skip to content

Commit e7b7ed8

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 c4b630f commit e7b7ed8

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
@@ -229,7 +229,7 @@ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Call
229229
if is_safetensors:
230230
data: gguf.utility.LocalTensor = model_part[name]
231231
if self.lazy:
232-
data_gen = lambda data=data: LazyTorchTensor.from_safetensors_meta(data) # noqa: E731
232+
data_gen = lambda data=data: LazyTorchTensor.from_local_tensor(data) # noqa: E731
233233
else:
234234
dtype = LazyTorchTensor._dtype_str_map[data.dtype]
235235
data_gen = lambda data=data: torch.from_numpy(data.mmap_bytes()).view(dtype).reshape(data.shape) # noqa: E731
@@ -10002,7 +10002,7 @@ def from_safetensors_slice(cls, st_slice: Any) -> Tensor:
1000210002
return cast(torch.Tensor, lazy)
1000310003

1000410004
@classmethod
10005-
def from_safetensors_meta(cls, t: gguf.utility.LocalTensor) -> Tensor:
10005+
def from_local_tensor(cls, t: gguf.utility.LocalTensor) -> Tensor:
1000610006
def load_tensor(tensor: gguf.utility.LocalTensor) -> Tensor:
1000710007
dtype = cls._dtype_str_map[tensor.dtype]
1000810008
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)