Spaces:
Running on Zero
Running on Zero
File size: 13,402 Bytes
abf4b7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | """Atlas AI models on one page: chat with Axiom-1-Chat, Axiom-1.1-Chat and Quasar, and make Quasar images and videos.
Runs on ZeroGPU: Axiom chats on the CPU (fast enough, and it spends none of the visitor's GPU quota); Quasar sits on the
GPU, which ZeroGPU attaches only while a @spaces.GPU function runs. Weights come from the public model repos at startup.
"""
import base64
import os
import sys
import tempfile
import threading
from pathlib import Path
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
sys.modules.setdefault("torchao", None) # Quasar's optional GPU quantiser; these fp32/bf16 weights don't use it
try:
import spaces
except ImportError: # outside Hugging Face: run the same functions without GPU scheduling
class spaces:
@staticmethod
def GPU(fn=None, **kw):
return fn if fn else (lambda f: f)
import gradio as gr
import numpy as np
import torch
from huggingface_hub import snapshot_download
from PIL import Image
from axiom.decoding import RECOMMENDED, default_exempt, generate, sentence_ends
from axiom.hub import load
torch.set_num_threads(max(1, min(4, os.cpu_count() or 2)))
HERE = Path(__file__).resolve().parent
AXIOM = {"Axiom-1.1-Chat": "Atlas-AI-research/Axiom-1.1-Chat", "Axiom-1-Chat": "Atlas-AI-research/Axiom-1-Chat"}
QUASAR = "Atlas-AI-research/Quasar"
QUASAR_FILES = ["config.json", "model.safetensors", "quasar/**", "tokenizers/**", "codecs/vision/**"] # no audio codec, no v5 variant
QUASAR_DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # ZeroGPU emulates CUDA at startup; placing models then is fastest
_models, _lock = {}, threading.Lock()
def text_of(content):
"""A chat message's text, whether Gradio gives a string or a list of content parts."""
if isinstance(content, str):
return content
if isinstance(content, dict):
return content.get("text") or ""
return " ".join(text_of(c) for c in content or [])
# ---- Axiom ---------------------------------------------------------------------------------------------------------
def axiom(name):
with _lock:
if name not in _models:
model, tok, meta = load(AXIOM[name])
sid = {s: tok.token_to_id(s) for s in ("<|endoftext|>", "<|user|>", "<|assistant|>", "<|end|>")}
_models[name] = dict(model=model, tok=tok, sid=sid, nl=tok.encode("\n").ids, exempt=default_exempt(tok),
sent_end=sentence_ends(tok), ctx=meta["axiom_config"]["train"]["seq_len"])
return _models[name]
def axiom_chat(message, history, name, temperature, top_p, max_new):
m = axiom(name)
tok, sid, nl = m["tok"], m["sid"], m["nl"]
def turn(role, text):
return [sid[f"<|{role}|>"]] + nl + tok.encode(text).ids + [sid["<|end|>"]] + nl
past = [turn(h["role"], text_of(h["content"])) for h in history if h.get("role") in ("user", "assistant")]
prompt_for = lambda turns: [sid["<|endoftext|>"]] + sum(turns, []) + turn("user", message) + [sid["<|assistant|>"]] + nl
while past and len(prompt_for(past)) + max_new > m["ctx"]: # drop the oldest turns to fit the 1,024-token window
past = past[1:]
cfg = RECOMMENDED.replace(temperature=float(temperature), top_p=float(top_p), max_new=int(max_new))
stop = (sid["<|end|>"], sid["<|endoftext|>"])
reply = []
for t in generate(m["model"], prompt_for(past), cfg, stop=stop, exempt=m["exempt"], max_ctx=m["ctx"], sent_end=m["sent_end"]):
if t in stop:
break
reply.append(t)
yield tok.decode(reply) # decode the whole reply each time: byte-level BPE can split characters
if not reply:
yield "…"
# ---- Quasar --------------------------------------------------------------------------------------------------------
def quasar():
with _lock:
if "quasar" not in _models:
path = Path(snapshot_download(QUASAR, allow_patterns=QUASAR_FILES))
sys.path.insert(0, str(path))
from quasar.inference.decoding import Sampling
from quasar.inference.extended import ExtendedGenerator
gen = ExtendedGenerator(path, QUASAR_DEVICE)
gen.vision() # load the image codec now too, not inside a GPU call
_models["quasar"] = (gen, Sampling)
return _models["quasar"]
def sampling(temperature, seed, max_new=64):
_, Sampling = quasar()
return Sampling(temperature=float(temperature), top_k=64, top_p=0.9, seed=int(seed), max_new_tokens=int(max_new))
def enlarge(pixels, size):
return Image.fromarray(pixels).resize((size, size), Image.NEAREST) # show the real pixels, just bigger
@spaces.GPU(duration=20)
def quasar_chat(message, history, temperature, max_new):
gen, _ = quasar() # each message on its own: given earlier turns as text, Quasar tends to repeat its last answer
return gen.generate_text(message, sampling(temperature, torch.seed() % 2**31, max_new)).strip() or "…"
@spaces.GPU(duration=30)
def quasar_image(prompt, resolution, seed, temperature):
if not prompt.strip():
raise gr.Error("Write a prompt first.")
gen, _ = quasar()
return enlarge(gen.generate_image(prompt, sampling(temperature, seed), resolution=int(resolution)), 384)
@spaces.GPU(duration=60)
def quasar_video(prompt, seed, temperature):
if not prompt.strip():
raise gr.Error("Write a prompt first.")
gen, _ = quasar()
frames = [enlarge(f, 256) for f in gen.generate_video(prompt, 8, sampling(temperature, seed))]
out = Path(tempfile.mkdtemp()) / "quasar.gif"
frames[0].save(out, save_all=True, append_images=frames[1:], duration=250, loop=0)
return str(out)
@spaces.GPU(duration=20)
def quasar_describe(image, temperature):
if image is None:
raise gr.Error("Add an image first.")
gen, _ = quasar()
im = Image.fromarray(image).convert("RGB")
side = min(im.size)
im = im.crop(((im.width - side) // 2, (im.height - side) // 2, (im.width + side) // 2, (im.height + side) // 2))
return gen.describe_image(np.asarray(im.resize((64, 64), Image.BICUBIC)), sampling(temperature, 0)).strip()
# Load everything at startup: ZeroGPU wants models on CUDA before the first request.
for _name in AXIOM:
axiom(_name)
quasar()
# ---- page ----------------------------------------------------------------------------------------------------------
def data_uri(name):
return "data:image/svg+xml;base64," + base64.b64encode((HERE / "assets" / name).read_bytes()).decode()
HEADER = f"""
<header class="hero">
<img class="mark" src="{data_uri('axiom-mark.svg')}" alt="Axiom">
<h1>Try the Atlas AI <span class="grad">models.</span></h1>
<p class="lede">Three small research models on the AXIOM architecture. They are experiments: expect wrong facts and
odd replies.</p>
<p class="by">By <img src="{data_uri('atlas-ai-wordmark.svg')}" alt="ATLAS AI"></p>
</header>
"""
CSS = """
:root, .dark {
--ink: #1D1D1F; --ground: #F5F5F7; --muted: #5B5B60;
--body-background-fill: var(--ground); --background-fill-primary: #FFFFFF; --background-fill-secondary: var(--ground);
--body-text-color: var(--ink); --block-background-fill: #FFFFFF; --block-border-color: #E3E3E8;
--border-color-primary: #E3E3E8; --input-background-fill: #FFFFFF; --body-text-color-subdued: var(--muted);
--block-label-text-color: var(--muted); --block-title-text-color: var(--ink);
--button-primary-background-fill: var(--ink); --button-primary-background-fill-hover: #3A3A3F;
--button-primary-text-color: #FFFFFF; --color-accent: #0A6CFF; --color-accent-soft: #E6F0FF;
}
body, gradio-app { background: var(--ground) !important; }
.gradio-container { max-width: 980px !important; margin: 0 auto !important; }
.hero { text-align: center; padding: 28px 16px 8px; position: relative; }
.hero::before { content: ""; position: absolute; inset: -40px 10% auto; height: 240px; z-index: -1; pointer-events: none;
background: radial-gradient(40% 60% at 25% 50%, rgba(10,132,255,.18), transparent 70%),
radial-gradient(40% 60% at 75% 50%, rgba(255,149,64,.16), transparent 70%); }
.hero .mark { width: 108px; height: 72px; display: block; margin: 0 auto 10px; }
.hero h1 { font-size: clamp(2rem, 5vw, 3.1rem); font-weight: 700; letter-spacing: -0.045em; line-height: 1.05;
color: var(--ink); margin: 0 0 12px; text-wrap: balance; }
.hero .grad { background: linear-gradient(95deg, #0030FF 5%, #0A6CFF 38%, #0096D6 70%, #12A9C9 95%);
-webkit-background-clip: text; background-clip: text; color: transparent; }
.hero .lede { max-width: 60ch; margin: 0 auto 10px; color: var(--muted); font-size: 1rem; line-height: 1.5; text-wrap: pretty; }
.hero .by { display: flex; gap: 8px; justify-content: center; align-items: center; margin: 0; color: var(--ink);
font-weight: 500; font-size: 13px; }
.hero .by img { height: 10px; }
.note { color: var(--muted); font-size: 14px; line-height: 1.5; }
.note a { color: #0A6CFF; }
.pixels img { image-rendering: pixelated; }
footer { display: none !important; }
"""
AXIOM_NOTE = """<p class="note"><b>Axiom-1.1-Chat</b> is the newer one: it declines most questions about things that
don't exist and gets more easy facts right. <b>Axiom-1-Chat</b> is the first release. Both are 65M-parameter,
attention-free models and still invent most facts.
<a href="https://huggingface.co/Atlas-AI-research/Axiom-1.1-Chat">Axiom-1.1 card</a> ·
<a href="https://huggingface.co/Atlas-AI-research/Axiom-1-Chat">Axiom-1 card</a></p>"""
QUASAR_NOTE = """<p class="note"><b>Quasar</b> is one 90M-parameter model for text, images and short video, built on the
Axiom-1.1 backbone with attention in 3 of 12 blocks. It answers each chat message on its own. Images often repeat
photos it was trained on, and video is simple synthetic motion. Images and videos run on a shared GPU and use a few
seconds of your free daily ZeroGPU time.
<a href="https://huggingface.co/Atlas-AI-research/Quasar">Quasar card</a></p>"""
with gr.Blocks(title="Atlas AI models", fill_width=False) as demo:
gr.HTML(HEADER)
with gr.Tab("Axiom chat"):
gr.HTML(AXIOM_NOTE)
which = gr.Radio(list(AXIOM), value="Axiom-1.1-Chat", label="Model")
with gr.Accordion("Sampling", open=False):
a_temp = gr.Slider(0.1, 1.2, value=RECOMMENDED.temperature, step=0.05, label="Temperature")
a_top_p = gr.Slider(0.1, 1.0, value=RECOMMENDED.top_p, step=0.05, label="Top-p")
a_max = gr.Slider(16, 300, value=160, step=8, label="Longest reply, tokens")
gr.ChatInterface(axiom_chat, additional_inputs=[which, a_temp, a_top_p, a_max],
chatbot=gr.Chatbot(height=420, label="Axiom"), concurrency_limit=1,
examples=[["What's your name?"], ["What is the capital of France?"], ["Who was Queen Valmora of Drestia?"],
["How do plants make food?"]], api_name="axiom_chat")
with gr.Tab("Quasar"):
gr.HTML(QUASAR_NOTE)
q_temp = gr.Slider(0.1, 1.2, value=0.5, step=0.05, label="Temperature")
with gr.Tab("Chat"):
q_max = gr.Slider(16, 256, value=96, step=8, label="Longest reply, tokens")
gr.ChatInterface(quasar_chat, additional_inputs=[q_temp, q_max], chatbot=gr.Chatbot(height=360, label="Quasar"),
concurrency_limit=1, examples=[["What is the capital of France?"], ["Write a short story about a cat."]],
api_name="quasar_chat")
with gr.Tab("Image"):
with gr.Row():
with gr.Column():
i_prompt = gr.Textbox(label="Prompt", value="a photo of a dog")
i_res = gr.Radio([64, 128], value=128, label="Size, pixels")
i_seed = gr.Number(value=20261021, precision=0, label="Seed")
i_go = gr.Button("Make image", variant="primary")
i_out = gr.Image(label="Quasar image", elem_classes="pixels", format="png")
i_go.click(quasar_image, [i_prompt, i_res, i_seed, q_temp], i_out, concurrency_limit=1, api_name="quasar_image")
with gr.Tab("Video"):
with gr.Row():
with gr.Column():
v_prompt = gr.Textbox(label="Prompt", value="A small blue circle moving right on a black background.")
v_seed = gr.Number(value=20261021, precision=0, label="Seed")
v_go = gr.Button("Make 8-frame video", variant="primary")
v_out = gr.Image(label="Quasar video (GIF)", elem_classes="pixels", type="filepath")
v_go.click(quasar_video, [v_prompt, v_seed, q_temp], v_out, concurrency_limit=1, api_name="quasar_video")
with gr.Tab("Describe an image"):
with gr.Row():
d_in = gr.Image(label="Image (cropped to a square, shrunk to 64 × 64)", type="numpy")
with gr.Column():
d_go = gr.Button("Describe", variant="primary")
d_out = gr.Textbox(label="Quasar's description", lines=5)
d_go.click(quasar_describe, [d_in, q_temp], d_out, concurrency_limit=1, api_name="quasar_describe")
if __name__ == "__main__":
demo.queue(max_size=32).launch(css=CSS, theme=gr.themes.Base(font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"]),
ssr_mode=False)
|