| 274 | return outputs |
| 275 | |
| 276 | def predict(self, |
| 277 | inputs: Iterable[JsonDict], |
| 278 | progress_indicator: Optional[ProgressIndicator] = lambda x: x, |
| 279 | **kw) -> list[JsonDict]: |
| 280 | inputs_as_list = list(inputs) |
| 281 | |
| 282 | if self._strict_id_validation: |
| 283 | self._validate_ids(inputs_as_list) |
| 284 | |
| 285 | # Try to get results from the cache. |
| 286 | input_keys = [self.key_fn(d) for d in inputs_as_list] |
| 287 | if (none_keys := [k for k in input_keys if k is None]): |
| 288 | logging.warning( |
| 289 | "Attmepting to retrieve %d (of %d) predictions from the cache where" |
| 290 | " the cache key is None - this can be from a missing or empty example" |
| 291 | " id. These will call model.predict() on this and subsequent calls.", |
| 292 | len(none_keys), |
| 293 | len(input_keys), |
| 294 | ) |
| 295 | if self._cache.pred_lock_key(input_keys): |
| 296 | with self._cache.get_pred_lock(input_keys): |
| 297 | cached_results = self._get_results_from_cache(input_keys) |
| 298 | else: |
| 299 | cached_results = self._get_results_from_cache(input_keys) |
| 300 | |
| 301 | # Make a single list of everything that wasn't found in the cache, |
| 302 | # to actually run the model on these inputs. |
| 303 | miss_idxs = [i for i, v in enumerate(cached_results) if v is None] |
| 304 | misses = [inputs_as_list[i] for i in miss_idxs] |
| 305 | if misses: |
| 306 | logging.info("%s: %d misses out of %d inputs", self._log_prefix, |
| 307 | len(miss_idxs), len(cached_results)) |
| 308 | else: |
| 309 | # If all results were already cached, return them. |
| 310 | return cached_results |
| 311 | |
| 312 | with self._cache.get_pred_lock(input_keys): |
| 313 | model_preds = list(self.wrapped.predict(progress_indicator(misses))) |
| 314 | logging.info("Received %d predictions from model", len(model_preds)) |
| 315 | |
| 316 | if len(model_preds) != len(misses): |
| 317 | raise ValueError(f"Received {len(model_preds)} predictions, which does " |
| 318 | f"not match {len(misses)}, the number of inputs.") |
| 319 | |
| 320 | # Merge results back into the output list. |
| 321 | with self._cache.lock: |
| 322 | for i, orig_idx in enumerate(miss_idxs): |
| 323 | self._cache.put(model_preds[i], self.key_fn(inputs_as_list[orig_idx])) |
| 324 | cached_results[orig_idx] = model_preds[i] |
| 325 | |
| 326 | # Remove the prediction lock from the cache as the request is complete |
| 327 | self._cache.delete_pred_lock(input_keys) |
| 328 | |
| 329 | return cached_results |
| 330 | |
| 331 | def _get_results_from_cache(self, input_keys: list[CacheKey]): |
| 332 | with self._cache.lock: |