p2E nano turbo

Description

This model is designed with a focus on speed and compactness, and is used for generating pixel art.

Benchmark

Benchmark p2E redmond 1 5v pokemon flux
speed 98 74 22
prompt 32 62 86
lightness 100 60 15
quality 64 88 58
total 2 1 1
import os
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
import io
import re
import zlib
import warnings
import numpy as np
import marimo as mo
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from PIL import Image

warnings.filterwarnings("ignore")

IMG_SIZE = 32
MAX_LEN = 16
VOCAB_SIZE = 4096
STOP_WORDS = {"a", "an", "the", "of", "pixel", "art", "icon"}

model_path = hf_hub_download(repo_id="User-Android/p2E", filename="model.onnx")
avail = ort.get_available_providers()
providers = [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in avail] or avail
sess = ort.InferenceSession(model_path, providers=providers)
in_x, in_t, in_txt = [inp.name for inp in sess.get_inputs()]

def encode_prompt(text):
    raw_words = re.findall(r"[a-z0-9]+", str(text).lower())
    words = [w for w in raw_words if w not in STOP_WORDS] or raw_words
    words = words[:MAX_LEN]
    ids = [(zlib.crc32(w.encode("utf-8")) % (VOCAB_SIZE - 1)) + 1 for w in words]
    ids += [0] * (MAX_LEN - len(ids))
    return np.array([ids], dtype=np.int64)

def make_checkerboard(size=256, cell=8):
    y, x = np.indices((size, size))
    board = ((x // cell) + (y // cell)) % 2
    gray = np.where(board == 0, 255, 220).astype(np.uint8)
    rgba = np.stack([gray, gray, gray, np.full_like(gray, 255)], axis=-1)
    return Image.fromarray(rgba, mode="RGBA")

def clean_alpha_mask(mask):
    padded = np.pad(mask.astype(np.int32), 1, mode="constant", constant_values=0)
    neighbors = padded[:-2, 1:-1] + padded[2:, 1:-1] + padded[1:-1, :-2] + padded[1:-1, 2:]
    return mask & (neighbors > 0)

CHECKER_BG = make_checkerboard(size=256, cell=8)

def generate_pixel_art(prompt, steps=40, cfg_scale=4.0):
    x = np.random.randn(1, 4, IMG_SIZE, IMG_SIZE).astype(np.float32)
    cond = encode_prompt(prompt)
    uncond = np.zeros_like(cond)
    t_schedule = np.linspace(1.0, 0.0, steps + 1, dtype=np.float32)
    cfg = np.float32(cfg_scale)

    def predict_v(x_in, t_val):
        t_b = np.array([t_val], dtype=np.float32)
        v_c = sess.run(None, {in_x: x_in, in_t: t_b, in_txt: cond})[0]
        v_u = sess.run(None, {in_x: x_in, in_t: t_b, in_txt: uncond})[0]
        return (v_u + cfg * (v_c - v_u)).astype(np.float32)

    for i in range(steps):
        t_cur = t_schedule[i]
        t_nxt = t_schedule[i + 1]
        dt = np.float32(t_cur - t_nxt)
        v1 = predict_v(x, t_cur)
        x_euler = (x - dt * v1).astype(np.float32)
        if t_nxt > 0.0:
            v2 = predict_v(x_euler, t_nxt)
            x = (x - np.float32(0.5) * dt * (v1 + v2)).astype(np.float32)
        else:
            x = x_euler

    rgba = ((np.clip(x, -1.0, 1.0) + 1.0) * 0.5)[0].transpose(1, 2, 0)
    alpha_raw = rgba[:, :, 3]
    mask = clean_alpha_mask(alpha_raw >= 0.5)
    if mask.sum() < 16:
        thresh = float(np.percentile(alpha_raw, 65))
        mask = alpha_raw >= thresh

    rgb = np.clip(np.round(rgba[:, :, :3] * 255.0), 0, 255).astype(np.uint8)
    out = np.zeros((IMG_SIZE, IMG_SIZE, 4), dtype=np.uint8)
    out[mask, :3] = rgb[mask]
    out[mask, 3] = 255

    fg = Image.fromarray(out, mode="RGBA").resize((256, 256), Image.Resampling.NEAREST)
    preview = Image.alpha_composite(CHECKER_BG, fg).convert("RGB")

    buf = io.BytesIO()
    preview.save(buf, format="PNG")
    return buf.getvalue()

def chat_handler(messages, config):
    prompt = str(messages[-1].content)
    png_bytes = generate_pixel_art(prompt)
    return mo.image(src=png_bytes, width=256, height=256)

chat = mo.ui.chat(chat_handler, prompts=["red sword", "blue potion", "cute cat", "gold crown"])
chat
Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support