File size: 12,750 Bytes
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e4c0fe
 
9d20fe4
9d3e0c7
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb4dacd
815acd7
9d20fe4
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb4dacd
 
815acd7
 
 
 
 
 
 
bb4dacd
 
 
 
 
 
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb4dacd
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e4c0fe
 
815acd7
 
9d20fe4
 
 
 
 
 
 
 
815acd7
 
 
3e4c0fe
 
 
 
 
 
 
 
 
815acd7
 
 
 
 
bb4dacd
 
9d20fe4
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb4dacd
815acd7
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""Prompt-free causal sampling. The inspector uses the actual sampled distribution."""
from gpu_runtime import manager
import secrets
import threading
import uuid
from contextlib import nullcontext

import torch


class Flow:
    def __init__(self, tokens=None, text="", model_key="", seed=None, ended=False):
        shared = manager()
        self._shared = shared is not None
        self._status = shared.dict() if shared else {}
        self.selected_repo = ""
        self.continue_automatically = False
        self.tokens = list(tokens or [])
        self.stream_id = uuid.uuid4().hex
        self.space_history = []
        self.attention_history = {}
        self.layer_rows = self.layer_keys = None
        self.layer_queries = [-1] * 512
        self.representations = None
        self.sent_dimension_axes_key = ""
        self.paused = False
        self.running = False
        self.reset_requested = False
        self.view_revision = 0
        self.view_lock = threading.RLock()
        self.text_snapshot_cache = None
        self.text = text
        self.model_key = model_key
        self.seed = seed
        self.rng_state = None
        self.ended = ended
        self.stop = shared.Event() if shared else threading.Event()
        self._control_lock = shared.RLock() if shared else threading.Lock()
        self._controls = shared.dict() if shared else {}

    @property
    def paused(self):
        return self._status.get("paused", False)

    @paused.setter
    def paused(self, value):
        self._status["paused"] = value

    @property
    def running(self):
        return self._status.get("running", False)

    @running.setter
    def running(self, value):
        self._status["running"] = value

    @property
    def reset_requested(self):
        return self._status.get("reset_requested", False)

    @reset_requested.setter
    def reset_requested(self, value):
        self._status["reset_requested"] = value

    @property
    def continue_automatically(self):
        return self._status.get("continue_automatically", False)

    @continue_automatically.setter
    def continue_automatically(self, value):
        self._status["continue_automatically"] = value

    def __getstate__(self):
        state = self.__dict__.copy()
        state.pop("view_lock", None)
        if not self._shared:
            state["_stopped"] = self.stop.is_set()
            state.pop("stop", None)
            state.pop("_control_lock", None)
        return state

    def __setstate__(self, state):
        self.__dict__.update(state)
        self.view_lock = threading.RLock()
        if not self._shared:
            self.stop = threading.Event()
            if self.__dict__.pop("_stopped", False):
                self.stop.set()
            self._control_lock = threading.Lock()

    def update_controls(self, **changes):
        bounds = {"temperature": (.05, 2), "top_p": (.05, 1), "penalty": (1, 2),
                  "memory": (16, 2048), "count": (1, 1024), "delay": (0, .5), "english_bias": (0, 4)}
        for name, value in changes.items():
            if name in ("watch", "auto_continue", "attention", "capture_representations"):
                if not isinstance(value, bool):
                    raise ValueError("Watch must be true or false.")
            elif name in ("attention_layer", "attention_head"):
                if int(value) != value or value < -1:
                    raise ValueError(f"{name} must be -1 or a nonnegative integer.")
            elif name not in bounds or not bounds[name][0] <= value <= bounds[name][1]:
                raise ValueError(f"Invalid live setting: {name}.")
            elif name in ("memory", "count") and int(value) != value:
                raise ValueError(f"{name} must be an integer.")
        with self._control_lock:
            self._controls.update(changes)

    def controls(self):
        with self._control_lock:
            return self._controls.copy()

    def __deepcopy__(self, memo):
        return Flow()  # Gradio creates an independent state for each visitor.


def distribution(logits, history, temperature, top_p, repetition_penalty, english_prior=None, english_bias=0):
    """Repetition penalty, optional language prior, temperature, then nucleus filtering."""
    if not 0.05 <= temperature <= 2 or not 0 < top_p <= 1 or not 1 <= repetition_penalty <= 2:
        raise ValueError("Sampling settings are outside the supported range.")
    scores = logits.detach().float().cpu().clone()
    if history and repetition_penalty != 1:
        ids = torch.tensor(sorted(set(history)), dtype=torch.long)
        values = scores[ids]
        scores[ids] = torch.where(values < 0, values * repetition_penalty, values / repetition_penalty)
    if not 0 <= english_bias <= 4:
        raise ValueError("English bias must be between 0 and 4.")
    if english_bias and english_prior is not None:
        if english_prior.shape != scores.shape:
            raise ValueError("Language prior does not match model vocabulary.")
        scores += english_prior * english_bias
    scores /= temperature
    raw = torch.softmax(scores, dim=-1)
    ordered, indices = torch.sort(raw, descending=True)
    # Keep the first token that crosses p, including the highest-probability token.
    remove = ordered.cumsum(0) - ordered >= top_p
    filtered = raw.clone()
    filtered[indices[remove]] = 0
    filtered /= filtered.sum()
    if not torch.isfinite(filtered).all():
        raise ValueError("The model returned invalid probabilities.")
    return filtered, raw


def start_id(model, tokenizer):
    for value in (tokenizer.bos_token_id, model.config.bos_token_id,
                  tokenizer.eos_token_id, model.config.eos_token_id):
        if value is not None:
            return int(value[0] if isinstance(value, (tuple, list)) else value)
    raise ValueError("This model has no BOS or EOS token. Prompt-free startup is unavailable.")


def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,

             context_limit=128, live_settings=None, attention_modules=None, english_prior=None):
    if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
        raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
    context_limit = int(context_limit)
    if flow.model_key and flow.model_key != key:
        raise ValueError("The loaded model changed. Choose Start fresh before continuing.")
    if flow.ended:
        raise ValueError("The model ended this stream. Choose Start fresh for another.")
    fresh = not flow.model_key
    if fresh:
        if seed is not None and (int(seed) != seed or not 0 <= seed <= 2**32 - 1):
            raise ValueError("Seed must be an integer from 0 to 4294967295, or blank.")
        flow.seed = int(seed) if seed is not None else secrets.randbits(32)
        flow.model_key = key
    rng = torch.Generator(device="cpu")
    if flow.rng_state is not None:
        rng.set_state(flow.rng_state)
    else:
        rng.manual_seed(flow.seed)
    prefix = [start_id(model, tokenizer)]
    eos = model.generation_config.eos_token_id
    eos_ids = set(eos if isinstance(eos, (list, tuple)) else [eos]) if eos is not None else set()
    eos_ids.update([tokenizer.eos_token_id] if tokenizer.eos_token_id is not None else [])
    limit = min(context_limit, int(getattr(model.config, "max_position_embeddings", context_limit)))
    cache = None
    consumed = 0
    emitted = 0
    with torch.inference_mode():
        while True:
            settings = live_settings() if live_settings is not None else {}
            if not settings.get("auto_continue", False) and emitted >= int(settings.get("count", count)):
                break
            next_limit = min(int(settings.get("memory", context_limit)),
                             int(getattr(model.config, "max_position_embeddings", context_limit)))
            if next_limit != limit:
                cache = None  # Old cached activations must not leak forgotten context.
                limit = next_limit
            current_temperature = settings.get("temperature", temperature)
            current_top_p = settings.get("top_p", top_p)
            current_penalty = settings.get("penalty", penalty)
            if flow.stop.is_set():
                break
            if len(flow.tokens) >= 16384:
                break
            all_ids = prefix + flow.tokens
            window = all_ids[-limit:]
            if cache is None or consumed >= limit:
                cache = None
                input_ids = torch.tensor([window], device=model.device)
                consumed = len(window)
            else:
                input_ids = torch.tensor([[flow.tokens[-1]]], device=model.device)
                consumed += 1
            probe = None
            if settings.get("attention", False):
                from attention_view import LayerAttentionProbe
                probe = LayerAttentionProbe(attention_modules or [], settings.get("attention_layer", -1),
                                       settings.get("attention_head", -1))
            with probe if probe is not None else nullcontext():
                capture_representations = settings.get("capture_representations", False)
                extra = {"output_hidden_states": True} if capture_representations else {}
                result = model(input_ids=input_ids, past_key_values=cache, use_cache=True, **extra)
            if capture_representations:
                from representations import RepresentationState
                if flow.representations is None:
                    flow.representations = RepresentationState()
                flow.representations.add(len(flow.tokens)-1, result.hidden_states)
            if probe is not None and flow.tokens:
                query = len(flow.tokens) - 1
                flow.attention_history[query] = probe.record(len(all_ids) - len(probe.row), query)
                packed, keys = probe.layer_record(len(all_ids))
                if flow.layer_rows is None or flow.layer_rows.shape[1] != len(packed):
                    flow.layer_rows = torch.zeros((512, *packed.shape), dtype=torch.float32)
                    flow.layer_keys = torch.zeros((512, len(packed)), dtype=torch.int32)
                    flow.layer_queries = [-1] * 512
                slot = query % 512
                flow.layer_rows[slot].copy_(packed)
                flow.layer_keys[slot].copy_(keys)
                flow.layer_queries[slot] = query
                for link in flow.attention_history[query]["links"]:
                    link["id"] = all_ids[link["n"] + 1]
                flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
            cache = result.past_key_values
            probs, before_nucleus = distribution(result.logits[0, -1], window,
                                                  current_temperature, current_top_p, current_penalty,
                                                  english_prior, settings.get("english_bias", 0))
            result = None  # Release optional full hidden-state outputs before yielding session state.
            chosen = int(torch.multinomial(probs, 1, generator=rng))
            flow.tokens.append(chosen)
            emitted += 1
            flow.rng_state = rng.get_state()
            flow.ended = chosen in eos_ids
            flow.text = tokenizer.decode(flow.tokens, skip_special_tokens=True,
                                         clean_up_tokenization_spaces=False)
            values, ids = torch.topk(probs, min(8, len(probs)))
            candidates = [(int(i), float(p)) for i, p in zip(ids, values) if p > 0]
            if chosen not in [i for i, _ in candidates]:
                candidates.append((chosen, float(probs[chosen])))
            yield {
                "text": flow.text,
                "candidates": candidates, "chosen": chosen,
                "chosen_probability": float(probs[chosen]),
                "retained_mass": float(before_nucleus[probs > 0].sum()),
                "other": max(0., 1. - sum(p for _, p in candidates)),
                "context_trimmed": len(all_ids) > limit,
                "context_limit": limit,
                "temperature": current_temperature, "top_p": current_top_p,
                "penalty": current_penalty,
                "english_bias": settings.get("english_bias", 0),
            }
            if flow.ended:
                break