File size: 1,925 Bytes
5c33f00 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | # 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
|