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.

persistent_cache.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import argparse
  10. import getpass
  11. import json
  12. import os
  13. import shelve
  14. from ..core._imperative_rt import PersistentCache as _PersistentCache
  15. from ..logger import get_logger
  16. from ..version import __version__, git_version
  17. class _FakeRedisConn:
  18. _cache_dir = None
  19. _is_shelve = False
  20. _dict = {}
  21. def __init__(self):
  22. if os.getenv("MGE_FASTRUN_CACHE_TYPE") == "MEMORY":
  23. self._dict = {}
  24. self._is_shelve = False
  25. get_logger().info("fastrun use in-memory cache")
  26. else:
  27. try:
  28. self._cache_dir = os.getenv("MGE_FASTRUN_CACHE_DIR")
  29. if not self._cache_dir:
  30. from ..hub.hub import _get_megengine_home
  31. self._cache_dir = os.path.expanduser(
  32. os.path.join(_get_megengine_home(), "persistent_cache")
  33. )
  34. os.makedirs(self._cache_dir, exist_ok=True)
  35. cache_file = os.path.join(self._cache_dir, "cache")
  36. self._dict = shelve.open(cache_file)
  37. self._is_shelve = True
  38. get_logger().info(
  39. "fastrun use in-file cache in {}".format(self._cache_dir)
  40. )
  41. except Exception as exc:
  42. self._dict = {}
  43. self._is_shelve = False
  44. get_logger().error(
  45. "failed to create cache file in {} {!r}; fallback to "
  46. "in-memory cache".format(self._cache_dir, exc)
  47. )
  48. def get(self, key):
  49. if self._is_shelve and isinstance(key, bytes):
  50. key = key.decode("utf-8")
  51. return self._dict.get(key)
  52. def set(self, key, val):
  53. if self._is_shelve and isinstance(key, bytes):
  54. key = key.decode("utf-8")
  55. self._dict[key] = val
  56. def clear(self):
  57. print("{} cache item deleted in {}".format(len(self._dict), self._cache_dir))
  58. self._dict.clear()
  59. def __del__(self):
  60. if self._is_shelve:
  61. self._dict.close()
  62. class PersistentCacheOnServer(_PersistentCache):
  63. _cached_conn = None
  64. _prefix = None
  65. _prev_get_refkeep = None
  66. @property
  67. def _conn(self):
  68. """get redis connection"""
  69. if self._cached_conn is None:
  70. self._cached_conn = _FakeRedisConn()
  71. self._prefix = self.make_user_prefix()
  72. return self._cached_conn
  73. @classmethod
  74. def make_user_prefix(cls):
  75. return "mgbcache:{}".format(getpass.getuser())
  76. def _make_key(self, category, key):
  77. prefix_with_version = "{}:MGB{}:GIT:{}".format(
  78. self._prefix, __version__, git_version
  79. )
  80. return b"@".join(
  81. (prefix_with_version.encode("ascii"), category.encode("ascii"), key)
  82. )
  83. def put(self, category, key, value):
  84. conn = self._conn
  85. key = self._make_key(category, key)
  86. conn.set(key, value)
  87. def get(self, category, key):
  88. conn = self._conn
  89. key = self._make_key(category, key)
  90. self._prev_get_refkeep = conn.get(key)
  91. return self._prev_get_refkeep
  92. def clean(self):
  93. conn = self._conn
  94. if isinstance(conn, _FakeRedisConn):
  95. conn.clear()