Run this model with HF Jobs

Run olaverse/YellowMIST-Encoder-15M-AP on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/olaverse/YellowMIST-Encoder-15M-AP. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/olaverse/YellowMIST-Encoder-15M-AP on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 4,991 Bytes
28f5f91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""Gated delta rule: the memory update inside Dew's DeltaNet layers.

Per head the memory is a matrix S (key dim x value dim). For each word t:

    S <- exp(g_t) * S                          decay      (g_t <= 0, log space)
    S <- S + beta_t * k_t (v_t - S^T k_t)^T    delta write (beta_t in [0, 1])
    o_t = S^T q_t * scale                      read

A word with beta = 0 and g = 0 leaves S exactly as it was: this is how a napping word
"does not write to the whiteboard and causes no decay".

Three implementations, checked against each other by `python -m dew.selftest`:
  * fla        Triton kernels from flash-linear-attention (fast training on GPU)
  * chunk      pure PyTorch, chunked (WY / UT form), any device, used when fla is missing
  * step       one word at a time, used for decoding and the ONNX export
"""
from __future__ import annotations

import inspect
import os

import torch

_FLA = None   # None = not checked yet, False = unavailable


def _fla():
    global _FLA
    if _FLA is None:
        _FLA = False
        if os.environ.get("DEW_NO_FLA") != "1":
            try:
                from fla.ops.gated_delta_rule import chunk_gated_delta_rule as f
                params = inspect.signature(f).parameters
                _FLA = (f, "head_first" in params)
            except Exception:
                _FLA = False
    return _FLA


def fla_available() -> bool:
    return bool(_fla())


def l2norm(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    return x * torch.rsqrt(x.pow(2).sum(-1, keepdim=True) + eps)


def gated_delta_rule(q, k, v, g, beta, impl: str = "auto"):
    """q, k: [B, T, H, K] (already L2-normalised), v: [B, T, H, V], g, beta: [B, T, H].
    Returns o: [B, T, H, V] in v's dtype."""
    scale = q.shape[-1] ** -0.5
    f = _fla() if impl in ("auto", "fla") else False
    if f and q.is_cuda:
        fn, has_head_first = f
        kw = {"scale": scale, "output_final_state": False}
        if has_head_first:
            kw["head_first"] = False
        o, _ = fn(q, k, v, g.float(), beta.to(q.dtype), **kw)
        return o.to(v.dtype)
    if impl == "fla":
        raise RuntimeError("fla requested but not available")
    return chunk_reference(q, k, v, g, beta, scale).to(v.dtype)


def chunk_reference(q, k, v, g, beta, scale, chunk: int = 64):
    """Chunked gated delta rule in plain PyTorch (fp32). Same maths as fla's reference."""
    dt = v.dtype
    with torch.autocast(q.device.type, enabled=False):
        q, k, v, g, beta = (x.float().transpose(1, 2) for x in (q, k, v, g, beta))   # [B, H, T, .]
        B, H, T, K = k.shape
        V = v.shape[-1]
        pad = (chunk - T % chunk) % chunk
        if pad:
            q, k, v = (torch.nn.functional.pad(x, (0, 0, 0, pad)) for x in (q, k, v))
            g, beta = (torch.nn.functional.pad(x, (0, pad)) for x in (g, beta))
        n = q.shape[2] // chunk
        q = q * scale
        kb = k * beta[..., None]
        vb = v * beta[..., None]
        q, k, kb, vb = (x.view(B, H, n, chunk, -1) for x in (q, k, kb, vb))
        g = g.view(B, H, n, chunk).cumsum(-1)
        tri = torch.ones(chunk, chunk, dtype=torch.bool, device=q.device).tril()
        diff = (g[..., :, None] - g[..., None, :]).masked_fill(~tri, float("-inf"))
        L = diff.exp()                                                     # decay from j to i (i >= j)
        A = ((kb @ k.transpose(-1, -2)) * L).tril(-1)
        eye = torch.eye(chunk, device=q.device).expand_as(A)
        Tm = torch.linalg.solve_triangular(eye + A, eye, upper=False, unitriangular=True)   # (I + A)^-1
        kcd = Tm @ (kb * g.exp()[..., None])
        u = Tm @ vb
        S = q.new_zeros(B, H, K, V)
        o = torch.empty_like(u)
        for i in range(n):
            qi, ki, gi = q[:, :, i], k[:, :, i], g[:, :, i]
            att = (qi @ ki.transpose(-1, -2) * L[:, :, i]).tril()
            vnew = u[:, :, i] - kcd[:, :, i] @ S
            o[:, :, i] = (qi * gi.exp()[..., None]) @ S + att @ vnew
            S = S * gi[..., -1, None, None].exp() + (ki * (gi[..., -1, None] - gi).exp()[..., None]).transpose(-1, -2) @ vnew
        o = o.view(B, H, n * chunk, V)[:, :, :T]
    return o.transpose(1, 2).to(dt)


def delta_step(q, k, v, g, beta, S):
    """One word. q, k: [B, H, K] (L2-normalised), v: [B, H, V], g, beta: [B, H], S: [B, H, K, V]."""
    scale = q.shape[-1] ** -0.5
    S = S * g.exp()[..., None, None]
    kv = (k[..., None] * S).sum(-2)                       # S^T k
    S = S + k[..., None] * ((v - kv) * beta[..., None])[..., None, :]
    o = (q[..., None] * S).sum(-2) * scale
    return o, S


def recurrent_reference(q, k, v, g, beta):
    """Whole sequence, one word at a time (slow; for tests)."""
    B, T, H, K = q.shape
    S = q.new_zeros(B, H, K, v.shape[-1]).float()
    out = []
    for t in range(T):
        o, S = delta_step(q[:, t].float(), k[:, t].float(), v[:, t].float(), g[:, t].float(), beta[:, t].float(), S)
        out.append(o)
    return torch.stack(out, 1)