-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
47420a3
commit 906ee17
Showing
7 changed files
with
219 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import tempfile | ||
|
||
with tempfile.TemporaryDirectory() as tmpdirname: | ||
print(type(tmpdirname)) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
# Copyright 2022 The JAX Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import logging | ||
import os | ||
import tensorflow as tf | ||
from typing import Optional | ||
|
||
from filelock import FileLock | ||
|
||
from jax._src.compilation_cache_interface import CacheInterface | ||
from jax._src.gfile_cache import GFileCacheImpl | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def is_path_gs(path: str) -> bool: | ||
return path.startswith("gs://") | ||
|
||
|
||
def get_size(path: str) -> int: | ||
return tf.io.gfile.stat(path).length | ||
|
||
|
||
def get_mtime(path: str) -> int: | ||
return tf.io.gfile.stat(path).mtime_nsec | ||
|
||
|
||
def update_mtime(path: str) -> None: | ||
if not is_path_gs(path): | ||
os.utime(path) # set mtime (and also atime) to current time | ||
else: | ||
tmp_path = f"{path}.tmp" | ||
tf.io.gfile.rename(path, tmp_path) | ||
tf.io.gfile.rename(tmp_path, path) | ||
|
||
|
||
class LRUCacheImpl: | ||
|
||
def __init__(self, cache_dir: str, max_cache_size: int, timeout=10): | ||
self.cache_dir = cache_dir | ||
self.max_cache_size = max_cache_size | ||
os.makedirs(cache_dir, exist_ok=True) | ||
self.timeout = timeout | ||
|
||
self.lock_file = os.path.join(self.cache_dir, ".lockfile") | ||
self.lock = FileLock(self.lock_file) | ||
|
||
def get(self, key: str) -> Optional[bytes]: | ||
with self.lock.acquire(timeout=self.timeout): | ||
file_path = os.path.join(self.cache_dir, key) | ||
|
||
if not os.path.exists(file_path): | ||
logger.debug("Cache miss") | ||
return None | ||
|
||
logger.debug("Cache hit") | ||
update_mtime(file_path) | ||
with open(file_path, "rb") as f: | ||
return f.read() | ||
|
||
def put(self, key: str, val: bytes) -> None: | ||
with self.lock.acquire(timeout=self.timeout): | ||
file_path = os.path.join(self.cache_dir, key) | ||
if os.path.exists(file_path): | ||
return | ||
|
||
self._evict_if_needed() | ||
with open(file_path, "wb") as f: | ||
f.write(val) | ||
update_mtime(file_path) | ||
|
||
def _evict_if_needed(self) -> None: | ||
if self.max_cache_size == -1: | ||
return # max_cache_size == -1: no limit on cache size | ||
|
||
files = os.listdir(self.cache_dir) | ||
|
||
mtime_path_sizes = [] | ||
cache_dir_size = 0 | ||
for filename in files: | ||
file_path = os.path.join(self.cache_dir, filename) | ||
|
||
file_size = get_size(file_path) | ||
file_mtime = get_mtime(file_path) | ||
|
||
cache_dir_size += file_size | ||
mtime_path_sizes.append((file_mtime, file_path, file_size)) | ||
|
||
# sort by mtime, descending | ||
mtime_path_sizes.sort(key=lambda xyz: xyz[0], reverse=True) | ||
|
||
while cache_dir_size >= self.max_cache_size: | ||
file_mtime, file_path, file_size = mtime_path_sizes[-1] | ||
os.remove(file_path) | ||
cache_dir_size -= file_size | ||
mtime_path_sizes.pop() | ||
|
||
class LRUCache(CacheInterface): | ||
|
||
def __init__(self, path: str): | ||
"""Sets up a cache at `path`. Cached values may already be present.""" | ||
if is_path_gs(path): | ||
# gs:// does not support cache eviction yet | ||
self.cache = GFileCacheImpl(path=path) | ||
else: | ||
self.cache = LRUCacheImpl(cache_dir=path, max_cache_size=1000000) | ||
|
||
def get(self, key: str) -> Optional[bytes]: | ||
"""Returns None if `key` isn't present.""" | ||
return self.cache.get(key) | ||
|
||
def put(self, key: str, value: bytes) -> None: | ||
"""Adds new cache entry.""" | ||
self.cache.put(key, value) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import jax | ||
from jax import Array | ||
import jax.numpy as jnp | ||
|
||
jax.config.update('jax_compilation_cache_dir', '/home/ayx/DevInternal/jax/cache_dir') | ||
jax.config.update('jax_raise_persistent_cache_errors', True) | ||
jax.config.update('jax_persistent_cache_min_entry_size_bytes', 1) | ||
jax.config.update('jax_persistent_cache_min_compile_time_secs', 0.0000000000001) | ||
|
||
@jax.jit | ||
def f(a: Array, b: Array, c: Array, d: Array) -> Array: | ||
q_a, r_a = jnp.linalg.qr(a) | ||
q_b, r_b = jnp.linalg.qr(b) | ||
q_c, r_c = jnp.linalg.qr(c) | ||
q_d, r_d = jnp.linalg.qr(d) | ||
return q_a + q_b + q_c + q_d + r_a + r_b + r_c - r_d | ||
|
||
@jax.jit | ||
def f2(a: Array): | ||
return a + 1 | ||
|
||
SIZE = 8000 | ||
|
||
a = jnp.zeros((SIZE, SIZE)) | ||
b = jnp.zeros((SIZE, SIZE)) | ||
c = jnp.zeros((SIZE, SIZE)) | ||
d = jnp.zeros((SIZE, SIZE)) | ||
|
||
f(a, b, c, d) | ||
f2(a) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# Copyright 2021 The JAX Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import random | ||
import string | ||
import tempfile | ||
|
||
from absl.testing import absltest | ||
|
||
from jax._src.lru_cache import LRUCacheImpl | ||
import jax._src.test_util as jtu | ||
|
||
|
||
class LRUCacheTest(jtu.JaxTestCase): | ||
|
||
def test_cache_eviction(self): | ||
def generate_random_k(): | ||
# simulate keys with many collisions | ||
return random.choice(string.ascii_lowercase[:12]) | ||
|
||
def generate_random_v(k): | ||
# simulate large values while ensures that one k corresponds to one v | ||
return bytes(f"{k}abcdefghijklmnopqrstuvwxyz" * 8192, encoding="utf-8") | ||
|
||
with tempfile.TemporaryDirectory() as tmpdirname: | ||
cache = LRUCacheImpl(tmpdirname, 884700) | ||
|
||
for _ in range(100000): | ||
k = generate_random_k() | ||
|
||
if cache.get(k) is not None: | ||
pass # cache hit | ||
else: | ||
v = generate_random_v(k) | ||
cache.put(k, v) | ||
|
||
|
||
if __name__ == "__main__": | ||
absltest.main(testLoader=jtu.JaxTestLoader()) |