File size: 1,658 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Frame-by-frame controller for the server: one call per 80 ms frame, per session."""
import numpy as np
import torch

from controller.encoder.student import load_student
from controller.model.model import load_controller
from duplex.spec import FRAME


class DuplexController:
    def __init__(self, encoder_ckpt, controller_ckpt, device="cuda:1"):
        self.device = torch.device(device)
        self.encoder = load_student(encoder_ckpt, self.device)
        self.ctl = load_controller(controller_ckpt, self.device)
        warm = self.new_session()                 # first calls pay one-time GPU set-up; do it before a caller arrives
        for _ in range(30):
            self.step(warm, np.zeros(FRAME, np.float32), np.zeros(FRAME, np.float32))

    def new_session(self):
        # batch of 2 in the encoder: row 0 is the caller's audio, row 1 the model's own output
        return {"enc": self.encoder.init_state(2, self.device), "ctl": self.ctl.init_state()}

    @torch.inference_mode()
    def step(self, sess, caller_frame, own_frame):
        """caller_frame, own_frame: float32 [1280] at 16 kHz. Returns probabilities over LABELS."""
        assert len(caller_frame) == FRAME and len(own_frame) == FRAME
        wav = torch.from_numpy(np.stack([caller_frame, own_frame]).astype(np.float32)).to(self.device)
        with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda"):
            feats, sess["enc"] = self.encoder.step(wav, sess["enc"])
            logits, sess["ctl"] = self.ctl.step(feats[0:1], feats[1:2], sess["ctl"])
        return torch.softmax(logits[0, -1].float(), dim=-1).cpu().numpy()