test_hashing.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. """
  2. Test the hashing module.
  3. """
  4. # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
  5. # Copyright (c) 2009 Gael Varoquaux
  6. # License: BSD Style, 3 clauses.
  7. import collections
  8. import gc
  9. import hashlib
  10. import io
  11. import itertools
  12. import pickle
  13. import random
  14. import sys
  15. import time
  16. from concurrent.futures import ProcessPoolExecutor
  17. from decimal import Decimal
  18. from joblib.func_inspect import filter_args
  19. from joblib.hashing import hash
  20. from joblib.memory import Memory
  21. from joblib.test.common import np, with_numpy
  22. from joblib.testing import fixture, parametrize, raises, skipif
  23. def unicode(s):
  24. return s
  25. ###############################################################################
  26. # Helper functions for the tests
  27. def time_func(func, *args):
  28. """Time function func on *args."""
  29. times = list()
  30. for _ in range(3):
  31. t1 = time.time()
  32. func(*args)
  33. times.append(time.time() - t1)
  34. return min(times)
  35. def relative_time(func1, func2, *args):
  36. """Return the relative time between func1 and func2 applied on
  37. *args.
  38. """
  39. time_func1 = time_func(func1, *args)
  40. time_func2 = time_func(func2, *args)
  41. relative_diff = 0.5 * (abs(time_func1 - time_func2) / (time_func1 + time_func2))
  42. return relative_diff
  43. class Klass(object):
  44. def f(self, x):
  45. return x
  46. class KlassWithCachedMethod(object):
  47. def __init__(self, cachedir):
  48. mem = Memory(location=cachedir)
  49. self.f = mem.cache(self.f)
  50. def f(self, x):
  51. return x
  52. ###############################################################################
  53. # Tests
  54. input_list = [
  55. 1,
  56. 2,
  57. 1.0,
  58. 2.0,
  59. 1 + 1j,
  60. 2.0 + 1j,
  61. "a",
  62. "b",
  63. (1,),
  64. (
  65. 1,
  66. 1,
  67. ),
  68. [
  69. 1,
  70. ],
  71. [
  72. 1,
  73. 1,
  74. ],
  75. {1: 1},
  76. {1: 2},
  77. {2: 1},
  78. None,
  79. gc.collect,
  80. [
  81. 1,
  82. ].append,
  83. # Next 2 sets have unorderable elements in python 3.
  84. set(("a", 1)),
  85. set(("a", 1, ("a", 1))),
  86. # Next 2 dicts have unorderable type of keys in python 3.
  87. {"a": 1, 1: 2},
  88. {"a": 1, 1: 2, "d": {"a": 1}},
  89. ]
  90. @parametrize("obj1", input_list)
  91. @parametrize("obj2", input_list)
  92. def test_trivial_hash(obj1, obj2):
  93. """Smoke test hash on various types."""
  94. # Check that 2 objects have the same hash only if they are the same.
  95. are_hashes_equal = hash(obj1) == hash(obj2)
  96. are_objs_identical = obj1 is obj2
  97. assert are_hashes_equal == are_objs_identical
  98. def test_hash_methods():
  99. # Check that hashing instance methods works
  100. a = io.StringIO(unicode("a"))
  101. assert hash(a.flush) == hash(a.flush)
  102. a1 = collections.deque(range(10))
  103. a2 = collections.deque(range(9))
  104. assert hash(a1.extend) != hash(a2.extend)
  105. @fixture(scope="function")
  106. @with_numpy
  107. def three_np_arrays():
  108. rnd = np.random.RandomState(0)
  109. arr1 = rnd.random_sample((10, 10))
  110. arr2 = arr1.copy()
  111. arr3 = arr2.copy()
  112. arr3[0] += 1
  113. return arr1, arr2, arr3
  114. def test_hash_numpy_arrays(three_np_arrays):
  115. arr1, arr2, arr3 = three_np_arrays
  116. for obj1, obj2 in itertools.product(three_np_arrays, repeat=2):
  117. are_hashes_equal = hash(obj1) == hash(obj2)
  118. are_arrays_equal = np.all(obj1 == obj2)
  119. assert are_hashes_equal == are_arrays_equal
  120. assert hash(arr1) != hash(arr1.T)
  121. def test_hash_numpy_dict_of_arrays(three_np_arrays):
  122. arr1, arr2, arr3 = three_np_arrays
  123. d1 = {1: arr1, 2: arr2}
  124. d2 = {1: arr2, 2: arr1}
  125. d3 = {1: arr2, 2: arr3}
  126. assert hash(d1) == hash(d2)
  127. assert hash(d1) != hash(d3)
  128. @with_numpy
  129. @parametrize("dtype", ["datetime64[s]", "timedelta64[D]"])
  130. def test_numpy_datetime_array(dtype):
  131. # memoryview is not supported for some dtypes e.g. datetime64
  132. # see https://github.com/joblib/joblib/issues/188 for more details
  133. a_hash = hash(np.arange(10))
  134. array = np.arange(0, 10, dtype=dtype)
  135. assert hash(array) != a_hash
  136. @with_numpy
  137. def test_hash_numpy_noncontiguous():
  138. a = np.asarray(np.arange(6000).reshape((1000, 2, 3)), order="F")[:, :1, :]
  139. b = np.ascontiguousarray(a)
  140. assert hash(a) != hash(b)
  141. c = np.asfortranarray(a)
  142. assert hash(a) != hash(c)
  143. @with_numpy
  144. @parametrize("coerce_mmap", [True, False])
  145. def test_hash_memmap(tmpdir, coerce_mmap):
  146. """Check that memmap and arrays hash identically if coerce_mmap is True."""
  147. filename = tmpdir.join("memmap_temp").strpath
  148. try:
  149. m = np.memmap(filename, shape=(10, 10), mode="w+")
  150. a = np.asarray(m)
  151. are_hashes_equal = hash(a, coerce_mmap=coerce_mmap) == hash(
  152. m, coerce_mmap=coerce_mmap
  153. )
  154. assert are_hashes_equal == coerce_mmap
  155. finally:
  156. if "m" in locals():
  157. del m
  158. # Force a garbage-collection cycle, to be certain that the
  159. # object is delete, and we don't run in a problem under
  160. # Windows with a file handle still open.
  161. gc.collect()
  162. @with_numpy
  163. @skipif(
  164. sys.platform == "win32",
  165. reason="This test is not stable under windows for some reason",
  166. )
  167. def test_hash_numpy_performance():
  168. """Check the performance of hashing numpy arrays:
  169. In [22]: a = np.random.random(1000000)
  170. In [23]: %timeit hashlib.md5(a).hexdigest()
  171. 100 loops, best of 3: 20.7 ms per loop
  172. In [24]: %timeit hashlib.md5(pickle.dumps(a, protocol=2)).hexdigest()
  173. 1 loops, best of 3: 73.1 ms per loop
  174. In [25]: %timeit hashlib.md5(cPickle.dumps(a, protocol=2)).hexdigest()
  175. 10 loops, best of 3: 53.9 ms per loop
  176. In [26]: %timeit hash(a)
  177. 100 loops, best of 3: 20.8 ms per loop
  178. """
  179. rnd = np.random.RandomState(0)
  180. a = rnd.random_sample(1000000)
  181. def md5_hash(x):
  182. return hashlib.md5(memoryview(x)).hexdigest()
  183. relative_diff = relative_time(md5_hash, hash, a)
  184. assert relative_diff < 0.3
  185. # Check that hashing an tuple of 3 arrays takes approximately
  186. # 3 times as much as hashing one array
  187. time_hashlib = 3 * time_func(md5_hash, a)
  188. time_hash = time_func(hash, (a, a, a))
  189. relative_diff = 0.5 * (abs(time_hash - time_hashlib) / (time_hash + time_hashlib))
  190. assert relative_diff < 0.3
  191. def test_bound_methods_hash():
  192. """Make sure that calling the same method on two different instances
  193. of the same class does resolve to the same hashes.
  194. """
  195. a = Klass()
  196. b = Klass()
  197. assert hash(filter_args(a.f, [], (1,))) == hash(filter_args(b.f, [], (1,)))
  198. def test_bound_cached_methods_hash(tmpdir):
  199. """Make sure that calling the same _cached_ method on two different
  200. instances of the same class does resolve to the same hashes.
  201. """
  202. a = KlassWithCachedMethod(tmpdir.strpath)
  203. b = KlassWithCachedMethod(tmpdir.strpath)
  204. assert hash(filter_args(a.f.func, [], (1,))) == hash(
  205. filter_args(b.f.func, [], (1,))
  206. )
  207. @with_numpy
  208. def test_hash_object_dtype():
  209. """Make sure that ndarrays with dtype `object' hash correctly."""
  210. a = np.array([np.arange(i) for i in range(6)], dtype=object)
  211. b = np.array([np.arange(i) for i in range(6)], dtype=object)
  212. assert hash(a) == hash(b)
  213. @with_numpy
  214. def test_numpy_scalar():
  215. # Numpy scalars are built from compiled functions, and lead to
  216. # strange pickling paths explored, that can give hash collisions
  217. a = np.float64(2.0)
  218. b = np.float64(3.0)
  219. assert hash(a) != hash(b)
  220. def test_dict_hash(tmpdir):
  221. # Check that dictionaries hash consistently, even though the ordering
  222. # of the keys is not guaranteed
  223. k = KlassWithCachedMethod(tmpdir.strpath)
  224. d = {
  225. "#s12069__c_maps.nii.gz": [33],
  226. "#s12158__c_maps.nii.gz": [33],
  227. "#s12258__c_maps.nii.gz": [33],
  228. "#s12277__c_maps.nii.gz": [33],
  229. "#s12300__c_maps.nii.gz": [33],
  230. "#s12401__c_maps.nii.gz": [33],
  231. "#s12430__c_maps.nii.gz": [33],
  232. "#s13817__c_maps.nii.gz": [33],
  233. "#s13903__c_maps.nii.gz": [33],
  234. "#s13916__c_maps.nii.gz": [33],
  235. "#s13981__c_maps.nii.gz": [33],
  236. "#s13982__c_maps.nii.gz": [33],
  237. "#s13983__c_maps.nii.gz": [33],
  238. }
  239. a = k.f(d)
  240. b = k.f(a)
  241. assert hash(a) == hash(b)
  242. def test_set_hash(tmpdir):
  243. # Check that sets hash consistently, even though their ordering
  244. # is not guaranteed
  245. k = KlassWithCachedMethod(tmpdir.strpath)
  246. s = set(
  247. [
  248. "#s12069__c_maps.nii.gz",
  249. "#s12158__c_maps.nii.gz",
  250. "#s12258__c_maps.nii.gz",
  251. "#s12277__c_maps.nii.gz",
  252. "#s12300__c_maps.nii.gz",
  253. "#s12401__c_maps.nii.gz",
  254. "#s12430__c_maps.nii.gz",
  255. "#s13817__c_maps.nii.gz",
  256. "#s13903__c_maps.nii.gz",
  257. "#s13916__c_maps.nii.gz",
  258. "#s13981__c_maps.nii.gz",
  259. "#s13982__c_maps.nii.gz",
  260. "#s13983__c_maps.nii.gz",
  261. ]
  262. )
  263. a = k.f(s)
  264. b = k.f(a)
  265. assert hash(a) == hash(b)
  266. def test_set_decimal_hash():
  267. # Check that sets containing decimals hash consistently, even though
  268. # ordering is not guaranteed
  269. assert hash(set([Decimal(0), Decimal("NaN")])) == hash(
  270. set([Decimal("NaN"), Decimal(0)])
  271. )
  272. def test_string():
  273. # Test that we obtain the same hash for object owning several strings,
  274. # whatever the past of these strings (which are immutable in Python)
  275. string = "foo"
  276. a = {string: "bar"}
  277. b = {string: "bar"}
  278. c = pickle.loads(pickle.dumps(b))
  279. assert hash([a, b]) == hash([a, c])
  280. @with_numpy
  281. def test_numpy_dtype_pickling():
  282. # numpy dtype hashing is tricky to get right: see #231, #239, #251 #1080,
  283. # #1082, and explanatory comments inside
  284. # ``joblib.hashing.NumpyHasher.save``.
  285. # In this test, we make sure that the pickling of numpy dtypes is robust to
  286. # object identity and object copy.
  287. dt1 = np.dtype("f4")
  288. dt2 = np.dtype("f4")
  289. # simple dtypes objects are interned
  290. assert dt1 is dt2
  291. assert hash(dt1) == hash(dt2)
  292. dt1_roundtripped = pickle.loads(pickle.dumps(dt1))
  293. assert dt1 is not dt1_roundtripped
  294. assert hash(dt1) == hash(dt1_roundtripped)
  295. assert hash([dt1, dt1]) == hash([dt1_roundtripped, dt1_roundtripped])
  296. assert hash([dt1, dt1]) == hash([dt1, dt1_roundtripped])
  297. complex_dt1 = np.dtype([("name", np.str_, 16), ("grades", np.float64, (2,))])
  298. complex_dt2 = np.dtype([("name", np.str_, 16), ("grades", np.float64, (2,))])
  299. # complex dtypes objects are not interned
  300. assert hash(complex_dt1) == hash(complex_dt2)
  301. complex_dt1_roundtripped = pickle.loads(pickle.dumps(complex_dt1))
  302. assert complex_dt1_roundtripped is not complex_dt1
  303. assert hash(complex_dt1) == hash(complex_dt1_roundtripped)
  304. assert hash([complex_dt1, complex_dt1]) == hash(
  305. [complex_dt1_roundtripped, complex_dt1_roundtripped]
  306. )
  307. assert hash([complex_dt1, complex_dt1]) == hash(
  308. [complex_dt1_roundtripped, complex_dt1]
  309. )
  310. @parametrize(
  311. "to_hash,expected",
  312. [
  313. ("This is a string to hash", "71b3f47df22cb19431d85d92d0b230b2"),
  314. ("C'est l\xe9t\xe9", "2d8d189e9b2b0b2e384d93c868c0e576"),
  315. ((123456, 54321, -98765), "e205227dd82250871fa25aa0ec690aa3"),
  316. (
  317. [random.Random(42).random() for _ in range(5)],
  318. "a11ffad81f9682a7d901e6edc3d16c84",
  319. ),
  320. ({"abcde": 123, "sadfas": [-9999, 2, 3]}, "aeda150553d4bb5c69f0e69d51b0e2ef"),
  321. ],
  322. )
  323. def test_hashes_stay_the_same(to_hash, expected):
  324. # We want to make sure that hashes don't change with joblib
  325. # version. For end users, that would mean that they have to
  326. # regenerate their cache from scratch, which potentially means
  327. # lengthy recomputations.
  328. # Expected results have been generated with joblib 0.9.2
  329. assert hash(to_hash) == expected
  330. @with_numpy
  331. def test_hashes_are_different_between_c_and_fortran_contiguous_arrays():
  332. # We want to be sure that the c-contiguous and f-contiguous versions of the
  333. # same array produce 2 different hashes.
  334. rng = np.random.RandomState(0)
  335. arr_c = rng.random_sample((10, 10))
  336. arr_f = np.asfortranarray(arr_c)
  337. assert hash(arr_c) != hash(arr_f)
  338. @with_numpy
  339. def test_0d_array():
  340. hash(np.array(0))
  341. @with_numpy
  342. def test_0d_and_1d_array_hashing_is_different():
  343. assert hash(np.array(0)) != hash(np.array([0]))
  344. @with_numpy
  345. def test_hashes_stay_the_same_with_numpy_objects():
  346. # Note: joblib used to test numpy objects hashing by comparing the produced
  347. # hash of an object with some hard-coded target value to guarantee that
  348. # hashing remains the same across joblib versions. However, since numpy
  349. # 1.20 and joblib 1.0, joblib relies on potentially unstable implementation
  350. # details of numpy to hash np.dtype objects, which makes the stability of
  351. # hash values across different environments hard to guarantee and to test.
  352. # As a result, hashing stability across joblib versions becomes best-effort
  353. # only, and we only test the consistency within a single environment by
  354. # making sure:
  355. # - the hash of two copies of the same objects is the same
  356. # - hashing some object in two different python processes produces the same
  357. # value. This should be viewed as a proxy for testing hash consistency
  358. # through time between Python sessions (provided no change in the
  359. # environment was done between sessions).
  360. def create_objects_to_hash():
  361. rng = np.random.RandomState(42)
  362. # Being explicit about dtypes in order to avoid
  363. # architecture-related differences. Also using 'f4' rather than
  364. # 'f8' for float arrays because 'f8' arrays generated by
  365. # rng.random.randn don't seem to be bit-identical on 32bit and
  366. # 64bit machines.
  367. to_hash_list = [
  368. rng.randint(-1000, high=1000, size=50).astype("<i8"),
  369. tuple(rng.randn(3).astype("<f4") for _ in range(5)),
  370. [rng.randn(3).astype("<f4") for _ in range(5)],
  371. {
  372. -3333: rng.randn(3, 5).astype("<f4"),
  373. 0: [
  374. rng.randint(10, size=20).astype("<i8"),
  375. rng.randn(10).astype("<f4"),
  376. ],
  377. },
  378. # Non regression cases for
  379. # https://github.com/joblib/joblib/issues/308
  380. np.arange(100, dtype="<i8").reshape((10, 10)),
  381. # Fortran contiguous array
  382. np.asfortranarray(np.arange(100, dtype="<i8").reshape((10, 10))),
  383. # Non contiguous array
  384. np.arange(100, dtype="<i8").reshape((10, 10))[:, :2],
  385. ]
  386. return to_hash_list
  387. # Create two lists containing copies of the same objects. joblib.hash
  388. # should return the same hash for to_hash_list_one[i] and
  389. # to_hash_list_two[i]
  390. to_hash_list_one = create_objects_to_hash()
  391. to_hash_list_two = create_objects_to_hash()
  392. e1 = ProcessPoolExecutor(max_workers=1)
  393. e2 = ProcessPoolExecutor(max_workers=1)
  394. try:
  395. for obj_1, obj_2 in zip(to_hash_list_one, to_hash_list_two):
  396. # testing consistency of hashes across python processes
  397. hash_1 = e1.submit(hash, obj_1).result()
  398. hash_2 = e2.submit(hash, obj_1).result()
  399. assert hash_1 == hash_2
  400. # testing consistency when hashing two copies of the same objects.
  401. hash_3 = e1.submit(hash, obj_2).result()
  402. assert hash_1 == hash_3
  403. finally:
  404. e1.shutdown()
  405. e2.shutdown()
  406. def test_hashing_pickling_error():
  407. def non_picklable():
  408. return 42
  409. with raises(pickle.PicklingError) as excinfo:
  410. hash(non_picklable)
  411. excinfo.match("PicklingError while hashing")
  412. def test_wrong_hash_name():
  413. msg = "Valid options for 'hash_name' are"
  414. with raises(ValueError, match=msg):
  415. data = {"foo": "bar"}
  416. hash(data, hash_name="invalid")