automatic-writing / engine.py
jejunepixels's picture
Add optional projected original-dimension axis guides with opacity and origin controls
9d3e0c7 verified
Raw History Blame Contribute Delete
12.8 kB
"""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