Spaces:
Running
Running
Initial public commit
Browse filesCo-authored-by: mlabonne <mlabonne@users.noreply.huggingface.co>
Co-authored-by: claude opus 5 (1m context) <claude opus 5 (1m context)@users.noreply.huggingface.co>
- .dockerignore +6 -0
- .gitattributes +35 -0
- .gitignore +3 -0
- Dockerfile +29 -0
- README.md +11 -0
- app.py +120 -0
- index.html +311 -0
- lfm2_diffusion.py +428 -0
- lliquid.gif +0 -0
- requirements.txt +5 -0
- style.css +248 -0
.dockerignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.gitattributes
|
| 3 |
+
__pycache__/
|
| 4 |
+
*.pyc
|
| 5 |
+
.venv/
|
| 6 |
+
*.md
|
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.venv/
|
Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
# non-root user (HF Spaces convention; writable HOME for the HF cache the model
|
| 4 |
+
# is pulled into at boot).
|
| 5 |
+
RUN useradd -m -u 1000 user
|
| 6 |
+
USER user
|
| 7 |
+
ENV HOME=/home/user \
|
| 8 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 9 |
+
HF_HOME=/home/user/.cache/huggingface \
|
| 10 |
+
PYTHONUNBUFFERED=1 \
|
| 11 |
+
TMPDIR=/tmp
|
| 12 |
+
|
| 13 |
+
WORKDIR /home/user/app
|
| 14 |
+
|
| 15 |
+
# CPU-only torch (the default PyPI wheel is CUDA and huge).
|
| 16 |
+
RUN pip install --no-cache-dir --user torch --index-url https://download.pytorch.org/whl/cpu
|
| 17 |
+
|
| 18 |
+
COPY --chown=user requirements.txt .
|
| 19 |
+
RUN pip install --no-cache-dir --user -r requirements.txt
|
| 20 |
+
|
| 21 |
+
COPY --chown=user . .
|
| 22 |
+
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
# One worker (single shared model), threads for concurrent requests. No --preload:
|
| 26 |
+
# the worker pulls + loads the model in its own process (avoids the torch/OpenMP
|
| 27 |
+
# fork deadlock). --timeout 0 keeps the first-boot model download from tripping
|
| 28 |
+
# the worker timeout.
|
| 29 |
+
CMD ["gunicorn", "-w", "1", "--threads", "8", "-k", "gthread", "-b", "0.0.0.0:7860", "--timeout", "0", "app:app"]
|
README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Masked Diffusion
|
| 3 |
+
emoji: 🌫️
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
header: mini
|
| 9 |
+
pinned: false
|
| 10 |
+
short_description: Masked diffusion with LFM2.5 Encoder on CPU
|
| 11 |
+
---
|
app.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Masked-diffusion chat — server-side CPU inference.
|
| 2 |
+
|
| 3 |
+
The model (LFM2.5-Encoder-350M-Diffusion, f32 safetensors) is loaded once and runs
|
| 4 |
+
on the server's CPU. Nothing is downloaded to the visitor's browser: the page streams
|
| 5 |
+
denoising frames from /api/generate as newline-delimited JSON and animates them,
|
| 6 |
+
exactly like the old in-browser WebGPU build did.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import threading
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from flask import Flask, Response, request, send_from_directory, stream_with_context
|
| 15 |
+
from tokenizers import Tokenizer
|
| 16 |
+
|
| 17 |
+
import lfm2_diffusion as L
|
| 18 |
+
|
| 19 |
+
APP_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 20 |
+
# Match threads to the cores actually granted to the container (cgroup quota),
|
| 21 |
+
# not the host's core count — oversubscription badly slows CPU matmuls.
|
| 22 |
+
_CPUS = L.effective_cpus()
|
| 23 |
+
torch.set_num_threads(_CPUS)
|
| 24 |
+
try:
|
| 25 |
+
torch.set_num_interop_threads(1)
|
| 26 |
+
except RuntimeError:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
app = Flask(__name__)
|
| 30 |
+
|
| 31 |
+
# ---- load model + tokenizer once, at import (per gunicorn worker) -----------
|
| 32 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 33 |
+
print(f"[boot] pulling {L.MODEL_ID} from the Hub, loading on {_CPUS} CPU thread(s)…", flush=True)
|
| 34 |
+
from huggingface_hub import hf_hub_download
|
| 35 |
+
TOK = Tokenizer.from_file(hf_hub_download(L.MODEL_ID, "tokenizer.json", token=HF_TOKEN))
|
| 36 |
+
MODEL = L.Lfm2Diffusion.from_hub(token=HF_TOKEN)
|
| 37 |
+
print("[boot] calibrating + quantizing (smoothed int8)…", flush=True)
|
| 38 |
+
MODEL.quantize_int8([TOK.encode(L.render_chat_prompt(p)).ids for p in L.CALIB_PROMPTS])
|
| 39 |
+
_GEN_LOCK = threading.Lock()
|
| 40 |
+
# warm up the graph so the first real request is not the slow one
|
| 41 |
+
list(L.diffuse(MODEL, TOK.encode(L.render_chat_prompt("Hi")).ids,
|
| 42 |
+
max_new=8, steps=4, block_size=8))
|
| 43 |
+
print("[boot] model ready", flush=True)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _clampi(v, lo, hi, default):
|
| 47 |
+
try:
|
| 48 |
+
return max(lo, min(hi, int(float(v))))
|
| 49 |
+
except (TypeError, ValueError):
|
| 50 |
+
return default
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@app.route("/")
|
| 54 |
+
def index():
|
| 55 |
+
return send_from_directory(APP_DIR, "index.html")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@app.route("/style.css")
|
| 59 |
+
def style():
|
| 60 |
+
return send_from_directory(APP_DIR, "style.css")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@app.route("/lliquid.gif")
|
| 64 |
+
def logo():
|
| 65 |
+
return send_from_directory(APP_DIR, "lliquid.gif")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@app.route("/api/ready")
|
| 69 |
+
def ready():
|
| 70 |
+
return {"ready": MODEL is not None}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@app.route("/api/generate")
|
| 74 |
+
def generate():
|
| 75 |
+
prompt = (request.args.get("prompt") or "").strip()
|
| 76 |
+
if not prompt:
|
| 77 |
+
return {"error": "empty prompt"}, 400
|
| 78 |
+
opts = dict(
|
| 79 |
+
max_new=_clampi(request.args.get("mnt"), 16, 192, 64),
|
| 80 |
+
steps=_clampi(request.args.get("steps"), 8, 128, 32),
|
| 81 |
+
block_size=_clampi(request.args.get("blk"), 8, 64, 16),
|
| 82 |
+
temperature=_clampi(request.args.get("temp"), 0, 100, 0) / 100.0,
|
| 83 |
+
tau=_clampi(request.args.get("tau"), 50, 100, 90) / 100.0,
|
| 84 |
+
)
|
| 85 |
+
prompt_ids = TOK.encode(L.render_chat_prompt(prompt)).ids
|
| 86 |
+
|
| 87 |
+
@stream_with_context
|
| 88 |
+
def frames():
|
| 89 |
+
# Serialize generation: the CPU model handles one request at a time.
|
| 90 |
+
if not _GEN_LOCK.acquire(blocking=False):
|
| 91 |
+
yield json.dumps({"error": "The model is busy with another request. Try again in a moment."}) + "\n"
|
| 92 |
+
return
|
| 93 |
+
try:
|
| 94 |
+
last = None
|
| 95 |
+
for fr in L.diffuse(MODEL, prompt_ids, **opts):
|
| 96 |
+
last = fr["gen_ids"]
|
| 97 |
+
tokens = [None if t == L.MASK_ID
|
| 98 |
+
else TOK.decode([t], skip_special_tokens=True)
|
| 99 |
+
for t in fr["gen_ids"]]
|
| 100 |
+
yield json.dumps({
|
| 101 |
+
"step": fr["step"],
|
| 102 |
+
"tokens": tokens,
|
| 103 |
+
"revealed": sorted(fr["revealed"]),
|
| 104 |
+
}) + "\n"
|
| 105 |
+
gen = [t for t in (last or []) if t != L.MASK_ID]
|
| 106 |
+
text = L.trim(TOK.decode(gen, skip_special_tokens=True))
|
| 107 |
+
yield json.dumps({"done": True, "text": text or "(empty)"}) + "\n"
|
| 108 |
+
except Exception as exc: # surface errors to the UI
|
| 109 |
+
yield json.dumps({"error": str(exc)}) + "\n"
|
| 110 |
+
finally:
|
| 111 |
+
_GEN_LOCK.release()
|
| 112 |
+
|
| 113 |
+
return Response(frames(), mimetype="application/x-ndjson", headers={
|
| 114 |
+
"Cache-Control": "no-cache, no-transform",
|
| 115 |
+
"X-Accel-Buffering": "no",
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), threaded=True)
|
index.html
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Masked-diffusion chat · LFM2.5 Encoder</title>
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
| 10 |
+
<link rel="stylesheet" href="style.css">
|
| 11 |
+
<script>
|
| 12 |
+
// Private Space auth: HF signs the embedded iframe URL with ?__sign=<token>.
|
| 13 |
+
// Incognito / Safari block the third-party .hf.space cookie, so that token is
|
| 14 |
+
// the only credential — carry it on same-origin API requests, else /api/*
|
| 15 |
+
// returns 404 and the model-ready poll hangs at 92%.
|
| 16 |
+
(() => {
|
| 17 |
+
const sign = new URLSearchParams(location.search).get("__sign");
|
| 18 |
+
if (!sign) return;
|
| 19 |
+
const orig = self.fetch.bind(self);
|
| 20 |
+
self.fetch = (input, init) => {
|
| 21 |
+
try {
|
| 22 |
+
const u = new URL(typeof input === "string" ? input : input.url, location.href);
|
| 23 |
+
if (u.origin === location.origin && !u.searchParams.has("__sign")) {
|
| 24 |
+
u.searchParams.set("__sign", sign);
|
| 25 |
+
input = u.toString();
|
| 26 |
+
}
|
| 27 |
+
} catch (e) { /* non-URL input: pass through */ }
|
| 28 |
+
return orig(input, init);
|
| 29 |
+
};
|
| 30 |
+
})();
|
| 31 |
+
</script>
|
| 32 |
+
</head>
|
| 33 |
+
<body>
|
| 34 |
+
<div class="wrap" id="app">
|
| 35 |
+
<header class="site-intro">
|
| 36 |
+
<h1>Masked-<em>diffusion</em> chat</h1>
|
| 37 |
+
<p class="sub">Watch LFM2.5 Encoder turn masked tokens into an answer through iterative denoising.</p>
|
| 38 |
+
</header>
|
| 39 |
+
|
| 40 |
+
<section class="model-strip is-loading" id="model-strip" aria-label="Model status">
|
| 41 |
+
<span class="model-logo-frame" aria-hidden="true">
|
| 42 |
+
<img id="model-logo" class="model-logo" width="56" height="59" alt="" src="lliquid.gif">
|
| 43 |
+
</span>
|
| 44 |
+
<div class="model-copy">
|
| 45 |
+
<div class="model-name-row">
|
| 46 |
+
<a href="https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M" target="_blank" rel="noopener">LFM2.5 Encoder</a>
|
| 47 |
+
<span class="model-variant">350M parameters</span>
|
| 48 |
+
</div>
|
| 49 |
+
</div>
|
| 50 |
+
<div class="load-block">
|
| 51 |
+
<div class="load-meta">
|
| 52 |
+
<span id="status" role="status" aria-live="polite">Connecting to server…</span>
|
| 53 |
+
<span id="load-percent">0%</span>
|
| 54 |
+
</div>
|
| 55 |
+
<div class="load-track" role="progressbar" aria-label="Model loading" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span id="load-progress"></span></div>
|
| 56 |
+
</div>
|
| 57 |
+
</section>
|
| 58 |
+
|
| 59 |
+
<main>
|
| 60 |
+
<section class="diffusion-workspace" id="workspace" aria-label="Masked-diffusion generator">
|
| 61 |
+
<article class="workspace-card prompt-panel">
|
| 62 |
+
<header class="panel-header">
|
| 63 |
+
<div><h2>Prompt</h2><p>Enter an instruction or question</p></div>
|
| 64 |
+
</header>
|
| 65 |
+
|
| 66 |
+
<form id="composer">
|
| 67 |
+
<label class="sr-only" for="prompt">Prompt</label>
|
| 68 |
+
<div class="prompt-stage">
|
| 69 |
+
<textarea id="prompt" rows="5" placeholder="Ask LFM2.5 Encoder…">Give three tips for staying healthy.</textarea>
|
| 70 |
+
<div class="prompt-scan" aria-hidden="true"></div>
|
| 71 |
+
</div>
|
| 72 |
+
<div class="composer-row">
|
| 73 |
+
<span>Enter to diffuse · Shift + Enter for a new line</span>
|
| 74 |
+
<button id="go" type="submit" disabled><span>Diffuse</span><i aria-hidden="true">→</i></button>
|
| 75 |
+
</div>
|
| 76 |
+
</form>
|
| 77 |
+
|
| 78 |
+
<div class="settings-heading"><h3>Generation settings</h3><span>Customize the denoising path</span></div>
|
| 79 |
+
<div class="settings-grid">
|
| 80 |
+
<label class="range-control" for="steps"><span>Step budget</span><output id="stepsV" for="steps">32</output><input type="range" id="steps" min="8" max="128" step="8" value="32"></label>
|
| 81 |
+
<label class="range-control" for="mnt"><span>Max tokens</span><output id="mntV" for="mnt">64</output><input type="range" id="mnt" min="16" max="192" step="16" value="64"></label>
|
| 82 |
+
<label class="range-control" for="blk"><span>Block size</span><output id="blkV" for="blk">16</output><input type="range" id="blk" min="8" max="64" step="8" value="16"></label>
|
| 83 |
+
<label class="range-control" for="temp"><span>Temperature</span><output id="tempV" for="temp">0.00</output><input type="range" id="temp" min="0" max="100" step="5" value="0"></label>
|
| 84 |
+
<label class="range-control range-wide" for="tau"><span>Confidence reveal</span><output id="tauV" for="tau">0.90</output><input type="range" id="tau" min="50" max="100" step="5" value="90"></label>
|
| 85 |
+
</div>
|
| 86 |
+
</article>
|
| 87 |
+
|
| 88 |
+
<article class="workspace-card response-panel">
|
| 89 |
+
<header class="panel-header response-heading">
|
| 90 |
+
<div><h2>Response</h2></div>
|
| 91 |
+
<span class="activity-pill" id="activity"><i></i><span id="activityText">Ready</span></span>
|
| 92 |
+
</header>
|
| 93 |
+
|
| 94 |
+
<div class="response-stage" id="responseStage" aria-live="polite">
|
| 95 |
+
<div class="response-scan" aria-hidden="true"></div>
|
| 96 |
+
<div class="empty-state" id="emptyState">
|
| 97 |
+
<div class="idle-orbit" aria-hidden="true"><span></span><i></i></div>
|
| 98 |
+
<strong>Ready to denoise</strong>
|
| 99 |
+
<p>Your answer will emerge here, token by token.</p>
|
| 100 |
+
<div class="idle-masks" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span><span></span></div>
|
| 101 |
+
</div>
|
| 102 |
+
<article class="assistant-message" id="assistantMessage" hidden>
|
| 103 |
+
<div id="canvas" class="canvas"></div>
|
| 104 |
+
<div class="generation-meta">
|
| 105 |
+
<div class="step-track"><span id="stepProgress"></span></div>
|
| 106 |
+
<div class="stats" id="live"></div>
|
| 107 |
+
</div>
|
| 108 |
+
</article>
|
| 109 |
+
</div>
|
| 110 |
+
</article>
|
| 111 |
+
</section>
|
| 112 |
+
|
| 113 |
+
<section class="examples-panel" aria-label="Example prompts">
|
| 114 |
+
<span class="examples-label">Examples</span>
|
| 115 |
+
<div class="example-list">
|
| 116 |
+
<button type="button" class="ex active" data-q="Give three tips for staying healthy.">Health tips</button>
|
| 117 |
+
<button type="button" class="ex" data-q="Explain what a black hole is to a five-year-old.">Black hole</button>
|
| 118 |
+
<button type="button" class="ex" data-q="Write a short poem about the ocean.">Ocean poem</button>
|
| 119 |
+
<button type="button" class="ex" data-q="What are the primary colors?">Primary colors</button>
|
| 120 |
+
<button type="button" class="ex" data-q="Give me a concise guide to brewing green tea.">Green tea</button>
|
| 121 |
+
<button type="button" class="ex" data-q="Explain why this loop never stops: while (x > 0) { x++; }">Debug a loop</button>
|
| 122 |
+
</div>
|
| 123 |
+
</section>
|
| 124 |
+
</main>
|
| 125 |
+
</div>
|
| 126 |
+
|
| 127 |
+
<script type="module">
|
| 128 |
+
// The model runs on the server (CPU). This script only drives the UI and
|
| 129 |
+
// streams denoising frames from /api/generate as newline-delimited JSON.
|
| 130 |
+
|
| 131 |
+
const MASK = null; // the server sends null for a still-masked position
|
| 132 |
+
const $ = (id) => document.getElementById(id);
|
| 133 |
+
|
| 134 |
+
const setLoadProgress = (percent) => {
|
| 135 |
+
const value = Math.max(0, Math.min(100, percent));
|
| 136 |
+
$("load-progress").style.width = `${value}%`;
|
| 137 |
+
$("load-percent").textContent = `${Math.round(value)}%`;
|
| 138 |
+
document.querySelector(".load-track").setAttribute("aria-valuenow", String(Math.round(value)));
|
| 139 |
+
};
|
| 140 |
+
const setStatus = (message, state = "loading") => {
|
| 141 |
+
$("status").textContent = message;
|
| 142 |
+
const badge = $("model-strip");
|
| 143 |
+
badge.classList.toggle("is-loading", state === "loading");
|
| 144 |
+
badge.classList.toggle("is-preparing", state === "preparing");
|
| 145 |
+
badge.classList.toggle("is-ready", state === "ready");
|
| 146 |
+
badge.classList.toggle("is-error", state === "error");
|
| 147 |
+
};
|
| 148 |
+
function updateRangeFill(el) {
|
| 149 |
+
const pct = ((+el.value - +el.min) / (+el.max - +el.min)) * 100;
|
| 150 |
+
el.style.setProperty("--pct", `${pct}%`);
|
| 151 |
+
}
|
| 152 |
+
for (const [s, l] of [["steps","stepsV"],["mnt","mntV"],["blk","blkV"]])
|
| 153 |
+
$(s).oninput = () => { updateRangeFill($(s)); $(l).textContent = $(s).value; };
|
| 154 |
+
$("temp").oninput = () => { updateRangeFill($("temp")); $("tempV").textContent = ($("temp").value / 100).toFixed(2); };
|
| 155 |
+
$("tau").oninput = () => { updateRangeFill($("tau")); $("tauV").textContent = ($("tau").value / 100).toFixed(2); };
|
| 156 |
+
document.querySelectorAll("input[type=range]").forEach(updateRangeFill);
|
| 157 |
+
|
| 158 |
+
// ---------- wait for the server-side model to be ready ----------
|
| 159 |
+
async function waitForServer() {
|
| 160 |
+
setStatus("Connecting to server…", "loading");
|
| 161 |
+
setLoadProgress(12);
|
| 162 |
+
for (let attempt = 0; attempt < 900; attempt++) {
|
| 163 |
+
try {
|
| 164 |
+
const r = await fetch("api/ready", { cache: "no-store" });
|
| 165 |
+
if (r.ok && (await r.json()).ready) return true;
|
| 166 |
+
} catch (e) { /* server still starting */ }
|
| 167 |
+
setStatus("Warming up model on the server…", "preparing");
|
| 168 |
+
setLoadProgress(Math.min(92, 12 + attempt * 4));
|
| 169 |
+
await new Promise((r) => setTimeout(r, 1000));
|
| 170 |
+
}
|
| 171 |
+
return false;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
(async () => {
|
| 175 |
+
const ok = await waitForServer();
|
| 176 |
+
if (ok) {
|
| 177 |
+
setLoadProgress(100);
|
| 178 |
+
setStatus("Model ready", "ready");
|
| 179 |
+
$("go").disabled = false;
|
| 180 |
+
} else {
|
| 181 |
+
setStatus("Model unavailable", "error");
|
| 182 |
+
setLoadProgress(100);
|
| 183 |
+
$("load-percent").textContent = "Error";
|
| 184 |
+
}
|
| 185 |
+
})();
|
| 186 |
+
|
| 187 |
+
// ---------- rendering ----------
|
| 188 |
+
const escapeHtml = (s) => s.replace(/&/g, "&").replace(/</g, "<");
|
| 189 |
+
function render(tokens, revealed) {
|
| 190 |
+
const revealedSet = new Set(revealed);
|
| 191 |
+
const parts = [];
|
| 192 |
+
for (let i = 0; i < tokens.length; i++) {
|
| 193 |
+
if (tokens[i] === MASK) {
|
| 194 |
+
parts.push(`<span class="mask" style="--token-index:${i}" aria-label="masked token"><MASK></span>`);
|
| 195 |
+
continue;
|
| 196 |
+
}
|
| 197 |
+
const esc = escapeHtml(tokens[i] || "·");
|
| 198 |
+
parts.push(`<span class="tok${revealedSet.has(i) ? " new" : ""}" style="--token-index:${i}">${esc}</span>`);
|
| 199 |
+
}
|
| 200 |
+
$("canvas").innerHTML = parts.join("");
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
// ---------- streamed generation ----------
|
| 204 |
+
async function generate(userText) {
|
| 205 |
+
const maxNew = +$("mnt").value;
|
| 206 |
+
const params = new URLSearchParams({
|
| 207 |
+
prompt: userText,
|
| 208 |
+
mnt: $("mnt").value, steps: $("steps").value, blk: $("blk").value,
|
| 209 |
+
temp: $("temp").value, tau: $("tau").value,
|
| 210 |
+
});
|
| 211 |
+
const t0 = performance.now();
|
| 212 |
+
const resp = await fetch("api/generate?" + params.toString());
|
| 213 |
+
if (!resp.ok || !resp.body) throw new Error(`HTTP ${resp.status}`);
|
| 214 |
+
|
| 215 |
+
const reader = resp.body.getReader();
|
| 216 |
+
const decoder = new TextDecoder();
|
| 217 |
+
let buffer = "", steps = 0, finalText = null;
|
| 218 |
+
for (;;) {
|
| 219 |
+
const { done, value } = await reader.read();
|
| 220 |
+
if (done) break;
|
| 221 |
+
buffer += decoder.decode(value, { stream: true });
|
| 222 |
+
let nl;
|
| 223 |
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
| 224 |
+
const line = buffer.slice(0, nl).trim();
|
| 225 |
+
buffer = buffer.slice(nl + 1);
|
| 226 |
+
if (!line) continue;
|
| 227 |
+
const msg = JSON.parse(line);
|
| 228 |
+
if (msg.error) throw new Error(msg.error);
|
| 229 |
+
if (msg.done) { finalText = msg.text; continue; }
|
| 230 |
+
steps = msg.step;
|
| 231 |
+
render(msg.tokens, msg.revealed);
|
| 232 |
+
const doneCount = msg.tokens.filter((t) => t !== MASK).length;
|
| 233 |
+
const dt = (performance.now() - t0) / 1000;
|
| 234 |
+
const progress = doneCount / maxNew * 100;
|
| 235 |
+
$("stepProgress").style.width = `${progress}%`;
|
| 236 |
+
$("activityText").textContent = `Denoising · ${Math.round(progress)}%`;
|
| 237 |
+
$("live").textContent = `Step ${msg.step} · ${doneCount}/${maxNew} tokens · ${dt.toFixed(2)}s · ${(doneCount / Math.max(dt, .01)).toFixed(0)} tok/s`;
|
| 238 |
+
await new Promise((r) => requestAnimationFrame(r));
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
const totalS = (performance.now() - t0) / 1000;
|
| 242 |
+
return { text: finalText ?? "", totalS, steps, msPerStep: totalS * 1000 / Math.max(steps, 1), tokPerS: maxNew / totalS };
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
$("composer").addEventListener("submit", async (event) => {
|
| 246 |
+
event.preventDefault();
|
| 247 |
+
const userText = $("prompt").value.trim();
|
| 248 |
+
if (!userText || $("go").disabled) return;
|
| 249 |
+
|
| 250 |
+
$("assistantMessage").hidden = false;
|
| 251 |
+
$("emptyState").hidden = true;
|
| 252 |
+
$("canvas").innerHTML = Array.from({ length: +$("mnt").value }, (_, i) => `<span class="mask" style="--token-index:${i}" aria-label="masked token"><MASK></span>`).join("");
|
| 253 |
+
$("live").textContent = "Starting diffusion…";
|
| 254 |
+
$("stepProgress").style.width = "0%";
|
| 255 |
+
$("assistantMessage").setAttribute("aria-busy", "true");
|
| 256 |
+
$("workspace").classList.add("is-generating");
|
| 257 |
+
$("responseStage").classList.add("is-denoising");
|
| 258 |
+
$("responseStage").classList.remove("is-complete");
|
| 259 |
+
$("activity").className = "activity-pill is-running";
|
| 260 |
+
$("activityText").textContent = "Building canvas";
|
| 261 |
+
$("go").disabled = true;
|
| 262 |
+
$("go").querySelector("span").textContent = "Denoising";
|
| 263 |
+
try {
|
| 264 |
+
const r = await generate(userText);
|
| 265 |
+
$("canvas").textContent = r.text || "(empty)";
|
| 266 |
+
$("stepProgress").style.width = "100%";
|
| 267 |
+
$("live").textContent = `${r.steps} steps · ${r.totalS.toFixed(2)}s · ${r.msPerStep.toFixed(0)} ms/step · ${r.tokPerS.toFixed(0)} tok/s`;
|
| 268 |
+
$("activity").className = "activity-pill is-done";
|
| 269 |
+
$("activityText").textContent = "Complete";
|
| 270 |
+
$("responseStage").classList.add("is-complete");
|
| 271 |
+
window.__LAST_GEN = r;
|
| 272 |
+
} catch (e) {
|
| 273 |
+
$("canvas").textContent = "Error: " + (e.message || e);
|
| 274 |
+
$("activity").className = "activity-pill is-error";
|
| 275 |
+
$("activityText").textContent = "Could not finish";
|
| 276 |
+
console.error(e);
|
| 277 |
+
}
|
| 278 |
+
$("assistantMessage").removeAttribute("aria-busy");
|
| 279 |
+
$("workspace").classList.remove("is-generating");
|
| 280 |
+
$("responseStage").classList.remove("is-denoising");
|
| 281 |
+
$("go").disabled = false;
|
| 282 |
+
$("go").querySelector("span").textContent = "Diffuse";
|
| 283 |
+
setTimeout(() => $("responseStage").classList.remove("is-complete"), 900);
|
| 284 |
+
});
|
| 285 |
+
|
| 286 |
+
$("prompt").addEventListener("keydown", (event) => {
|
| 287 |
+
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
|
| 288 |
+
event.preventDefault();
|
| 289 |
+
$("composer").requestSubmit();
|
| 290 |
+
}
|
| 291 |
+
});
|
| 292 |
+
|
| 293 |
+
document.querySelector(".example-list").addEventListener("click", (event) => {
|
| 294 |
+
const option = event.target.closest(".ex");
|
| 295 |
+
if (!option) return;
|
| 296 |
+
document.querySelectorAll(".ex").forEach((el) => el.classList.toggle("active", el === option));
|
| 297 |
+
$("prompt").value = option.dataset.q || "";
|
| 298 |
+
$("prompt").dispatchEvent(new Event("input", { bubbles: true }));
|
| 299 |
+
document.querySelector(".prompt-panel").classList.remove("example-changed");
|
| 300 |
+
requestAnimationFrame(() => document.querySelector(".prompt-panel").classList.add("example-changed"));
|
| 301 |
+
});
|
| 302 |
+
|
| 303 |
+
$("prompt").addEventListener("input", () => {
|
| 304 |
+
const active = document.querySelector(".ex.active");
|
| 305 |
+
if (!active?.dataset.q || active.dataset.q !== $("prompt").value) {
|
| 306 |
+
document.querySelectorAll(".ex").forEach((el) => el.classList.remove("active"));
|
| 307 |
+
}
|
| 308 |
+
});
|
| 309 |
+
</script>
|
| 310 |
+
</body>
|
| 311 |
+
</html>
|
lfm2_diffusion.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""lfm2_diffusion.py — CPU (PyTorch) masked-diffusion inference for LFM2.5 Encoder.
|
| 2 |
+
|
| 3 |
+
Server-side replacement for the old in-browser WebGPU path. The model, decode
|
| 4 |
+
loop, and numerics are a 1:1 port of the reference JS (lfm2_webgpu_forward.js /
|
| 5 |
+
lfm2_bidir_mdlm.js): a *bidirectional* LFM2 forward, then the block-scheduled,
|
| 6 |
+
confidence-driven MDLM unmasking loop.
|
| 7 |
+
|
| 8 |
+
Speed comes from three things:
|
| 9 |
+
* fast-dLLM "DualCache" (as in the WebGPU build): the first step of each block
|
| 10 |
+
runs a full-canvas forward that fills a per-layer K/V cache (attention) and Bx
|
| 11 |
+
cache (shortconv); every later step of that block only recomputes the active
|
| 12 |
+
~block-size slice, attending to / convolving against the frozen cache.
|
| 13 |
+
* smoothed int8 dynamic quantization of every matmul (see `quantize_int8`).
|
| 14 |
+
* one worker thread per available core (cgroup-aware, no oversubscription).
|
| 15 |
+
|
| 16 |
+
The checkpoint is pulled from the Hub model repo at boot (no local copy);
|
| 17 |
+
everything runs on CPU so nothing is downloaded to the client.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import math
|
| 22 |
+
import re
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from huggingface_hub import hf_hub_download
|
| 28 |
+
from safetensors.torch import load_file
|
| 29 |
+
|
| 30 |
+
# The perfectblend diffusion-SFT checkpoint (f32 safetensors). It is the encoder
|
| 31 |
+
# turned into an MDLM chatbot — the *base* LFM2.5-Encoder-350M is a plain MLM and
|
| 32 |
+
# echoes instead of answering, so it is not interchangeable here.
|
| 33 |
+
MODEL_ID = os.environ.get("DIFFUSION_MODEL", "LiquidAI/LFM2.5-Encoder-350M-Diffusion")
|
| 34 |
+
WEIGHTS_FILE = os.environ.get("DIFFUSION_WEIGHTS", "model.safetensors")
|
| 35 |
+
|
| 36 |
+
# --- architecture constants (LFM2.5-Encoder-350M), mirrored from the JS ------
|
| 37 |
+
H = 1024 # hidden size
|
| 38 |
+
NL = 16 # layers
|
| 39 |
+
NH = 16 # attention heads
|
| 40 |
+
NKV = 8 # kv heads (GQA group size 2)
|
| 41 |
+
HD = 64 # head dim
|
| 42 |
+
FF = 4608 # ffn inner size
|
| 43 |
+
EPS = 1e-5
|
| 44 |
+
ROPE_THETA = 1e6
|
| 45 |
+
ATTN_LAYERS = frozenset({2, 5, 8, 10, 12, 14}) # the rest are shortconv layers
|
| 46 |
+
|
| 47 |
+
# --- MDLM / tokenizer constants (see the model card) -------------------------
|
| 48 |
+
MASK_ID = 16 # <|mask|>
|
| 49 |
+
REAL_VOCAB = 64402 # ignore logit ids >= REAL_VOCAB (padded vocab is 65536)
|
| 50 |
+
|
| 51 |
+
# --- int8 smoothing (see Lfm2Diffusion.quantize_int8) ------------------------
|
| 52 |
+
SMOOTH_ALPHA = 0.5
|
| 53 |
+
# Fixed calibration set, only used to measure per-channel activation ranges (one
|
| 54 |
+
# forward each, ~1s at boot). app.py tokenizes these.
|
| 55 |
+
CALIB_PROMPTS = (
|
| 56 |
+
"What is the capital of France?",
|
| 57 |
+
"Write a haiku about the ocean.",
|
| 58 |
+
"Give me two tips for better sleep.",
|
| 59 |
+
"What is 12 times 8?",
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def effective_cpus():
|
| 64 |
+
"""Cores actually available to this process (cgroup quota, not the host)."""
|
| 65 |
+
try: # cgroup v2
|
| 66 |
+
raw = open("/sys/fs/cgroup/cpu.max").read().split()
|
| 67 |
+
if raw and raw[0] != "max":
|
| 68 |
+
return max(1, round(int(raw[0]) / int(raw[1])))
|
| 69 |
+
except (OSError, ValueError):
|
| 70 |
+
pass
|
| 71 |
+
try: # cgroup v1
|
| 72 |
+
q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read())
|
| 73 |
+
p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read())
|
| 74 |
+
if q > 0:
|
| 75 |
+
return max(1, q // p)
|
| 76 |
+
except (OSError, ValueError):
|
| 77 |
+
pass
|
| 78 |
+
try:
|
| 79 |
+
return max(1, len(os.sched_getaffinity(0)))
|
| 80 |
+
except AttributeError:
|
| 81 |
+
return os.cpu_count() or 1
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def render_chat_prompt(user_text, system_text=None):
|
| 85 |
+
"""LFM2 chat template for a single user turn + add_generation_prompt."""
|
| 86 |
+
s = ""
|
| 87 |
+
if system_text:
|
| 88 |
+
s += f"[SYS]\n{system_text.strip()}\n[/SYS]\n\n"
|
| 89 |
+
s += f"[Question]\n{user_text.strip()}\n[/Question]\n\n[Answer]\n"
|
| 90 |
+
return s
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def trim(text):
|
| 94 |
+
"""Cut generated text at the answer terminator / role markers (app.py trim)."""
|
| 95 |
+
for stop in ("[/Answer]", "[Question]", "[SYS]"):
|
| 96 |
+
i = text.find(stop)
|
| 97 |
+
if i != -1:
|
| 98 |
+
text = text[:i]
|
| 99 |
+
text = text.strip()
|
| 100 |
+
text = re.sub(r"^(?:\[Answer\]|Answer\b)\s*:?\s*", "", text, flags=re.I)
|
| 101 |
+
text = re.sub(r"\s*(?:\.{3}|…)\s*$", "", text)
|
| 102 |
+
return text.strip()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def load_hf_tensors(path):
|
| 106 |
+
"""Load the safetensors checkpoint — weights are already f32 and [out, in], so
|
| 107 |
+
there is nothing to dequantize or transpose. The dimension check makes a
|
| 108 |
+
checkpoint that doesn't match the constants above fail loudly at boot rather
|
| 109 |
+
than as silent garbage."""
|
| 110 |
+
t = load_file(path)
|
| 111 |
+
attn = frozenset(int(m.group(1)) for k in t
|
| 112 |
+
if (m := re.match(r"lfm2\.layers\.(\d+)\.self_attn\.", k)))
|
| 113 |
+
a = min(attn)
|
| 114 |
+
got = (t["lfm2.embed_tokens.weight"].shape[1],
|
| 115 |
+
1 + max(int(m.group(1)) for k in t if (m := re.match(r"lfm2\.layers\.(\d+)\.", k))),
|
| 116 |
+
attn,
|
| 117 |
+
t["lfm2.layers.0.feed_forward.w1.weight"].shape[0],
|
| 118 |
+
t[f"lfm2.layers.{a}.self_attn.q_proj.weight"].shape[0],
|
| 119 |
+
t[f"lfm2.layers.{a}.self_attn.k_proj.weight"].shape[0])
|
| 120 |
+
want = (H, NL, ATTN_LAYERS, FF, NH * HD, NKV * HD)
|
| 121 |
+
if got != want:
|
| 122 |
+
raise ValueError(f"{path}: (hidden, layers, attn layers, ffn, q, kv) is {got}, expected {want}")
|
| 123 |
+
return t
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class RowScaledLinear(nn.Module):
|
| 127 |
+
"""Per-token activations around a dynamically quantized Linear.
|
| 128 |
+
|
| 129 |
+
The int8 kernel derives ONE activation scale per call, so a single loud token
|
| 130 |
+
coarsens every other row in the batch. Normalising each row to unit max first
|
| 131 |
+
(and putting the scale back on the output) makes that one scale exactly right
|
| 132 |
+
for every row, which is per-token quantization at the cost of two elementwise
|
| 133 |
+
passes."""
|
| 134 |
+
|
| 135 |
+
def __init__(self, qlin):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.q = qlin
|
| 138 |
+
|
| 139 |
+
def forward(self, x):
|
| 140 |
+
r = x.abs().amax(-1, keepdim=True).clamp_min(1e-6)
|
| 141 |
+
return self.q(x / r) * r
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def rms_norm(x, w, eps=EPS):
|
| 145 |
+
inv = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
|
| 146 |
+
return x * inv * w
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _linear(in_f, out_f, weight):
|
| 150 |
+
m = nn.Linear(in_f, out_f, bias=False)
|
| 151 |
+
m.weight.data = weight.contiguous()
|
| 152 |
+
return m
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class Lfm2Layer(nn.Module):
|
| 156 |
+
def __init__(self, t, li):
|
| 157 |
+
super().__init__()
|
| 158 |
+
p = f"lfm2.layers.{li}."
|
| 159 |
+
self.attn = li in ATTN_LAYERS
|
| 160 |
+
self.register_buffer("op_norm", t[p + "operator_norm.weight"], persistent=False)
|
| 161 |
+
self.register_buffer("ffn_norm", t[p + "ffn_norm.weight"], persistent=False)
|
| 162 |
+
# fused gate+up: one GEMM instead of two
|
| 163 |
+
self.w13 = _linear(H, 2 * FF, torch.cat(
|
| 164 |
+
[t[p + "feed_forward.w1.weight"], t[p + "feed_forward.w3.weight"]], 0))
|
| 165 |
+
self.w2 = _linear(FF, H, t[p + "feed_forward.w2.weight"])
|
| 166 |
+
if self.attn:
|
| 167 |
+
self.qkv = _linear(H, H + 2 * NKV * HD, torch.cat(
|
| 168 |
+
[t[p + "self_attn.q_proj.weight"], t[p + "self_attn.k_proj.weight"],
|
| 169 |
+
t[p + "self_attn.v_proj.weight"]], 0))
|
| 170 |
+
self.o = _linear(H, H, t[p + "self_attn.out_proj.weight"])
|
| 171 |
+
self.register_buffer("q_norm", t[p + "self_attn.q_layernorm.weight"], persistent=False)
|
| 172 |
+
self.register_buffer("k_norm", t[p + "self_attn.k_layernorm.weight"], persistent=False)
|
| 173 |
+
else:
|
| 174 |
+
self.register_buffer("conv", t[p + "conv.conv.weight"].reshape(H, 1, -1), persistent=False)
|
| 175 |
+
self.in_proj = _linear(H, 3 * H, t[p + "conv.in_proj.weight"])
|
| 176 |
+
self.out_proj = _linear(H, H, t[p + "conv.out_proj.weight"])
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Lfm2Diffusion(nn.Module):
|
| 180 |
+
"""Takes ownership of `tensors`: most weights are used without copying, and
|
| 181 |
+
quantize_int8 rescales them in place."""
|
| 182 |
+
|
| 183 |
+
def __init__(self, tensors):
|
| 184 |
+
super().__init__()
|
| 185 |
+
t = tensors
|
| 186 |
+
self.register_buffer("emb", t["lfm2.embed_tokens.weight"].contiguous(), persistent=False)
|
| 187 |
+
self.register_buffer("emb_norm", t["lfm2.embedding_norm.weight"], persistent=False)
|
| 188 |
+
# tied logits, trimmed to the real vocab (ids >= REAL_VOCAB are suppressed
|
| 189 |
+
# anyway, so there's no point computing the padded tail every step). Cloned,
|
| 190 |
+
# not shared with `emb`: quantize_int8 rescales the head's columns in place.
|
| 191 |
+
self.lm_head = _linear(H, REAL_VOCAB, t["lfm2.embed_tokens.weight"][:REAL_VOCAB].clone())
|
| 192 |
+
self.layers = nn.ModuleList([Lfm2Layer(t, li) for li in range(NL)])
|
| 193 |
+
self.eval()
|
| 194 |
+
|
| 195 |
+
i = torch.arange(HD // 2, dtype=torch.float32)
|
| 196 |
+
ang = torch.arange(1024, dtype=torch.float32)[:, None] * torch.pow(ROPE_THETA, -2.0 * i / HD)[None, :]
|
| 197 |
+
self.rope_cos, self.rope_sin = torch.cos(ang), torch.sin(ang)
|
| 198 |
+
|
| 199 |
+
@classmethod
|
| 200 |
+
def from_hub(cls, token=None):
|
| 201 |
+
path = hf_hub_download(MODEL_ID, WEIGHTS_FILE, token=token)
|
| 202 |
+
return cls(load_hf_tensors(path))
|
| 203 |
+
|
| 204 |
+
# --- int8 -----------------------------------------------------------------
|
| 205 |
+
def _calibrate(self, calib_ids):
|
| 206 |
+
"""Per-channel |activation| maxima at every Linear input, from one forward
|
| 207 |
+
per calibration prompt over the canvas a first decode step actually sees
|
| 208 |
+
(prompt + an all-masked answer). Running whole generations instead is 3x
|
| 209 |
+
slower at boot and no more accurate."""
|
| 210 |
+
act = {}
|
| 211 |
+
|
| 212 |
+
def hook(name):
|
| 213 |
+
def f(_mod, inp, _out):
|
| 214 |
+
a = inp[0].detach().abs().amax(0)
|
| 215 |
+
act[name] = a if name not in act else torch.maximum(act[name], a)
|
| 216 |
+
return f
|
| 217 |
+
|
| 218 |
+
handles = [m.register_forward_hook(hook(n))
|
| 219 |
+
for n, m in self.named_modules() if isinstance(m, nn.Linear)]
|
| 220 |
+
try:
|
| 221 |
+
for ids in calib_ids:
|
| 222 |
+
P, T = len(ids), len(ids) + 64
|
| 223 |
+
x = torch.full((T,), MASK_ID, dtype=torch.long)
|
| 224 |
+
x[:P] = torch.tensor(ids, dtype=torch.long)
|
| 225 |
+
self.forward(x, list(range(P, T)), self.new_state(T))
|
| 226 |
+
finally:
|
| 227 |
+
for h in handles:
|
| 228 |
+
h.remove()
|
| 229 |
+
return act
|
| 230 |
+
|
| 231 |
+
def quantize_int8(self, calib_ids):
|
| 232 |
+
"""Smooth per-channel activation outliers into the weights, then quantize.
|
| 233 |
+
|
| 234 |
+
Dynamic int8 (onednn/fbgemm) is the only fast int8 path on CPU, but it
|
| 235 |
+
scales activations per *tensor*, and this model's post-norm activations have
|
| 236 |
+
per-channel outliers that hijack that single scale — plain int8 costs ~35%
|
| 237 |
+
of the argmaxes, which iterative unmasking then compounds into visibly worse
|
| 238 |
+
answers. So do SmoothQuant first: pull a per-channel factor s out of each
|
| 239 |
+
Linear's input and into whatever produced it, which is exact algebra, and
|
| 240 |
+
the activations quantize cleanly at no runtime cost."""
|
| 241 |
+
act = self._calibrate(calib_ids)
|
| 242 |
+
|
| 243 |
+
def smooth(lin, act_max, absorb, group=1):
|
| 244 |
+
"""s = max|x|^a / max|w|^(1-a), folded into lin's columns and, inverted,
|
| 245 |
+
into the producer. `group` shares one factor across neighbouring input
|
| 246 |
+
channels (GQA: several query heads read the same kv channel)."""
|
| 247 |
+
w_max = lin.weight.abs().amax(0)
|
| 248 |
+
if group > 1:
|
| 249 |
+
act_max = act_max.view(-1, group, HD).amax(1)
|
| 250 |
+
w_max = w_max.view(-1, group, HD).amax(1)
|
| 251 |
+
s = (act_max.clamp_min(1e-5) ** SMOOTH_ALPHA /
|
| 252 |
+
w_max.clamp_min(1e-5) ** (1 - SMOOTH_ALPHA)).clamp(1e-2, 1e2)
|
| 253 |
+
cols = s[:, None, :].expand(-1, group, HD).reshape(-1) if group > 1 else s
|
| 254 |
+
lin.weight.data *= cols
|
| 255 |
+
absorb(s)
|
| 256 |
+
|
| 257 |
+
for li, layer in enumerate(self.layers):
|
| 258 |
+
n = f"layers.{li}."
|
| 259 |
+
smooth(layer.w13, act[n + "w13"], lambda s: layer.ffn_norm.div_(s))
|
| 260 |
+
# w2 reads silu(gate) * up, so its factor folds into the up rows.
|
| 261 |
+
smooth(layer.w2, act[n + "w2"], lambda s: layer.w13.weight.data[FF:].div_(s[:, None]))
|
| 262 |
+
if layer.attn:
|
| 263 |
+
smooth(layer.qkv, act[n + "qkv"], lambda s: layer.op_norm.div_(s))
|
| 264 |
+
# o reads the attention output, i.e. the v channels repeated across
|
| 265 |
+
# each GQA group, so one factor per kv channel folds into the v rows.
|
| 266 |
+
smooth(layer.o, act[n + "o"], group=NH // NKV,
|
| 267 |
+
absorb=lambda s: layer.qkv.weight.data[H + NKV * HD:].div_(s.reshape(-1, 1)))
|
| 268 |
+
else:
|
| 269 |
+
smooth(layer.in_proj, act[n + "in_proj"], lambda s: layer.op_norm.div_(s))
|
| 270 |
+
# out_proj reads C * conv(Bx); the conv is depthwise, so its
|
| 271 |
+
# per-channel kernel absorbs the factor (the Bx cache is untouched).
|
| 272 |
+
smooth(layer.out_proj, act[n + "out_proj"], lambda s: layer.conv.div_(s[:, None, None]))
|
| 273 |
+
smooth(self.lm_head, act["lm_head"], lambda s: self.emb_norm.div_(s))
|
| 274 |
+
|
| 275 |
+
for eng in ("fbgemm", "onednn", "qnnpack"):
|
| 276 |
+
if eng in torch.backends.quantized.supported_engines:
|
| 277 |
+
torch.backends.quantized.engine = eng
|
| 278 |
+
break
|
| 279 |
+
torch.ao.quantization.quantize_dynamic(
|
| 280 |
+
self, {nn.Linear: torch.ao.quantization.per_channel_dynamic_qconfig},
|
| 281 |
+
dtype=torch.qint8, inplace=True)
|
| 282 |
+
# collect first: wrapping while walking would descend into the wrappers
|
| 283 |
+
todo = [(mod, name, child) for mod in self.modules()
|
| 284 |
+
for name, child in mod.named_children()
|
| 285 |
+
if isinstance(child, torch.ao.nn.quantized.dynamic.Linear)]
|
| 286 |
+
for mod, name, child in todo:
|
| 287 |
+
setattr(mod, name, RowScaledLinear(child))
|
| 288 |
+
return self
|
| 289 |
+
|
| 290 |
+
def _rope(self, x, pos):
|
| 291 |
+
cos = self.rope_cos[pos][:, None, :]
|
| 292 |
+
sin = self.rope_sin[pos][:, None, :]
|
| 293 |
+
x1, x2 = x[..., :HD // 2], x[..., HD // 2:]
|
| 294 |
+
return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
|
| 295 |
+
|
| 296 |
+
def new_state(self, T):
|
| 297 |
+
"""Per-generation DualCache: frozen K/V (attn) and Bx (conv) per layer."""
|
| 298 |
+
st = []
|
| 299 |
+
for L in self.layers:
|
| 300 |
+
if L.attn:
|
| 301 |
+
st.append({"k": torch.zeros(T, NKV, HD), "v": torch.zeros(T, NKV, HD)})
|
| 302 |
+
else:
|
| 303 |
+
st.append({"bx": torch.zeros(T, H)})
|
| 304 |
+
return st
|
| 305 |
+
|
| 306 |
+
def _conv_slice(self, bx_cache, conv_w, s0, length):
|
| 307 |
+
T = bx_cache.shape[0]
|
| 308 |
+
left = bx_cache[s0 - 1] if s0 - 1 >= 0 else torch.zeros(H)
|
| 309 |
+
right = bx_cache[s0 + length] if s0 + length < T else torch.zeros(H)
|
| 310 |
+
padded = torch.cat([left[None], bx_cache[s0:s0 + length], right[None]], 0)
|
| 311 |
+
out = F.conv1d(padded.t().unsqueeze(0), conv_w, padding=0, groups=H)
|
| 312 |
+
return out.squeeze(0).t()
|
| 313 |
+
|
| 314 |
+
@torch.inference_mode()
|
| 315 |
+
def forward(self, ids, rows, st, s0=None, length=None):
|
| 316 |
+
"""Full refresh (s0 is None) fills the caches over all T; a slice step
|
| 317 |
+
(s0, length) recomputes only [s0, s0+length) against the frozen cache.
|
| 318 |
+
rows: absolute positions to return logits for -> (len(rows), REAL_VOCAB)."""
|
| 319 |
+
T = ids.shape[0]
|
| 320 |
+
if s0 is None:
|
| 321 |
+
s0, length = 0, T
|
| 322 |
+
pos = torch.arange(s0, s0 + length)
|
| 323 |
+
h = self.emb[ids[s0:s0 + length]]
|
| 324 |
+
|
| 325 |
+
for L, cache in zip(self.layers, st):
|
| 326 |
+
xn = rms_norm(h, L.op_norm)
|
| 327 |
+
if L.attn:
|
| 328 |
+
qkv = L.qkv(xn)
|
| 329 |
+
q = qkv[:, :H].view(length, NH, HD)
|
| 330 |
+
k = qkv[:, H:H + NKV * HD].view(length, NKV, HD)
|
| 331 |
+
v = qkv[:, H + NKV * HD:].view(length, NKV, HD)
|
| 332 |
+
q = self._rope(rms_norm(q, L.q_norm), pos)
|
| 333 |
+
k = self._rope(rms_norm(k, L.k_norm), pos)
|
| 334 |
+
cache["k"][s0:s0 + length] = k
|
| 335 |
+
cache["v"][s0:s0 + length] = v
|
| 336 |
+
# GQA handled inside sdpa (query head h -> kv head h // GQA); no
|
| 337 |
+
# need to materialize an expanded [T, NH, HD] copy of the cache.
|
| 338 |
+
attn = F.scaled_dot_product_attention(
|
| 339 |
+
q.transpose(0, 1), cache["k"].transpose(0, 1), cache["v"].transpose(0, 1),
|
| 340 |
+
enable_gqa=True)
|
| 341 |
+
h = h + L.o(attn.transpose(0, 1).reshape(length, H))
|
| 342 |
+
else:
|
| 343 |
+
bcx = L.in_proj(xn)
|
| 344 |
+
B, C, x = bcx[:, :H], bcx[:, H:2 * H], bcx[:, 2 * H:]
|
| 345 |
+
cache["bx"][s0:s0 + length] = B * x
|
| 346 |
+
conv = self._conv_slice(cache["bx"], L.conv, s0, length)
|
| 347 |
+
h = h + L.out_proj(C * conv)
|
| 348 |
+
fn = rms_norm(h, L.ffn_norm)
|
| 349 |
+
gu = L.w13(fn)
|
| 350 |
+
h = h + L.w2(F.silu(gu[:, :FF]) * gu[:, FF:])
|
| 351 |
+
|
| 352 |
+
h = rms_norm(h, self.emb_norm)
|
| 353 |
+
if rows is not None:
|
| 354 |
+
h = h[torch.as_tensor([r - s0 for r in rows], dtype=torch.long)]
|
| 355 |
+
return self.lm_head(h)[:, :REAL_VOCAB]
|
| 356 |
+
|
| 357 |
+
@staticmethod
|
| 358 |
+
def _select(logits, temperature):
|
| 359 |
+
if temperature and temperature > 0:
|
| 360 |
+
u = torch.rand_like(logits).clamp_min_(1e-20)
|
| 361 |
+
ids = (logits + temperature * (-torch.log(-torch.log(u)))).argmax(-1)
|
| 362 |
+
else:
|
| 363 |
+
ids = logits.argmax(-1)
|
| 364 |
+
conf = torch.softmax(logits, dim=-1).gather(1, ids.unsqueeze(1)).squeeze(1)
|
| 365 |
+
return ids, conf
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# --- MDLM decode loop (port of diffuseGPU: block-scheduled adaptive reveal) ---
|
| 369 |
+
def diffuse(model, prompt_ids, max_new=64, steps=32, block_size=16,
|
| 370 |
+
temperature=0.0, tau=0.9):
|
| 371 |
+
"""Generator yielding {step, gen_ids, revealed} frames. gen_ids is the
|
| 372 |
+
generated region only (length max_new); revealed is the set of indices (into
|
| 373 |
+
gen_ids) freshly committed this step."""
|
| 374 |
+
P = len(prompt_ids)
|
| 375 |
+
T = P + max_new
|
| 376 |
+
x = torch.full((T,), MASK_ID, dtype=torch.long)
|
| 377 |
+
x[:P] = torch.tensor(prompt_ids, dtype=torch.long)
|
| 378 |
+
|
| 379 |
+
yield {"step": 0, "gen_ids": x[P:].tolist(), "revealed": set()}
|
| 380 |
+
|
| 381 |
+
st = model.new_state(T)
|
| 382 |
+
nblk = max(1, math.ceil(max_new / block_size))
|
| 383 |
+
per_block = max(1, math.ceil(steps / nblk))
|
| 384 |
+
step = 0
|
| 385 |
+
for b in range(nblk):
|
| 386 |
+
s0 = P + b * block_size
|
| 387 |
+
s1 = min(P + (b + 1) * block_size, T)
|
| 388 |
+
if not (x[s0:s1] == MASK_ID).any():
|
| 389 |
+
continue
|
| 390 |
+
block_steps_left = per_block
|
| 391 |
+
fresh = True # first step of each block = full refresh (rebuild caches)
|
| 392 |
+
while True:
|
| 393 |
+
rows = [i for i in range(s0, s1) if x[i].item() == MASK_ID]
|
| 394 |
+
if not rows:
|
| 395 |
+
break
|
| 396 |
+
if fresh:
|
| 397 |
+
logits = model.forward(x, rows, st)
|
| 398 |
+
fresh = False
|
| 399 |
+
else:
|
| 400 |
+
logits = model.forward(x, rows, st, s0=s0, length=s1 - s0)
|
| 401 |
+
ids, conf = model._select(logits, temperature)
|
| 402 |
+
cand = sorted(
|
| 403 |
+
({"pos": rows[i], "id": int(ids[i]), "conf": float(conf[i])}
|
| 404 |
+
for i in range(len(rows))),
|
| 405 |
+
key=lambda c: c["conf"], reverse=True)
|
| 406 |
+
min_k = len(rows) if block_steps_left <= 1 else math.ceil(len(rows) / block_steps_left)
|
| 407 |
+
revealed, taken, committed = set(), set(), 0
|
| 408 |
+
|
| 409 |
+
def adj(pos):
|
| 410 |
+
return (pos - 1) in taken or (pos + 1) in taken
|
| 411 |
+
|
| 412 |
+
for idx, c in enumerate(cand):
|
| 413 |
+
if idx == 0 or ((c["conf"] >= tau or committed < min_k) and not adj(c["pos"])):
|
| 414 |
+
x[c["pos"]] = c["id"]
|
| 415 |
+
revealed.add(c["pos"] - P)
|
| 416 |
+
taken.add(c["pos"])
|
| 417 |
+
committed += 1
|
| 418 |
+
for c in cand:
|
| 419 |
+
if committed >= min_k:
|
| 420 |
+
break
|
| 421 |
+
if c["pos"] not in taken:
|
| 422 |
+
x[c["pos"]] = c["id"]
|
| 423 |
+
revealed.add(c["pos"] - P)
|
| 424 |
+
taken.add(c["pos"])
|
| 425 |
+
committed += 1
|
| 426 |
+
block_steps_left = max(1, block_steps_left - 1)
|
| 427 |
+
step += 1
|
| 428 |
+
yield {"step": step, "gen_ids": x[P:].tolist(), "revealed": revealed}
|
lliquid.gif
ADDED
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
safetensors>=0.4
|
| 2 |
+
huggingface_hub>=0.26
|
| 3 |
+
tokenizers>=0.20.0
|
| 4 |
+
flask>=3.0
|
| 5 |
+
gunicorn>=21.2
|
style.css
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
--paper:#fff;
|
| 3 |
+
--ink:#050505;
|
| 4 |
+
--purple:#6c4fe0;
|
| 5 |
+
--lilac:#cd82f0;
|
| 6 |
+
--green:#2dbd70;
|
| 7 |
+
--red:#e45454;
|
| 8 |
+
--neutral-50:#fafafa;
|
| 9 |
+
--neutral-100:#f4f4f3;
|
| 10 |
+
--neutral-200:#e7e7e5;
|
| 11 |
+
--neutral-300:#b9b9b5;
|
| 12 |
+
--neutral-500:#737373;
|
| 13 |
+
--neutral-700:#404040;
|
| 14 |
+
--border:rgba(0,0,0,.09);
|
| 15 |
+
--sans:"Inter",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
|
| 16 |
+
--serif:"Instrument Serif",Georgia,"Times New Roman",serif;
|
| 17 |
+
--mono:"JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,monospace;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
* { box-sizing:border-box; }
|
| 21 |
+
html { background:var(--neutral-50); }
|
| 22 |
+
body {
|
| 23 |
+
min-width:320px;
|
| 24 |
+
min-height:100vh;
|
| 25 |
+
margin:0;
|
| 26 |
+
background:var(--neutral-50);
|
| 27 |
+
color:var(--ink);
|
| 28 |
+
font:16px/1.45 var(--sans);
|
| 29 |
+
-webkit-font-smoothing:antialiased;
|
| 30 |
+
}
|
| 31 |
+
button,textarea,input { font:inherit; }
|
| 32 |
+
a { color:inherit; }
|
| 33 |
+
[hidden] { display:none!important; }
|
| 34 |
+
|
| 35 |
+
.wrap {
|
| 36 |
+
display:flex;
|
| 37 |
+
flex-direction:column;
|
| 38 |
+
width:min(calc(100% - 32px),1240px);
|
| 39 |
+
min-height:100vh;
|
| 40 |
+
min-height:100dvh;
|
| 41 |
+
margin:0 auto;
|
| 42 |
+
border-right:1px solid var(--border);
|
| 43 |
+
border-left:1px solid var(--border);
|
| 44 |
+
background:var(--paper);
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
.site-intro { margin-top:auto; padding:20px 30px 16px; }
|
| 48 |
+
h1 {
|
| 49 |
+
margin:0 0 7px;
|
| 50 |
+
font:400 clamp(40px,4.3vw,51px)/.98 var(--serif);
|
| 51 |
+
letter-spacing:.002em;
|
| 52 |
+
}
|
| 53 |
+
h1 em { color:var(--purple); font-weight:400; font-style:italic; }
|
| 54 |
+
.sub { max-width:900px; margin:0; color:var(--neutral-500); font-size:15px; line-height:1.45; }
|
| 55 |
+
|
| 56 |
+
.model-strip {
|
| 57 |
+
display:grid;
|
| 58 |
+
grid-template-columns:48px 280px minmax(240px,1fr);
|
| 59 |
+
align-items:center;
|
| 60 |
+
column-gap:16px;
|
| 61 |
+
min-height:76px;
|
| 62 |
+
padding:12px 30px;
|
| 63 |
+
border-top:1px solid var(--border);
|
| 64 |
+
border-bottom:1px solid var(--border);
|
| 65 |
+
background:linear-gradient(90deg,rgba(108,79,224,.018),rgba(205,130,240,.035),rgba(108,79,224,.018));
|
| 66 |
+
transition:background .3s ease;
|
| 67 |
+
}
|
| 68 |
+
.model-logo-frame { position:relative; display:block; width:48px; height:48px; overflow:hidden; }
|
| 69 |
+
.model-logo {
|
| 70 |
+
position:absolute;
|
| 71 |
+
top:50%;
|
| 72 |
+
left:50%;
|
| 73 |
+
display:block;
|
| 74 |
+
width:56px;
|
| 75 |
+
height:auto;
|
| 76 |
+
max-width:none;
|
| 77 |
+
transform:translate(-50%,-50%);
|
| 78 |
+
image-rendering:pixelated;
|
| 79 |
+
}
|
| 80 |
+
.model-copy { display:flex; min-width:0; align-items:center; justify-content:center; }
|
| 81 |
+
.model-name-row { display:flex; min-height:25px; align-items:center; gap:10px; white-space:nowrap; }
|
| 82 |
+
.model-copy a { font:400 22px/1.15 var(--serif); text-decoration:none; }
|
| 83 |
+
.model-copy a:hover { color:var(--purple); }
|
| 84 |
+
.model-variant { display:inline-flex; height:18px; align-items:center; box-sizing:border-box; padding:0 7px; border:1px solid rgba(108,79,224,.14); border-radius:999px; background:rgba(108,79,224,.05); color:var(--purple); font:700 9px/1 var(--mono); letter-spacing:.035em; text-transform:uppercase; }
|
| 85 |
+
.load-block { min-width:0; }
|
| 86 |
+
.load-meta { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-bottom:8px; color:var(--neutral-500); font-size:12px; font-weight:600; }
|
| 87 |
+
#load-percent { font:600 11px/1 var(--mono); font-variant-numeric:tabular-nums; }
|
| 88 |
+
.load-track { height:7px; overflow:hidden; border-radius:999px; background:rgba(108,79,224,.09); }
|
| 89 |
+
.load-track span { display:block; width:0; height:100%; border-radius:inherit; background:linear-gradient(90deg,var(--purple),var(--lilac)); transition:width .18s ease; }
|
| 90 |
+
.is-ready .load-track { background:rgba(45,189,112,.09); }
|
| 91 |
+
.is-ready .load-track span { background:var(--green); }
|
| 92 |
+
.is-ready .load-meta { color:#188e50; }
|
| 93 |
+
.is-error .load-track span { background:var(--red); }
|
| 94 |
+
.is-error .load-meta { color:var(--red); }
|
| 95 |
+
|
| 96 |
+
main { display:flex; min-height:0; flex:0 0 auto; flex-direction:column; margin-bottom:auto; padding:18px 30px 22px; }
|
| 97 |
+
.diffusion-workspace {
|
| 98 |
+
display:grid;
|
| 99 |
+
grid-template-columns:minmax(360px,.9fr) minmax(480px,1.18fr);
|
| 100 |
+
align-items:stretch;
|
| 101 |
+
gap:18px;
|
| 102 |
+
min-height:432px;
|
| 103 |
+
}
|
| 104 |
+
.workspace-card {
|
| 105 |
+
position:relative;
|
| 106 |
+
min-width:0;
|
| 107 |
+
overflow:hidden;
|
| 108 |
+
border:1px solid var(--border);
|
| 109 |
+
border-radius:12px;
|
| 110 |
+
background:var(--paper);
|
| 111 |
+
transition:border-color .2s,box-shadow .2s,transform .2s;
|
| 112 |
+
}
|
| 113 |
+
.prompt-panel,.response-panel { padding:20px; }
|
| 114 |
+
.panel-header { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:16px; }
|
| 115 |
+
.panel-header h2 { margin:0 0 5px; color:var(--neutral-500); font:600 12px/1.25 var(--mono); letter-spacing:.08em; text-transform:uppercase; }
|
| 116 |
+
.panel-header p { margin:0; color:var(--neutral-500); font-size:13px; line-height:1.4; }
|
| 117 |
+
.activity-pill {
|
| 118 |
+
display:inline-flex;
|
| 119 |
+
align-items:center;
|
| 120 |
+
gap:8px;
|
| 121 |
+
flex:none;
|
| 122 |
+
padding:7px 10px;
|
| 123 |
+
border:1px solid var(--border);
|
| 124 |
+
border-radius:999px;
|
| 125 |
+
background:var(--neutral-50);
|
| 126 |
+
color:var(--neutral-500);
|
| 127 |
+
font-size:11px;
|
| 128 |
+
font-weight:650;
|
| 129 |
+
white-space:nowrap;
|
| 130 |
+
}
|
| 131 |
+
.activity-pill i { width:8px; height:8px; border-radius:50%; background:var(--green); box-shadow:0 0 0 4px rgba(45,189,112,.1); }
|
| 132 |
+
.activity-pill.is-running { border-color:rgba(108,79,224,.2); background:rgba(108,79,224,.055); color:var(--purple); }
|
| 133 |
+
.activity-pill.is-running i { background:var(--purple); box-shadow:0 0 0 5px rgba(108,79,224,.11); animation:status-pulse .8s ease-in-out infinite; }
|
| 134 |
+
.activity-pill.is-done { border-color:rgba(45,189,112,.2); background:rgba(45,189,112,.055); color:#188e50; animation:done-pill .5s ease both; }
|
| 135 |
+
.activity-pill.is-error { border-color:rgba(228,84,84,.2); background:rgba(228,84,84,.055); color:var(--red); }
|
| 136 |
+
.activity-pill.is-error i { background:var(--red); box-shadow:none; }
|
| 137 |
+
|
| 138 |
+
.prompt-stage { position:relative; min-height:145px; overflow:hidden; border:1px solid var(--border); border-radius:10px; background:var(--paper); transition:border-color .2s,box-shadow .2s; }
|
| 139 |
+
.prompt-stage:focus-within { border-color:var(--purple); box-shadow:0 0 0 3px rgba(108,79,224,.11); }
|
| 140 |
+
#prompt { position:relative; z-index:1; display:block; width:100%; min-height:145px; padding:15px 16px; border:0; outline:0; background:transparent; color:var(--ink); font-size:15px; line-height:1.55; resize:none; }
|
| 141 |
+
#prompt::placeholder { color:var(--neutral-300); }
|
| 142 |
+
.prompt-scan,.response-scan { position:absolute; inset:-1px; z-index:3; opacity:0; pointer-events:none; background:linear-gradient(90deg,transparent 20%,rgba(108,79,224,.055) 40%,rgba(205,130,240,.24) 49%,rgba(255,255,255,.86) 53%,transparent 73%); transform:translateX(-110%); }
|
| 143 |
+
.is-generating .prompt-scan { opacity:1; animation:panel-sweep 1.15s cubic-bezier(.45,0,.25,1) infinite; }
|
| 144 |
+
.composer-row { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-top:10px; }
|
| 145 |
+
.composer-row > span { color:var(--neutral-500); font-size:10px; }
|
| 146 |
+
#go { display:inline-flex; min-width:102px; align-items:center; justify-content:center; gap:9px; padding:9px 13px; border:1px solid var(--ink); border-radius:999px; background:var(--ink); color:var(--paper); font-size:12px; font-weight:650; cursor:pointer; transition:transform .16s,box-shadow .16s,opacity .16s; }
|
| 147 |
+
#go i { font-size:16px; font-style:normal; transition:transform .16s; }
|
| 148 |
+
#go:hover:not(:disabled) { transform:translateY(-1px); box-shadow:0 7px 18px rgba(0,0,0,.12); }
|
| 149 |
+
#go:hover:not(:disabled) i { transform:translateX(2px); }
|
| 150 |
+
#go:disabled { cursor:wait; opacity:.48; }
|
| 151 |
+
|
| 152 |
+
.settings-heading { display:flex; align-items:baseline; justify-content:space-between; gap:12px; margin:17px 1px 9px; }
|
| 153 |
+
.settings-heading h3 { margin:0; color:var(--neutral-500); font:600 10px/1.25 var(--mono); letter-spacing:.08em; text-transform:uppercase; }
|
| 154 |
+
.settings-heading span { color:var(--neutral-300); font-size:10px; }
|
| 155 |
+
.settings-grid { display:grid; grid-template-columns:1fr 1fr; gap:7px; }
|
| 156 |
+
.range-control { display:grid; grid-template-columns:1fr auto; align-items:center; gap:5px 8px; min-width:0; padding:8px 10px 6px; border:1px solid var(--border); border-radius:9px; background:var(--neutral-50); }
|
| 157 |
+
.range-control > span { overflow:hidden; color:var(--neutral-500); font-size:10px; font-weight:650; text-overflow:ellipsis; white-space:nowrap; }
|
| 158 |
+
.range-control output { color:var(--purple); font:650 10px/1 var(--mono); font-variant-numeric:tabular-nums; }
|
| 159 |
+
.range-control input { grid-column:1/-1; }
|
| 160 |
+
.range-wide { grid-column:1/-1; }
|
| 161 |
+
input[type=range] { width:100%; height:18px; margin:0; appearance:none; background:transparent; accent-color:var(--purple); --pct:50%; cursor:pointer; }
|
| 162 |
+
input[type=range]::-webkit-slider-runnable-track { height:5px; border-radius:999px; background:linear-gradient(90deg,var(--purple) 0 var(--pct),var(--neutral-200) var(--pct) 100%); }
|
| 163 |
+
input[type=range]::-webkit-slider-thumb { width:14px; height:14px; margin-top:-4.5px; appearance:none; border:3px solid var(--paper); border-radius:50%; background:var(--purple); box-shadow:0 1px 4px rgba(38,26,90,.3); }
|
| 164 |
+
input[type=range]::-moz-range-track { height:5px; border:0; border-radius:999px; background:var(--neutral-200); }
|
| 165 |
+
input[type=range]::-moz-range-progress { height:5px; border-radius:999px; background:var(--purple); }
|
| 166 |
+
input[type=range]::-moz-range-thumb { width:9px; height:9px; border:3px solid var(--paper); border-radius:50%; background:var(--purple); }
|
| 167 |
+
|
| 168 |
+
.response-panel { display:flex; flex-direction:column; }
|
| 169 |
+
.response-stage { position:relative; display:flex; min-height:342px; flex:1; overflow:hidden; border:1px solid var(--border); border-radius:10px; background:linear-gradient(145deg,#fff 0%,rgba(108,79,224,.015) 55%,rgba(205,130,240,.035) 100%); transition:border-color .2s,box-shadow .2s; }
|
| 170 |
+
.response-stage.is-denoising { border-color:rgba(108,79,224,.3); box-shadow:0 0 0 3px rgba(108,79,224,.055),inset 0 0 38px rgba(108,79,224,.025); }
|
| 171 |
+
.response-stage.is-denoising .response-scan { opacity:1; animation:response-sweep 1.15s cubic-bezier(.45,0,.25,1) infinite; }
|
| 172 |
+
.empty-state { display:flex; width:100%; flex-direction:column; align-items:center; justify-content:center; padding:30px; color:var(--neutral-500); text-align:center; }
|
| 173 |
+
.empty-state strong { margin-top:17px; color:var(--neutral-700); font-size:14px; }
|
| 174 |
+
.empty-state p { margin:5px 0 16px; font-size:12px; }
|
| 175 |
+
.idle-orbit { position:relative; display:grid; width:58px; height:58px; place-items:center; border:1px solid rgba(108,79,224,.18); border-radius:50%; box-shadow:inset 0 0 0 12px rgba(108,79,224,.025); }
|
| 176 |
+
.idle-orbit::before,.idle-orbit span { content:""; position:absolute; border-radius:50%; }
|
| 177 |
+
.idle-orbit::before { width:10px; height:10px; background:var(--purple); box-shadow:0 0 0 6px rgba(108,79,224,.08); }
|
| 178 |
+
.idle-orbit span { top:2px; width:7px; height:7px; background:var(--lilac); transform-origin:3.5px 26px; animation:idle-orbit-turn 3.2s linear infinite; }
|
| 179 |
+
.idle-orbit i { width:28px; height:28px; border:1px dashed rgba(108,79,224,.18); border-radius:50%; animation:idle-orbit-turn 8s linear infinite reverse; }
|
| 180 |
+
.idle-masks { display:flex; align-items:center; gap:5px; }
|
| 181 |
+
.idle-masks span { width:24px; height:8px; border-radius:3px; background:rgba(108,79,224,.09); animation:idle-mask 1.6s ease-in-out infinite alternate; }
|
| 182 |
+
.idle-masks span:nth-child(2),.idle-masks span:nth-child(5) { width:39px; animation-delay:-.5s; }
|
| 183 |
+
.idle-masks span:nth-child(3),.idle-masks span:nth-child(6) { width:18px; animation-delay:-.9s; }
|
| 184 |
+
.assistant-message { display:flex; width:100%; min-height:100%; flex-direction:column; padding:18px 18px 16px; }
|
| 185 |
+
.canvas { flex:1; color:var(--ink); font-size:16px; line-height:1.75; white-space:pre-wrap; word-break:break-word; }
|
| 186 |
+
.canvas .mask { display:inline-flex; height:1.7em; align-items:center; margin:2px 3px 2px 0; padding:0 6px; border:1px solid rgba(108,79,224,.12); border-radius:4px; background:linear-gradient(100deg,rgba(108,79,224,.055),rgba(205,130,240,.2),rgba(108,79,224,.055)); background-size:220% 100%; color:rgba(108,79,224,.78); font:600 9px/1 var(--mono); letter-spacing:-.025em; vertical-align:.1em; animation:mask-breathe 1.25s ease-in-out infinite,mask-shimmer 1.45s linear infinite; animation-delay:calc(var(--token-index) * -23ms); }
|
| 187 |
+
.canvas .tok { animation:token-settle .28s ease both; }
|
| 188 |
+
.canvas .tok.new { position:relative; border-radius:3px; animation:token-reveal .62s cubic-bezier(.2,.8,.2,1) both; }
|
| 189 |
+
.starting-copy { color:var(--neutral-300); font-style:italic; }
|
| 190 |
+
.generation-meta { margin-top:auto; padding-top:14px; }
|
| 191 |
+
.step-track { height:6px; overflow:hidden; border-radius:999px; background:rgba(108,79,224,.08); }
|
| 192 |
+
.step-track span { display:block; width:0; height:100%; border-radius:inherit; background:linear-gradient(90deg,var(--purple),var(--lilac)); box-shadow:0 0 12px rgba(108,79,224,.28); transition:width .22s cubic-bezier(.2,.8,.2,1); }
|
| 193 |
+
.stats { min-height:16px; margin-top:8px; color:var(--neutral-500); font:500 10px/1.5 var(--mono); font-variant-numeric:tabular-nums; }
|
| 194 |
+
.response-stage.is-complete { animation:response-complete .8s ease both; }
|
| 195 |
+
|
| 196 |
+
.examples-panel { display:flex; align-items:center; gap:15px; margin-top:16px; padding:15px 17px; overflow:hidden; border:1px solid var(--border); border-radius:11px; background:var(--neutral-50); }
|
| 197 |
+
.examples-label { flex:none; color:var(--neutral-500); font:600 11px/1.3 var(--mono); letter-spacing:.07em; text-transform:uppercase; }
|
| 198 |
+
.example-list { display:flex; flex-wrap:wrap; gap:7px; min-width:0; padding-top:2px; }
|
| 199 |
+
.ex { display:inline-flex; align-items:center; padding:8px 12px; border:1px solid var(--border); border-radius:999px; background:var(--paper); color:var(--neutral-700); font-size:12px; line-height:1.15; cursor:pointer; transition:background .15s,border-color .15s,color .15s,transform .15s,box-shadow .15s; }
|
| 200 |
+
.ex:hover { border-color:rgba(108,79,224,.28); color:var(--purple); transform:translateY(-1px); box-shadow:0 5px 12px rgba(54,42,105,.08); }
|
| 201 |
+
.ex.active { border-color:var(--ink); background:var(--ink); color:var(--paper); box-shadow:none; }
|
| 202 |
+
.prompt-panel.example-changed { animation:example-pulse .55s ease both; }
|
| 203 |
+
.sr-only { position:absolute!important; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
|
| 204 |
+
|
| 205 |
+
@keyframes idle-orbit-turn { to { transform:rotate(360deg); } }
|
| 206 |
+
@keyframes status-pulse { 50% { transform:scale(.72); opacity:.55; } }
|
| 207 |
+
@keyframes done-pill { 0% { transform:scale(.95); } 55% { transform:scale(1.04); } 100% { transform:scale(1); } }
|
| 208 |
+
@keyframes panel-sweep { from { transform:translateX(-110%); } to { transform:translateX(110%); } }
|
| 209 |
+
@keyframes response-sweep { 0% { transform:translateX(-115%); } 70%,100% { transform:translateX(115%); } }
|
| 210 |
+
@keyframes idle-mask { to { opacity:.35; transform:scaleX(.82); } }
|
| 211 |
+
@keyframes mask-breathe { 50% { opacity:.42; transform:scaleY(.78); } }
|
| 212 |
+
@keyframes mask-shimmer { from { background-position:100% 0; } to { background-position:-100% 0; } }
|
| 213 |
+
@keyframes token-settle { from { opacity:.35; } to { opacity:1; } }
|
| 214 |
+
@keyframes token-reveal { 0% { color:var(--purple); background:rgba(205,130,240,.3); box-shadow:0 0 14px rgba(205,130,240,.35); transform:translateY(2px); } 100% { color:inherit; background:transparent; box-shadow:none; transform:none; } }
|
| 215 |
+
@keyframes response-complete { 0% { box-shadow:0 0 0 0 rgba(45,189,112,.2); } 45% { border-color:rgba(45,189,112,.42); box-shadow:0 0 0 5px rgba(45,189,112,.09),inset 0 0 38px rgba(45,189,112,.035); } 100% { box-shadow:none; } }
|
| 216 |
+
@keyframes example-pulse { 0% { border-color:var(--border); } 50% { border-color:rgba(108,79,224,.35); box-shadow:0 0 0 4px rgba(108,79,224,.06); } 100% { border-color:var(--border); box-shadow:none; } }
|
| 217 |
+
|
| 218 |
+
@media (max-width:1120px) {
|
| 219 |
+
.diffusion-workspace { grid-template-columns:minmax(330px,.88fr) minmax(410px,1.12fr); gap:14px; }
|
| 220 |
+
}
|
| 221 |
+
@media (max-width:900px) {
|
| 222 |
+
.diffusion-workspace { grid-template-columns:1fr; gap:14px; }
|
| 223 |
+
.response-stage { min-height:320px; }
|
| 224 |
+
.model-copy { min-width:190px; }
|
| 225 |
+
}
|
| 226 |
+
@media (max-width:720px) {
|
| 227 |
+
.wrap { width:100%; border:0; }
|
| 228 |
+
.site-intro { padding:20px; }
|
| 229 |
+
h1 { font-size:40px; }
|
| 230 |
+
.sub { font-size:14px; }
|
| 231 |
+
.model-strip { grid-template-columns:48px minmax(0,1fr); column-gap:16px; row-gap:10px; padding:12px 20px; }
|
| 232 |
+
.model-copy { min-width:0; }
|
| 233 |
+
.load-block { grid-column:1/-1; }
|
| 234 |
+
main { padding:15px 20px 20px; }
|
| 235 |
+
.prompt-panel,.response-panel { padding:17px; }
|
| 236 |
+
.examples-panel { align-items:flex-start; flex-direction:column; gap:9px; }
|
| 237 |
+
}
|
| 238 |
+
@media (max-width:470px) {
|
| 239 |
+
.model-name-row { align-items:flex-start; flex-direction:column; gap:2px; }
|
| 240 |
+
.settings-grid { grid-template-columns:1fr; }
|
| 241 |
+
.range-wide { grid-column:auto; }
|
| 242 |
+
.composer-row { align-items:flex-end; flex-direction:column; }
|
| 243 |
+
.composer-row > span { align-self:flex-start; }
|
| 244 |
+
.response-heading { align-items:flex-start; flex-direction:column; }
|
| 245 |
+
}
|
| 246 |
+
@media (prefers-reduced-motion:reduce) {
|
| 247 |
+
*,*::before,*::after { scroll-behavior:auto!important; animation-duration:.01ms!important; animation-iteration-count:1!important; transition-duration:.01ms!important; }
|
| 248 |
+
}
|