Skip to content

Instantly share code, notes, and snippets.

@mogwai
Created March 10, 2024 10:26
Show Gist options
  • Save mogwai/e56871e6744fab99bc2cd9bd09bd89b8 to your computer and use it in GitHub Desktop.
Save mogwai/e56871e6744fab99bc2cd9bd09bd89b8 to your computer and use it in GitHub Desktop.
Hashing torch
import torch
import io
import numpy as np
import hashlib
x = torch.randn(1, 20)
buff = io.BytesIO()
torch.save(x, buff)
buff.seek(0)
out = hashlib.sha256(buff.getvalue()).hexdigest()
print(out)
def sha256(b):
if isinstance(b, (int, list, float)):
b = str(b)
if isinstance(b, torch.Tensor):
b = b.cpu().numpy()
if isinstance(b, np.ndarray):
b = b.tobytes()
if type(b) == str:
b = b.encode()
if type(b) == bytes:
return hashlib.sha256(b).hexdigest()
else:
raise Exception("Not implemented a method to handle {0}".format(type(b)))
print(sha256(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment