Spaces:
Running on Zero
Running on Zero
Download engine.py from jejunepixels/chat-visualiser: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/spaces/jejunepixels/chat-visualiser/resolve/main/engine.py
- Command line
-
hf download hf://spaces/jejunepixels/chat-visualiser/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/jejunepixels/chat-visualiser/resolve/main/engine.py
15.7 kB
| """Causal sampling with probabilities and optional model internals.""" | |
| 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.roles = {} | |
| self.probabilities = {} | |
| self.sampling_choices = {} | |
| self.messages = [] | |
| self.message_tokens = [] | |
| self.stream_id = uuid.uuid4().hex | |
| self.space_history = [] | |
| self.similarity_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 {} | |
| def paused(self): | |
| return self._status.get("paused", False) | |
| def paused(self, value): | |
| self._status["paused"] = value | |
| def running(self): | |
| return self._status.get("running", False) | |
| def running(self, value): | |
| self._status["running"] = value | |
| def reset_requested(self): | |
| return self._status.get("reset_requested", False) | |
| def reset_requested(self, value): | |
| self._status["reset_requested"] = value | |
| def continue_automatically(self): | |
| return self._status.get("continue_automatically", False) | |
| 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 save_attention(flow, query, row, packed, keys): | |
| 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.attention_history.pop(flow.layer_queries[slot], None) | |
| flow.attention_history[query] = row | |
| flow.layer_rows[slot].copy_(packed) | |
| flow.layer_keys[slot].copy_(keys) | |
| flow.layer_queries[slot] = query | |
| def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed, | |
| context_limit=128, live_settings=None, attention_modules=None, english_prior=None, | |
| chat_context=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, prefix_indices = chat_context or ([start_id(model, tokenizer)], [-1]) | |
| reply_start = len(flow.tokens) if chat_context else 0 | |
| 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[reply_start:] | |
| visible_indices = prefix_indices + list(range(reply_start, len(flow.tokens))) | |
| query = visible_indices[-1] | |
| 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 | |
| chat_queries = {} | |
| if settings.get("attention", False): | |
| from attention_view import LayerAttentionProbe | |
| probe_options = {} | |
| if chat_context: | |
| input_indices = visible_indices[-input_ids.shape[-1]:] | |
| chat_queries = {position: n for position, n in enumerate(input_indices) | |
| if n is not None and n >= max(len(flow.tokens) - 512, | |
| flow.message_tokens[-2][0]) | |
| and n not in flow.attention_history} | |
| probe_options = {"positions": list(chat_queries), | |
| "visible_keys": [n is not None for n in visible_indices]} | |
| if not chat_context or chat_queries: | |
| probe = LayerAttentionProbe(attention_modules or [], settings.get("attention_layer", -1), | |
| settings.get("attention_head", -1), **probe_options) | |
| 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() | |
| if chat_context and emitted == 0: | |
| window_indices = visible_indices[-len(window):] | |
| for position, n in enumerate(window_indices): | |
| if n is not None and n >= flow.message_tokens[-2][0]: | |
| flow.representations.add(n, result.hidden_states, position) | |
| elif query is not None: | |
| flow.representations.add(query, result.hidden_states) | |
| if probe is not None and chat_context: | |
| for n, row, packed, keys in probe.chat_records(chat_queries.values(), visible_indices, all_ids): | |
| save_attention(flow, n, row, packed, keys) | |
| elif probe is not None and query is not None and query >= 0: | |
| row = probe.record(len(all_ids) - len(probe.row), query) | |
| for link in row["links"]: | |
| position = link["n"] + 1 | |
| link["n"] = visible_indices[position] | |
| link["id"] = all_ids[position] | |
| row["links"] = [link for link in row["links"] if link["n"] is not None] | |
| packed, keys = probe.layer_record(len(all_ids)) | |
| lookup = torch.tensor([-2, *(n if n is not None else -2 for n in visible_indices)]) | |
| packed[:, :, 0] = lookup[packed[:, :, 0].long() + 2] | |
| save_attention(flow, query, row, packed, keys) | |
| 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)) | |
| if chat_context: | |
| flow.roles[len(flow.tokens)] = "assistant" | |
| flow.probabilities[len(flow.tokens)] = float(probs[chosen]) | |
| alternatives = torch.topk(before_nucleus, min(8, len(probs))).indices.tolist() | |
| if chosen not in alternatives: | |
| alternatives.append(chosen) | |
| flow.sampling_choices[len(flow.tokens)] = { | |
| "candidates": [ | |
| {"id": candidate, "probability": float(probs[candidate]), | |
| "before_top_p": float(before_nucleus[candidate])} | |
| for candidate in alternatives | |
| ], | |
| "temperature": current_temperature, "top_p": current_top_p, | |
| } | |
| flow.tokens.append(chosen) | |
| emitted += 1 | |
| flow.rng_state = rng.get_state() | |
| flow.ended = chosen in eos_ids | |
| flow.text = tokenizer.decode(flow.tokens[reply_start:], 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 | |