test_hashing.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 time
  8. import hashlib
  9. import sys
  10. import os
  11. import gc
  12. import io
  13. import collections
  14. import itertools
  15. import pickle
  16. import random
  17. from decimal import Decimal
  18. import pytest
  19. from joblib.hashing import hash
  20. from joblib.func_inspect import filter_args
  21. from joblib.memory import Memory
  22. from joblib.testing import raises, skipif, fixture, parametrize
  23. from joblib.test.common import np, with_numpy
  24. def unicode(s):
  25. return s
  26. ###############################################################################
  27. # Helper functions for the tests
  28. def time_func(func, *args):
  29. """ Time function func on *args.
  30. """
  31. times = list()
  32. for _ in range(3):
  33. t1 = time.time()
  34. func(*args)
  35. times.append(time.time() - t1)
  36. return min(times)
  37. def relative_time(func1, func2, *args):
  38. """ Return the relative time between func1 and func2 applied on
  39. *args.
  40. """
  41. time_func1 = time_func(func1, *args)
  42. time_func2 = time_func(func2, *args)
  43. relative_diff = 0.5 * (abs(time_func1 - time_func2)
  44. / (time_func1 + time_func2))
  45. return relative_diff
  46. class Klass(object):
  47. def f(self, x):
  48. return x
  49. class KlassWithCachedMethod(object):
  50. def __init__(self, cachedir):
  51. mem = Memory(cachedir=cachedir)
  52. self.f = mem.cache(self.f)
  53. def f(self, x):
  54. return x
  55. ###############################################################################
  56. # Tests
  57. input_list = [1, 2, 1., 2., 1 + 1j, 2. + 1j,
  58. 'a', 'b',
  59. (1,), (1, 1,), [1, ], [1, 1, ],
  60. {1: 1}, {1: 2}, {2: 1},
  61. None,
  62. gc.collect,
  63. [1, ].append,
  64. # Next 2 sets have unorderable elements in python 3.
  65. set(('a', 1)),
  66. set(('a', 1, ('a', 1))),
  67. # Next 2 dicts have unorderable type of keys in python 3.
  68. {'a': 1, 1: 2},
  69. {'a': 1, 1: 2, 'd': {'a': 1}}]
  70. @parametrize('obj1', input_list)
  71. @parametrize('obj2', input_list)
  72. def test_trivial_hash(obj1, obj2):
  73. """Smoke test hash on various types."""
  74. # Check that 2 objects have the same hash only if they are the same.
  75. are_hashes_equal = hash(obj1) == hash(obj2)
  76. are_objs_identical = obj1 is obj2
  77. assert are_hashes_equal == are_objs_identical
  78. def test_hash_methods():
  79. # Check that hashing instance methods works
  80. a = io.StringIO(unicode('a'))
  81. assert hash(a.flush) == hash(a.flush)
  82. a1 = collections.deque(range(10))
  83. a2 = collections.deque(range(9))
  84. assert hash(a1.extend) != hash(a2.extend)
  85. @fixture(scope='function')
  86. @with_numpy
  87. def three_np_arrays():
  88. rnd = np.random.RandomState(0)
  89. arr1 = rnd.random_sample((10, 10))
  90. arr2 = arr1.copy()
  91. arr3 = arr2.copy()
  92. arr3[0] += 1
  93. return arr1, arr2, arr3
  94. def test_hash_numpy_arrays(three_np_arrays):
  95. arr1, arr2, arr3 = three_np_arrays
  96. for obj1, obj2 in itertools.product(three_np_arrays, repeat=2):
  97. are_hashes_equal = hash(obj1) == hash(obj2)
  98. are_arrays_equal = np.all(obj1 == obj2)
  99. assert are_hashes_equal == are_arrays_equal
  100. assert hash(arr1) != hash(arr1.T)
  101. def test_hash_numpy_dict_of_arrays(three_np_arrays):
  102. arr1, arr2, arr3 = three_np_arrays
  103. d1 = {1: arr1, 2: arr2}
  104. d2 = {1: arr2, 2: arr1}
  105. d3 = {1: arr2, 2: arr3}
  106. assert hash(d1) == hash(d2)
  107. assert hash(d1) != hash(d3)
  108. @with_numpy
  109. @parametrize('dtype', ['datetime64[s]', 'timedelta64[D]'])
  110. def test_numpy_datetime_array(dtype):
  111. # memoryview is not supported for some dtypes e.g. datetime64
  112. # see https://github.com/joblib/joblib/issues/188 for more details
  113. a_hash = hash(np.arange(10))
  114. array = np.arange(0, 10, dtype=dtype)
  115. assert hash(array) != a_hash
  116. @with_numpy
  117. def test_hash_numpy_noncontiguous():
  118. a = np.asarray(np.arange(6000).reshape((1000, 2, 3)),
  119. order='F')[:, :1, :]
  120. b = np.ascontiguousarray(a)
  121. assert hash(a) != hash(b)
  122. c = np.asfortranarray(a)
  123. assert hash(a) != hash(c)
  124. @with_numpy
  125. @parametrize('coerce_mmap', [True, False])
  126. def test_hash_memmap(tmpdir, coerce_mmap):
  127. """Check that memmap and arrays hash identically if coerce_mmap is True."""
  128. filename = tmpdir.join('memmap_temp').strpath
  129. try:
  130. m = np.memmap(filename, shape=(10, 10), mode='w+')
  131. a = np.asarray(m)
  132. are_hashes_equal = (hash(a, coerce_mmap=coerce_mmap) ==
  133. hash(m, coerce_mmap=coerce_mmap))
  134. assert are_hashes_equal == coerce_mmap
  135. finally:
  136. if 'm' in locals():
  137. del m
  138. # Force a garbage-collection cycle, to be certain that the
  139. # object is delete, and we don't run in a problem under
  140. # Windows with a file handle still open.
  141. gc.collect()
  142. @with_numpy
  143. @skipif(sys.platform == 'win32', reason='This test is not stable under windows'
  144. ' for some reason')
  145. def test_hash_numpy_performance():
  146. """ Check the performance of hashing numpy arrays:
  147. In [22]: a = np.random.random(1000000)
  148. In [23]: %timeit hashlib.md5(a).hexdigest()
  149. 100 loops, best of 3: 20.7 ms per loop
  150. In [24]: %timeit hashlib.md5(pickle.dumps(a, protocol=2)).hexdigest()
  151. 1 loops, best of 3: 73.1 ms per loop
  152. In [25]: %timeit hashlib.md5(cPickle.dumps(a, protocol=2)).hexdigest()
  153. 10 loops, best of 3: 53.9 ms per loop
  154. In [26]: %timeit hash(a)
  155. 100 loops, best of 3: 20.8 ms per loop
  156. """
  157. rnd = np.random.RandomState(0)
  158. a = rnd.random_sample(1000000)
  159. def md5_hash(x):
  160. return hashlib.md5(memoryview(x)).hexdigest()
  161. relative_diff = relative_time(md5_hash, hash, a)
  162. assert relative_diff < 0.3
  163. # Check that hashing an tuple of 3 arrays takes approximately
  164. # 3 times as much as hashing one array
  165. time_hashlib = 3 * time_func(md5_hash, a)
  166. time_hash = time_func(hash, (a, a, a))
  167. relative_diff = 0.5 * (abs(time_hash - time_hashlib)
  168. / (time_hash + time_hashlib))
  169. assert relative_diff < 0.3
  170. def test_bound_methods_hash():
  171. """ Make sure that calling the same method on two different instances
  172. of the same class does resolve to the same hashes.
  173. """
  174. a = Klass()
  175. b = Klass()
  176. assert (hash(filter_args(a.f, [], (1, ))) ==
  177. hash(filter_args(b.f, [], (1, ))))
  178. def test_bound_cached_methods_hash(tmpdir):
  179. """ Make sure that calling the same _cached_ method on two different
  180. instances of the same class does resolve to the same hashes.
  181. """
  182. a = KlassWithCachedMethod(tmpdir.strpath)
  183. b = KlassWithCachedMethod(tmpdir.strpath)
  184. assert (hash(filter_args(a.f.func, [], (1, ))) ==
  185. hash(filter_args(b.f.func, [], (1, ))))
  186. @with_numpy
  187. def test_hash_object_dtype():
  188. """ Make sure that ndarrays with dtype `object' hash correctly."""
  189. a = np.array([np.arange(i) for i in range(6)], dtype=object)
  190. b = np.array([np.arange(i) for i in range(6)], dtype=object)
  191. assert hash(a) == hash(b)
  192. @with_numpy
  193. def test_numpy_scalar():
  194. # Numpy scalars are built from compiled functions, and lead to
  195. # strange pickling paths explored, that can give hash collisions
  196. a = np.float64(2.0)
  197. b = np.float64(3.0)
  198. assert hash(a) != hash(b)
  199. def test_dict_hash(tmpdir):
  200. # Check that dictionaries hash consistently, eventhough the ordering
  201. # of the keys is not garanteed
  202. k = KlassWithCachedMethod(tmpdir.strpath)
  203. d = {'#s12069__c_maps.nii.gz': [33],
  204. '#s12158__c_maps.nii.gz': [33],
  205. '#s12258__c_maps.nii.gz': [33],
  206. '#s12277__c_maps.nii.gz': [33],
  207. '#s12300__c_maps.nii.gz': [33],
  208. '#s12401__c_maps.nii.gz': [33],
  209. '#s12430__c_maps.nii.gz': [33],
  210. '#s13817__c_maps.nii.gz': [33],
  211. '#s13903__c_maps.nii.gz': [33],
  212. '#s13916__c_maps.nii.gz': [33],
  213. '#s13981__c_maps.nii.gz': [33],
  214. '#s13982__c_maps.nii.gz': [33],
  215. '#s13983__c_maps.nii.gz': [33]}
  216. a = k.f(d)
  217. b = k.f(a)
  218. assert hash(a) == hash(b)
  219. def test_set_hash(tmpdir):
  220. # Check that sets hash consistently, even though their ordering
  221. # is not guaranteed
  222. k = KlassWithCachedMethod(tmpdir.strpath)
  223. s = set(['#s12069__c_maps.nii.gz',
  224. '#s12158__c_maps.nii.gz',
  225. '#s12258__c_maps.nii.gz',
  226. '#s12277__c_maps.nii.gz',
  227. '#s12300__c_maps.nii.gz',
  228. '#s12401__c_maps.nii.gz',
  229. '#s12430__c_maps.nii.gz',
  230. '#s13817__c_maps.nii.gz',
  231. '#s13903__c_maps.nii.gz',
  232. '#s13916__c_maps.nii.gz',
  233. '#s13981__c_maps.nii.gz',
  234. '#s13982__c_maps.nii.gz',
  235. '#s13983__c_maps.nii.gz'])
  236. a = k.f(s)
  237. b = k.f(a)
  238. assert hash(a) == hash(b)
  239. def test_set_decimal_hash():
  240. # Check that sets containing decimals hash consistently, even though
  241. # ordering is not guaranteed
  242. assert (hash(set([Decimal(0), Decimal('NaN')])) ==
  243. hash(set([Decimal('NaN'), Decimal(0)])))
  244. def test_string():
  245. # Test that we obtain the same hash for object owning several strings,
  246. # whatever the past of these strings (which are immutable in Python)
  247. string = 'foo'
  248. a = {string: 'bar'}
  249. b = {string: 'bar'}
  250. c = pickle.loads(pickle.dumps(b))
  251. assert hash([a, b]) == hash([a, c])
  252. @with_numpy
  253. def test_dtype():
  254. # Test that we obtain the same hash for object owning several dtype,
  255. # whatever the past of these dtypes. Catter for cache invalidation with
  256. # complex dtype
  257. a = np.dtype([('f1', np.uint), ('f2', np.int32)])
  258. b = a
  259. c = pickle.loads(pickle.dumps(a))
  260. assert hash([a, c]) == hash([a, b])
  261. @parametrize('to_hash,expected',
  262. [('This is a string to hash',
  263. '71b3f47df22cb19431d85d92d0b230b2'),
  264. (u"C'est l\xe9t\xe9",
  265. '2d8d189e9b2b0b2e384d93c868c0e576'),
  266. ((123456, 54321, -98765),
  267. 'e205227dd82250871fa25aa0ec690aa3'),
  268. ([random.Random(42).random() for _ in range(5)],
  269. 'a11ffad81f9682a7d901e6edc3d16c84'),
  270. ({'abcde': 123, 'sadfas': [-9999, 2, 3]},
  271. 'aeda150553d4bb5c69f0e69d51b0e2ef')])
  272. def test_hashes_stay_the_same(to_hash, expected):
  273. # We want to make sure that hashes don't change with joblib
  274. # version. For end users, that would mean that they have to
  275. # regenerate their cache from scratch, which potentially means
  276. # lengthy recomputations.
  277. # Expected results have been generated with joblib 0.9.2
  278. assert hash(to_hash) == expected
  279. @with_numpy
  280. def test_hashes_are_different_between_c_and_fortran_contiguous_arrays():
  281. # We want to be sure that the c-contiguous and f-contiguous versions of the
  282. # same array produce 2 different hashes.
  283. rng = np.random.RandomState(0)
  284. arr_c = rng.random_sample((10, 10))
  285. arr_f = np.asfortranarray(arr_c)
  286. assert hash(arr_c) != hash(arr_f)
  287. @with_numpy
  288. def test_0d_array():
  289. hash(np.array(0))
  290. @with_numpy
  291. def test_0d_and_1d_array_hashing_is_different():
  292. assert hash(np.array(0)) != hash(np.array([0]))
  293. @with_numpy
  294. def test_hashes_stay_the_same_with_numpy_objects():
  295. # We want to make sure that hashes don't change with joblib
  296. # version. For end users, that would mean that they have to
  297. # regenerate their cache from scratch, which potentially means
  298. # lengthy recomputations.
  299. rng = np.random.RandomState(42)
  300. # Being explicit about dtypes in order to avoid
  301. # architecture-related differences. Also using 'f4' rather than
  302. # 'f8' for float arrays because 'f8' arrays generated by
  303. # rng.random.randn don't seem to be bit-identical on 32bit and
  304. # 64bit machines.
  305. to_hash_list = [
  306. rng.randint(-1000, high=1000, size=50).astype('<i8'),
  307. tuple(rng.randn(3).astype('<f4') for _ in range(5)),
  308. [rng.randn(3).astype('<f4') for _ in range(5)],
  309. {
  310. -3333: rng.randn(3, 5).astype('<f4'),
  311. 0: [
  312. rng.randint(10, size=20).astype('<i8'),
  313. rng.randn(10).astype('<f4')
  314. ]
  315. },
  316. # Non regression cases for https://github.com/joblib/joblib/issues/308.
  317. # Generated with joblib 0.9.4.
  318. np.arange(100, dtype='<i8').reshape((10, 10)),
  319. # Fortran contiguous array
  320. np.asfortranarray(np.arange(100, dtype='<i8').reshape((10, 10))),
  321. # Non contiguous array
  322. np.arange(100, dtype='<i8').reshape((10, 10))[:, :2],
  323. ]
  324. # These expected results have been generated with joblib 0.9.0
  325. expected_hashes = [
  326. '10a6afc379ca2708acfbaef0ab676eab',
  327. '988a7114f337f381393025911ebc823b',
  328. 'c6809f4b97e35f2fa0ee8d653cbd025c',
  329. 'b3ad17348e32728a7eb9cda1e7ede438',
  330. '927b3e6b0b6a037e8e035bda134e0b05',
  331. '108f6ee98e7db19ea2006ffd208f4bf1',
  332. 'bd48ccaaff28e16e6badee81041b7180'
  333. ]
  334. for to_hash, expected in zip(to_hash_list, expected_hashes):
  335. assert hash(to_hash) == expected
  336. def test_hashing_pickling_error():
  337. def non_picklable():
  338. return 42
  339. with raises(pickle.PicklingError) as excinfo:
  340. hash(non_picklable)
  341. excinfo.match('PicklingError while hashing')
  342. def test_wrong_hash_name():
  343. msg = "Valid options for 'hash_name' are"
  344. with raises(ValueError, match=msg):
  345. data = {'foo': 'bar'}
  346. hash(data, hash_name='invalid')