You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cache.py 3.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import pickle
  2. import os
  3. import os.path as osp
  4. from typing import Callable, Generic, TypeVar
  5. from .logger import print_log, ABLLogger
  6. K = TypeVar("K")
  7. T = TypeVar("T")
  8. PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
  9. class Cache(Generic[K, T]):
  10. def __init__(self, func: Callable[[K], T]):
  11. """Create cache
  12. :param func: Function this cache evaluates
  13. :param cache: If true, do in memory caching.
  14. :param cache_root: If not None, cache to files at the provided path.
  15. :param key_func: Convert the key into a hashable object if needed
  16. """
  17. self.func = func
  18. self.has_init = False
  19. def __getitem__(self, obj, *args) -> T:
  20. return self.get_from_dict(obj, *args)
  21. def clear_cache(self):
  22. """Invalidate entire cache."""
  23. self.cache_dict.clear()
  24. def _init_cache(self, obj):
  25. if self.has_init:
  26. return
  27. self.cache = True
  28. self.cache_dict = dict()
  29. self.key_func = obj.key_func
  30. self.max_size = obj.max_cache_size
  31. self.hits, self.misses = 0, 0
  32. self.full = False
  33. self.root = [] # root of the circular doubly linked list
  34. self.root[:] = [self.root, self.root, None, None]
  35. self.has_init = True
  36. def get_from_dict(self, obj, *args) -> T:
  37. """Implements dict based cache."""
  38. pred_pseudo_label, y, *res_args = args
  39. cache_key = (self.key_func(pred_pseudo_label), self.key_func(y), *res_args)
  40. link = self.cache_dict.get(cache_key)
  41. if link is not None:
  42. # Move the link to the front of the circular queue
  43. link_prev, link_next, _key, result = link
  44. link_prev[NEXT] = link_next
  45. link_next[PREV] = link_prev
  46. last = self.root[PREV]
  47. last[NEXT] = self.root[PREV] = link
  48. link[PREV] = last
  49. link[NEXT] = self.root
  50. self.hits += 1
  51. return result
  52. self.misses += 1
  53. result = self.func(obj, *args)
  54. if self.full:
  55. # Use the old root to store the new key and result.
  56. oldroot = self.root
  57. oldroot[KEY] = cache_key
  58. oldroot[RESULT] = result
  59. # Empty the oldest link and make it the new root.
  60. self.root = oldroot[NEXT]
  61. oldkey = self.root[KEY]
  62. oldresult = self.root[RESULT]
  63. self.root[KEY] = self.root[RESULT] = None
  64. # Now update the cache dictionary.
  65. del self.cache_dict[oldkey]
  66. self.cache_dict[cache_key] = oldroot
  67. else:
  68. # Put result in a new link at the front of the queue.
  69. last = self.root[PREV]
  70. link = [last, self.root, cache_key, result]
  71. last[NEXT] = self.root[PREV] = self.cache_dict[cache_key] = link
  72. if isinstance(self.max_size, int):
  73. self.full = len(self.cache_dict) >= self.max_size
  74. return result
  75. def abl_cache():
  76. def decorator(func):
  77. cache_instance = Cache(func)
  78. def wrapper(obj, *args):
  79. if obj.use_cache:
  80. cache_instance._init_cache(obj)
  81. return cache_instance.get_from_dict(obj, *args)
  82. else:
  83. return func(obj, *args)
  84. return wrapper
  85. return decorator

An efficient Python toolkit for Abductive Learning (ABL), a novel paradigm that integrates machine learning and logical reasoning in a unified framework.