|
| 1 | +import importlib |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import tempfile |
| 5 | +from collections.abc import Callable |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import numba |
| 9 | +import numba.core.caching |
| 10 | +from numba.core.caching import CacheImpl |
| 11 | + |
| 12 | + |
| 13 | +class PyTensorLoader(importlib.abc.SourceLoader): |
| 14 | + def __init__(self): |
| 15 | + # Key is "pytensor_generated_" + hash of pytensor graph |
| 16 | + self._module_sources = {} |
| 17 | + self._module_globals = {} |
| 18 | + self._module_locals = {} |
| 19 | + |
| 20 | + def get_source(self, fullname): |
| 21 | + if fullname not in self._module_sources: |
| 22 | + raise ImportError() |
| 23 | + return self._module_sources[fullname] |
| 24 | + |
| 25 | + def get_data(self, path): |
| 26 | + if path not in self._module_sources: |
| 27 | + raise ImportError() |
| 28 | + return self._module_sources[path].encode("utf-8") |
| 29 | + |
| 30 | + def get_filename(self, path): |
| 31 | + if path not in self._module_sources: |
| 32 | + raise ImportError() |
| 33 | + return path |
| 34 | + |
| 35 | + def add_module(self, name, src, global_env, local_env): |
| 36 | + self._module_sources[name] = src |
| 37 | + self._module_globals[name] = global_env |
| 38 | + self._module_locals[name] = local_env |
| 39 | + |
| 40 | + def exec_module(self, module): |
| 41 | + name = module.__name__ |
| 42 | + variables = module.__dict__ |
| 43 | + variables.update(self._module_globals[name]) |
| 44 | + variables.update(self._module_locals[name]) |
| 45 | + code = compile(self._module_sources[name], name, "exec") |
| 46 | + exec(code, variables) |
| 47 | + |
| 48 | + def create_module(self, spec): |
| 49 | + return None |
| 50 | + |
| 51 | + |
| 52 | +pytensor_loader = PyTensorLoader() |
| 53 | + |
| 54 | + |
| 55 | +def load_module(key, src, global_env, local_env): |
| 56 | + pytensor_loader.add_module(key, src, global_env, local_env) |
| 57 | + spec = importlib.util.spec_from_loader(key, pytensor_loader) |
| 58 | + module = importlib.util.module_from_spec(spec) |
| 59 | + spec.loader.exec_module(module) |
| 60 | + sys.modules[key] = module |
| 61 | + return module |
| 62 | + |
| 63 | + |
| 64 | +class NumbaPyTensorCacheLocator(numba.core.caching._CacheLocator): |
| 65 | + def __init__(self, py_func, py_file): |
| 66 | + # print(f"New locator {py_func=}, {py_file=}") |
| 67 | + self._py_func = py_func |
| 68 | + self._py_file = py_file |
| 69 | + self._hash = py_file |
| 70 | + # src_hash = hash(pytensor_loader._module_sources[self._py_file]) |
| 71 | + # self._hash = hash((src_hash, py_file, pytensor.__version__)) |
| 72 | + |
| 73 | + def ensure_cache_path(self): |
| 74 | + path = self.get_cache_path() |
| 75 | + os.makedirs(path, exist_ok=True) |
| 76 | + # Ensure the directory is writable by trying to write a temporary file |
| 77 | + tempfile.TemporaryFile(dir=path).close() |
| 78 | + |
| 79 | + def get_cache_path(self): |
| 80 | + """ |
| 81 | + Return the directory the function is cached in. |
| 82 | + """ |
| 83 | + return "~/.cache/pytensor" |
| 84 | + |
| 85 | + def get_source_stamp(self): |
| 86 | + """ |
| 87 | + Get a timestamp representing the source code's freshness. |
| 88 | + Can return any picklable Python object. |
| 89 | + """ |
| 90 | + |
| 91 | + return self._hash |
| 92 | + |
| 93 | + def get_disambiguator(self): |
| 94 | + """ |
| 95 | + Get a string disambiguator for this locator's function. |
| 96 | + It should allow disambiguating different but similarly-named functions. |
| 97 | + """ |
| 98 | + return None |
| 99 | + |
| 100 | + @classmethod |
| 101 | + def from_function(cls, py_func, py_file): |
| 102 | + """ |
| 103 | + Create a locator instance for the given function located in the |
| 104 | + given file. |
| 105 | + """ |
| 106 | + if py_func.__module__ in pytensor_loader._module_sources: |
| 107 | + return cls(py_func, py_file) |
| 108 | + |
| 109 | + |
| 110 | +CacheImpl._locator_classes.append(NumbaPyTensorCacheLocator) |
| 111 | + |
| 112 | + |
| 113 | +def compile_function_src2( |
| 114 | + key: str, |
| 115 | + src: str, |
| 116 | + function_name: str, |
| 117 | + global_env: dict[Any, Any] | None = None, |
| 118 | + local_env: dict[Any, Any] | None = None, |
| 119 | +) -> Callable: |
| 120 | + # with NamedTemporaryFile(delete=False) as f: |
| 121 | + # filename = f.name |
| 122 | + # f.write(src.encode()) |
| 123 | + |
| 124 | + if global_env is None: |
| 125 | + global_env = {} |
| 126 | + |
| 127 | + if local_env is None: |
| 128 | + local_env = {} |
| 129 | + |
| 130 | + # mod_code = compile(src, filename, mode="exec") |
| 131 | + # exec(mod_code, global_env, local_env) |
| 132 | + # print(key, src) |
| 133 | + module = load_module(key, src, global_env, local_env) |
| 134 | + res = getattr(module, function_name) |
| 135 | + |
| 136 | + # res = cast(Callable, res) |
| 137 | + # res.__source__ = src # type: ignore |
| 138 | + return res |
0 commit comments