File size: 9,329 Bytes
4ffdd01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# SPDX-License-Identifier: Apache-2.0
"""Host reference of Raon sampling (ARCH sections 5, 6; STATE.md section 4). Defines the semantics the device
samplers are tested against. Plain torch + numpy.

Official processors (``generate``: one ``LogitsProcessorList`` shared by text tokens and code0): temperature (only
when != 1.0; HF divides), top-k (when > 0; ``min(top_k, vocab)``, boundary ties kept), top-p (when < 1; HF
``TopPLogitsWarper``). Text masks before them: ``<|audio_output_pad|>`` = finfo.min always (text mode samples with
force_text_output=True), ``<|im_end|>`` = finfo.min on the first generated token (``disable_eos_on_first_output``).
Then ``softmax`` (fp32), ``clamp_min(finfo.tiny)``, ``torch.multinomial``. Code0: the same processors on the 2049
audio logits; repetition-aware sampling (RAS) may resample from the raw softmax.

Two modes:

* ``"torch"``: the official float ops and RNG calls in the official order (golden parity; reproduces the official
  token stream when the logits are equal and the torch RNG is seeded the same way);
* ``"device"``: the device semantics (``device_select``: top-k candidates by descending score / ascending id,
  HF nucleus cut, fp32 softmax over the kept set, first rank with cumsum > u), u from Philox (``tt.state.philox_u``,
  counter (GEN, purpose)).
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import List, Optional, Sequence

import numpy as np
import torch

from ..tt import state as S

NEG_INF = float("-inf")
F32_MIN = torch.finfo(torch.float32).min


# ============================================================================================ HF processors
def temperature_warp(scores: torch.Tensor, temperature: float) -> torch.Tensor:
    return scores / temperature if temperature and temperature != 1.0 else scores


def top_k_warp(scores: torch.Tensor, top_k: int) -> torch.Tensor:
    if not top_k or top_k <= 0:
        return scores
    k = min(int(top_k), scores.shape[-1])
    kth = torch.topk(scores, k)[0][..., -1, None]
    return scores.masked_fill(scores < kth, NEG_INF)


def top_p_warp(scores: torch.Tensor, top_p: float) -> torch.Tensor:
    if top_p is None or top_p >= 1.0:
        return scores
    sl, si = torch.sort(scores, descending=False)
    cum = sl.softmax(dim=-1).cumsum(dim=-1)
    rem = cum <= (1 - top_p)
    rem[..., -1:] = False
    return scores.masked_fill(rem.scatter(-1, si, rem), NEG_INF)


def hf_process(scores: torch.Tensor, do_sample: bool, temperature: float, top_k: int, top_p: float) -> torch.Tensor:
    """The official ``LogitsProcessorList`` (warpers are only built when sampling)."""
    if not do_sample:
        return scores
    s = temperature_warp(scores, temperature)
    s = top_k_warp(s, top_k)
    return top_p_warp(s, top_p)


def torch_draw(processed: torch.Tensor, generator: Optional[torch.Generator] = None) -> int:
    """softmax fp32, clamp tiny, multinomial on a [1, V] tensor (official call shape)."""
    probs = torch.softmax(processed.reshape(1, -1), dim=-1, dtype=torch.float32)
    probs = probs.clamp_min(torch.finfo(probs.dtype).tiny)
    return int(torch.multinomial(probs, num_samples=1, generator=generator)[0, 0])


def torch_draw_raw(logits: torch.Tensor, generator: Optional[torch.Generator] = None) -> int:
    """RAS resample: softmax of the raw logits ([V], official ``apply_repetition_aware_sampling``)."""
    probs = torch.softmax(logits.reshape(-1), dim=-1, dtype=torch.float32)
    probs = probs.clamp_min(torch.finfo(probs.dtype).tiny)
    return int(torch.multinomial(probs, num_samples=1, generator=generator)[0])


# ============================================================================================ device selection
def candidate_order(scores: torch.Tensor) -> torch.Tensor:
    s = scores.reshape(-1)
    ids = torch.nonzero(torch.isfinite(s) & (s > F32_MIN / 2), as_tuple=False).reshape(-1)
    key = np.lexsort((ids.numpy(), -s[ids].double().numpy()))
    return ids[torch.from_numpy(key)]


def top_p_keep(sorted_desc: torch.Tensor, top_p: float) -> int:
    if top_p >= 1.0:
        return int(sorted_desc.numel())
    asc = torch.flip(sorted_desc, [0])
    cum = torch.softmax(asc, -1).cumsum(-1)
    remove = cum <= (1.0 - top_p)
    remove[-1] = False
    return int((~remove).sum())


def device_select(scores: torch.Tensor, do_sample: bool, inv_temperature: float = 1.0, top_k: int = 0,
                  top_p: float = 1.0, u: Optional[float] = None) -> int:
    """STATE.md section 4 selection on masked fp32 scores (masked ids = -inf / finfo.min)."""
    s = scores.reshape(-1).float()
    if not do_sample:
        return int(torch.argmax(s))
    if u is None:
        raise ValueError("device_select needs u when sampling")
    s = s * torch.tensor(np.float32(inv_temperature))
    if top_k and 0 < int(top_k) < s.numel():  # HF top-k: keep every score >= the k-th (boundary ties kept)
        kth = torch.topk(s, int(top_k)).values[-1]
        ids = torch.nonzero(s >= kth, as_tuple=False).reshape(-1)
        ids = ids[torch.isfinite(s[ids]) & (s[ids] > F32_MIN / 2)]
        order = ids[torch.from_numpy(np.lexsort((ids.numpy(), -s[ids].double().numpy())))]
    else:
        order = candidate_order(s)
    ss = s[order]
    kept = top_p_keep(ss, top_p)
    p = torch.softmax(ss[:kept], -1)
    c = torch.cumsum(p, -1)
    hit = torch.nonzero(c > torch.tensor(np.float32(u)), as_tuple=False)
    rank = int(hit[0, 0]) if hit.numel() else kept - 1
    return int(order[rank])


def select_idorder(scores: torch.Tensor, u: float) -> int:
    """RAS resample (STATE.md section 4): fp32 softmax over ALL ids, cumsum in id order, the first id with
    cumsum > u (the last id if none). Same distribution as the sorted selection, cheaper on the device (mk_talker
    ``mks::select_full_idorder``)."""
    p = torch.softmax(scores.reshape(-1).float(), -1)
    c = torch.cumsum(p, -1)
    hit = torch.nonzero(c > torch.tensor(np.float32(u)), as_tuple=False)
    return int(hit[0, 0]) if hit.numel() else int(p.numel() - 1)


# ============================================================================================ the sampler
@dataclass
class SamplingParams:
    do_sample: bool = True
    temperature: float = 0.7
    top_k: int = 20
    top_p: float = 0.8
    seed: int = 0
    ras_enabled: bool = False
    ras_window_size: int = 50
    ras_repetition_threshold: float = 0.5

    @classmethod
    def from_dict(cls, d) -> "SamplingParams":
        d = dict(d or {})
        return cls(**{k: d[k] for k in cls.__dataclass_fields__ if k in d and d[k] is not None})


@dataclass
class Sampler:
    """Samples at the sample points of STATE.md section 3 on a STATE page (GEN, masks and the RAS history come from
    the page; the caller applies ``tt.state.after_*`` with the result)."""

    params: SamplingParams = field(default_factory=SamplingParams)
    mode: str = "device"
    generator: Optional[torch.Generator] = None
    ras_hits: int = 0

    def text(self, logits: torch.Tensor, page: np.ndarray) -> int:
        p = self.params
        s = logits.reshape(-1).float().clone()
        for i in S.text_masks(page):
            s[i] = F32_MIN
        g = int(np.asarray(page).reshape(-1)[S.W.GEN])
        if self.mode == "torch":
            if not p.do_sample:
                return int(torch.argmax(s))
            return torch_draw(hf_process(s, True, p.temperature, p.top_k, p.top_p), self.generator)
        inv = 1.0 / p.temperature if p.do_sample else 1.0
        u = S.philox_u(p.seed, g, S.PURPOSE_SAMPLE) if p.do_sample else None
        return device_select(s, p.do_sample, inv, p.top_k, p.top_p, u)

    def code0(self, logits: torch.Tensor, page: np.ndarray) -> int:
        """code0 incl. RAS (0..2048; 2048 = audio end)."""
        p = self.params
        raw = logits.reshape(-1).float()
        g = int(np.asarray(page).reshape(-1)[S.W.GEN])
        if self.mode == "torch":
            if not p.do_sample:
                return int(torch.argmax(raw))
            c = torch_draw(hf_process(raw.clone(), True, p.temperature, p.top_k, p.top_p), self.generator)
            if S.ras_triggered(page, c):
                self.ras_hits += 1
                c = torch_draw_raw(raw, self.generator)
            return c
        if not p.do_sample:
            return int(torch.argmax(raw))
        c = device_select(raw, True, 1.0 / p.temperature, p.top_k, p.top_p, S.philox_u(p.seed, g, S.PURPOSE_SAMPLE))
        if S.ras_triggered(page, c):
            self.ras_hits += 1
            c = select_idorder(raw, S.philox_u(p.seed, g, S.PURPOSE_RAS))
        return c


# ============================================================================================ distributions (gates)
def official_probs(logits: torch.Tensor, temperature: float, top_k: int = 20, top_p: float = 0.8,
                   masks: Sequence[int] = ()) -> torch.Tensor:
    """The official sampling distribution in float64 (gate TVDs)."""
    s = logits.double().reshape(-1).clone()
    for i in masks:
        s[i] = float("-inf")
    s = s / temperature if temperature != 1.0 else s
    s = top_k_warp(s, top_k)
    s = top_p_warp(s, top_p)
    return torch.softmax(s, -1)


def tvd(p: torch.Tensor, q: torch.Tensor) -> float:
    return 0.5 * float((p.double() - q.double()).abs().sum())