Spaces:
Running on Zero
Running on Zero
Download concepts.py from Pliploop/steerable-retrieval: direct link, hf CLI and curl.
- Browser
- Download file 1.39 kB
-
https://huggingface.co/spaces/Pliploop/steerable-retrieval/resolve/main/concepts.py
- Command line
-
hf download hf://spaces/Pliploop/steerable-retrieval/concepts.py
-
curl -L -o concepts.py https://huggingface.co/spaces/Pliploop/steerable-retrieval/resolve/main/concepts.py
1.39 kB
| """Bounded concept-payload cache and CPU recovery for GPU worker failures.""" | |
| from collections import OrderedDict | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| class ConceptPayloadCache: | |
| def __init__(self, capacity=64): | |
| if capacity < 1: | |
| raise ValueError("Concept cache capacity must be positive.") | |
| self.capacity = capacity | |
| self._values = OrderedDict() | |
| def get_or_create(self, concept, *, gpu, cpu, on_cpu=None): | |
| key = " ".join(concept.strip().lower().split()) | |
| if key in self._values: | |
| self._values.move_to_end(key) | |
| return self._values[key] | |
| try: | |
| payload = gpu(concept) | |
| except Exception: | |
| # Worker initialization can fail before @spaces.GPU executes the | |
| # decorated function, so recovery must live outside that boundary. | |
| logger.warning("GPU concept creation failed; falling back to CPU", exc_info=True) | |
| if on_cpu is not None: | |
| on_cpu() | |
| try: | |
| payload = cpu(concept) | |
| except Exception: | |
| logger.exception("CPU concept creation also failed") | |
| raise | |
| self._values[key] = payload | |
| self._values.move_to_end(key) | |
| while len(self._values) > self.capacity: | |
| self._values.popitem(last=False) | |
| return payload | |