Spaces:
Running on Zero

File size: 1,891 Bytes
a369496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""PyTorch reference kernels for frozen CaMa feature extraction."""

import torch
from torch.nn import functional as F


def causal_convolution(sequence, weight, bias=None, activation=None):
    width = sequence.shape[-1]
    result = F.conv1d(sequence, weight.unsqueeze(1), bias, padding=weight.shape[-1] - 1,
                      groups=sequence.shape[1])[..., :width]
    if activation not in (None, 'silu', 'swish'):
        raise ValueError(f'Unsupported CaMa activation: {activation}')
    return F.silu(result) if activation is not None else result


def selective_scan(inputs, delta, decay, in_scale, out_scale, skip=None, gate=None, bias=None,
                   delta_softplus=False, return_last_state=False):
    dtype = inputs.dtype
    inputs, delta = inputs.float(), delta.float()
    if bias is not None:
        delta = delta + bias.float()[:, None]
    if delta_softplus:
        delta = F.softplus(delta)
    transition = torch.exp(torch.einsum('bdl,dn->bdln', delta, decay))
    drive = torch.einsum('bdl,bnl,bdl->bdln', delta, in_scale.float(), inputs)
    state = torch.zeros_like(transition[:, :, 0])
    values = []
    for position in range(inputs.shape[-1]):
        state = transition[:, :, position] * state + drive[:, :, position]
        values.append(torch.einsum('bdn,bn->bd', state, out_scale[:, :, position].float()))
    output = torch.stack(values, dim=-1)
    if skip is not None:
        output = output + inputs * skip[:, None]
    if gate is not None:
        output = output * F.silu(gate)
    output = output.to(dtype)
    return (output, state) if return_last_state else output


def install():
    from vendor.rscama import mamba_block

    if not mamba_block.is_fast_path_available:
        mamba_block.causal_conv1d_fn = causal_convolution
        mamba_block.selective_scan_fn = selective_scan
        mamba_block.is_fast_path_available = True