Run this model with HF Jobs

Run olaverse/YellowMIST-Encoder-15M-EU 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-EU. 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-EU 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: 6,551 Bytes
0598fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""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)


EXPORT_SAFE = False      # True: use the ONNX-exportable inverse in eager too (tests)
CHUNK = int(__import__("os").environ.get("DEW_CHUNK", "64"))   # chunk size off GPU; exact for any power of 2.
                                                               # Short text runs faster with 16-32 on CPU.


def unit_lower_inverse(A: torch.Tensor) -> torch.Tensor:
    """(I + A)^-1 for strictly lower-triangular A [..., C, C], C a power of 2, by block doubling.

    Start from 1x1 blocks (inverse = 1) and merge neighbouring blocks: if D is the block-diagonal part with blocks
    of size s and L links each pair's second half to its first, then (D + L)^-1 = D^-1 - D^-1 L D^-1 exactly
    (L D^-1 L = 0). log2(C) rounds of two matmuls: as stable as a triangular solve, few ops (fast on CPU), and
    only matmul / mul / sub, so it exports to ONNX. (Forming powers of A instead cancels badly in fp32.)"""
    C = A.shape[-1]
    assert C & (C - 1) == 0, "chunk size must be a power of 2"
    idx = torch.arange(C, device=A.device)
    r, c = idx[:, None], idx[None, :]
    inv = torch.eye(C, dtype=A.dtype, device=A.device).expand(A.shape)
    s = 1
    while s < C:
        pair = (r // (2 * s)) == (c // (2 * s))
        link = pair & ((r // s) % 2 == 1) & ((c // s) % 2 == 0)
        L = A * link.to(A.dtype)
        inv = inv - inv @ L @ inv
        s *= 2
    return inv


def chunk_reference(q, k, v, g, beta, scale, chunk: int = 0):
    """Chunked gated delta rule in plain PyTorch (fp32). Same maths as fla's reference."""
    dt = v.dtype
    chunk = chunk or CHUNK
    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)
        if torch.onnx.is_in_onnx_export() or EXPORT_SAFE:   # ONNX has no triangular solve
            Tm = unit_lower_inverse(A)
        else:
            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)
        outs = []
        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
            outs.append((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 = torch.stack(outs, 2).reshape(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)