Spaces:
Running on Zero

File size: 5,329 Bytes
abf4b7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Decoding safeguards for Axiom-1: repetition and frequency penalties, no-repeat-n-gram blocking, min/max reply
length, stop tokens.

Every rule looks only at the reply generated so far, never at the prompt, so a reply may reuse the user's words
("What is the capital of France?" -> "The capital of France is Paris."). Penalties skip `exempt` tokens (punctuation,
whitespace, specials): charging "." and "\\n" per use pushes a small model into run-on text.
"""
import re
from dataclasses import dataclass, fields

import torch


@dataclass
class DecodeConfig:
    temperature: float = 0.7        # <= 0: greedy
    top_p: float = 0.9
    top_k: int = 0                  # 0 = off
    repetition_penalty: float = 1.0  # CTRL rule on tokens already in the reply: logit / r if > 0, logit * r if < 0
    frequency_penalty: float = 0.0  # logit -= f * (times the token is already in the reply)
    no_repeat_ngram: int = 0        # ban a token that would repeat an n-gram of the reply; 0 = off
    min_new: int = 0                # stop tokens are banned until the reply has this many tokens
    max_new: int = 300
    end_bias: float = 0.0           # added to the first stop token right after a sentence-final token (rd_improvements.md §2.5)

    def replace(self, **kw):
        return DecodeConfig(**{f.name: getattr(self, f.name) for f in fields(self)} | kw)


# Tuned with eval_chat.py --sweep (rd_coherence.md §4). Lower temperature read more fluent to the judge but made replies
# generic (at 0.3, 41/68 replies opened alike; greedy: 6/68 and loops); the penalties keep repetition at zero.
# end_bias 6 (rd_improvements.md §2.5): judge "good" 37% -> 58% and self-stopping 28% -> 80% on axiom1_chat, no training.
RECOMMENDED = DecodeConfig(temperature=0.5, top_p=0.9, repetition_penalty=1.15, no_repeat_ngram=4, min_new=2, max_new=300,
                           end_bias=6.0)
_SENT_END = re.compile(r"[.!?][\"')\]]?\s*$")


def sentence_ends(tok):
    """bool [V]: tokens that end a sentence (".", "!", "?", optionally followed by a closing quote or bracket)."""
    return torch.tensor([bool(_SENT_END.search(tok.decode([i]))) for i in range(tok.get_vocab_size())])


def default_exempt(tok):
    """bool [V]: special tokens and tokens with no letter or digit (punctuation, spaces, newlines)."""
    V = tok.get_vocab_size()
    special = {i for s, i in tok.get_vocab().items() if s.startswith("<|") and s.endswith("|>")}
    return torch.tensor([i in special or not re.search(r"\w", tok.decode([i])) for i in range(V)])


def process(logits, reply, cfg, stop=(), exempt=None, sent_end=None):
    """logits [V] for the next token, reply = token ids generated so far -> adjusted float logits (a new tensor).
    sent_end (from sentence_ends) enables cfg.end_bias; without it the bias is off."""
    logits = logits.float().clone()
    prev = torch.tensor(reply, dtype=torch.long, device=logits.device)
    if exempt is not None and len(prev):
        prev = prev[~exempt.to(logits.device)[prev]]
    if len(prev) and (cfg.repetition_penalty != 1.0 or cfg.frequency_penalty):
        counts = torch.bincount(prev, minlength=len(logits)).float()
        seen = counts > 0
        r = cfg.repetition_penalty
        logits[seen] = torch.where(logits[seen] > 0, logits[seen] / r, logits[seen] * r)
        logits -= cfg.frequency_penalty * counts
    n = cfg.no_repeat_ngram
    if n and len(reply) >= n:
        tail = reply[len(reply) - n + 1:] if n > 1 else []
        banned = [reply[i + n - 1] for i in range(len(reply) - n + 1) if reply[i:i + n - 1] == tail]
        logits[banned] = -float("inf")
    if len(reply) < cfg.min_new and stop:
        logits[list(stop)] = -float("inf")
    elif cfg.end_bias and stop and sent_end is not None and reply and sent_end[reply[-1]]:
        logits[stop[0]] += cfg.end_bias  # nudge toward ending once a sentence is complete
    return logits


def sample(logits, cfg, gen=None):
    if cfg.temperature <= 0:
        return int(logits.argmax())
    p = (logits / cfg.temperature).softmax(-1)
    if cfg.top_k:
        p[p < p.topk(cfg.top_k).values[-1]] = 0
    sp, si = p.sort(descending=True)
    sp[(sp.cumsum(0) - sp) > cfg.top_p] = 0
    return int(si[torch.multinomial(sp, 1, generator=gen)])


@torch.no_grad()
def generate(model, prompt, cfg, stop=(), exempt=None, gen=None, max_ctx=1024, sent_end=None):
    """Yield reply token ids one at a time (streaming); the stop token, if one is produced, is yielded last.
    Same model calls as axiom.lm.generate: AXIOM decodes from its recurrent state, the Transformer re-reads its context.
    cfg.end_bias applies only when sent_end is given (stop[0] must be the end-of-reply token)."""
    model.eval()
    axiom = bool(model.law_layers())
    dev = model.emb.weight.device
    x = torch.tensor([prompt], device=dev)
    states, reply = None, []
    for _ in range(cfg.max_new):
        if not axiom:
            logits, _, _ = model(x[:, -max_ctx:])
        elif states is None:
            logits, _, states = model(x)
        else:
            logits, _, states = model(x[:, -1:], states)
        t = sample(process(logits[0, -1], reply, cfg, stop, exempt, sent_end), cfg, gen)
        reply.append(t)
        x = torch.cat([x, torch.tensor([[t]], device=dev)], 1)
        yield t
        if t in stop:
            return