# SPDX-License-Identifier: Apache-2.0 """The ``cpu`` engine: the clean-room fp32 reference behind the pipeline's engine interface.""" from __future__ import annotations from typing import List, Sequence import numpy as np from .. import model_spec as S from . import model as R class CpuEngine: name = "cpu" def __init__(self, W: dict, threads: int = 0): import torch self.W = {k: (v.float() if v.is_floating_point() else v) for k, v in W.items()} if threads: torch.set_num_threads(int(threads)) def vision(self, patches: Sequence) -> List[np.ndarray]: import torch out = [] with torch.inference_mode(): for p in patches: soft = R.vision_tower(self.W, torch.from_numpy(p.pixels), torch.from_numpy(p.positions).long(), p.n_tokens) out.append(R.embed_mm(self.W, "embed_vision", soft).numpy()) return out def audio(self, clips: Sequence) -> List[np.ndarray]: import torch out = [] with torch.inference_mode(): for feats, mask in clips: o, valid = R.audio_tower(self.W, torch.from_numpy(feats), torch.from_numpy(mask)) out.append(R.embed_mm(self.W, "embed_audio", o[valid]).numpy()) return out def text(self, xs: Sequence[np.ndarray], want_tokens: bool = False): import torch sums, toks = [], [] with torch.inference_mode(): for x in xs: t = R.text_backbone(self.W, torch.from_numpy(x)[None], torch.ones(1, x.shape[0]))[0] sums.append(t.double().sum(0).float().numpy()) if want_tokens: toks.append(t.numpy()) return np.stack(sums), (toks if want_tokens else None) def describe(self): return {"engine": "cpu"} def close(self): pass