无限 SVG 作品:将视觉世界投射到 SVG-Anything
Unlimited SVG Works: Projection of Visual Worlds into SVG-Anything

原始链接: https://github.com/baidu/Unlimited-SVG/

Unlimited-SVG 是百度文心(ERNIE)多模态模型,仅使用约 0.5B 激活参数,就能将任意图像转换为结构化、可编辑的 SVG。它基于 DeepSeek-OCR 构建,使用 DeepEncoder 将 2048×2048 图像压缩为 1024 个视觉 token,同时保留细小的文字、笔画和空间细节,并采用 MoE 解码器保持激活计算稀疏。这使其能够在可本地部署、支持 BF16 的 NVIDIA GPU 上实时生成超过 10,000 个 token 的长 SVG,避免依赖重量级前沿 API。该项目提供 Hugging Face(baidu/Unlimited-SVG)和 ModelScope 发布版本,并附带演示。说明涵盖通过 uv 安装依赖、通过填充/Alpha 合成将图像预处理为 2048×2048,以及使用 Transformers 或 vLLM 运行推理。输出默认采用贪心生成;较低温度适用于 CAD/图表/文字密集型图像,较高温度则有助于处理照片。脚本会验证并保存提取出的 SVG 输出。

黑客新闻 最新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 投稿 登录 无限 SVG 作品:将视觉世界投影到 SVG-Anything (github.com/baidu) 8 分,由 tingletech 发布于 1 小时前 | 过往 | 收藏 | 讨论 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请加入 YC | 联系 搜索:
相关文章

原文

Unlimited SVG Works: Trace On — Projection of Visual Worlds into SVG-Anything.

  • [2026/12/01] 🤝 Thanks to AK and Hugging Face for creating a demo for us. It is now available at Hugging Face Spaces.
  • [2026/12/01] 🤝 Thanks to the ModelScope community for their support. Our model is now available at ModelScope.
  • [2026/12/01] 🚀 We present Unlimited-SVG, a multimodal model that redraws any image as a structured, editable SVG using just 0.5B activated parameters.

Generating a complete SVG for a complex image often exceeds 10,000 tokens—a long-context regime where large models quickly become slow and prohibitive. Built on DeepSeek-OCR, Unlimited SVG breaks this bottleneck from both ends.

On the input side, DeepEncoder compresses an entire 2048 × 2048 image into just 1024 vision tokens while preserving fine details such as small text, thin strokes, and exact spatial coordinates—dramatically shrinking the visual prefix before decoding even begins.

On the decoding side, its mixture-of-experts (MoE) architecture activates only ~0.5B parameters per token. Minimal visual prefix meets sparse active compute: Unlimited SVG sustains real-time generation well past 10,000 tokens—making long-horizon, complex SVG conversion practical on a compact, locally deployable model rather than relying on heavy frontier APIs like GPT-6.2 Astra, Claude Fable 5.2 and Gemini 4 Argon.

Run from the repository root on x86-64 Linux with uv, a compatible NVIDIA driver, and a free BF16-capable GPU. Use the Hugging Face model baidu/Unlimited-SVG, which supports 2048 × 2048 global inference. Both examples use ImageOps.pad to resize the long edge to 2048 pixels while preserving the aspect ratio, then center the image on a gray 2048 × 2048 canvas without tiling. Transparent pixels are composited onto white first, so images with alpha do not turn black.

Both examples run greedily by default (do_sample=False in Transformers, temperature=0 in vLLM) for deterministic output. Tune the sampling temperature to the image type:

  • CAD, diagrams, charts, and other images that need exact detail consistency: keep the temperature low (e.g., 0–0.3) to preserve precise geometry and text.
  • Natural scenes and photos: raise the temperature (e.g., 0.5–0.8) to avoid repetitive loops and encourage more varied strokes.

To sample with Transformers, pass do_sample=True and a temperature instead of the greedy override above; with vLLM, set temperature in the request.

Install dependencies.

uv venv .venv-svg-hf --python 3.12
uv pip install --python .venv-svg-hf/bin/python \
  torch==2.6.0 torchvision==0.21.0 transformers==4.46.3 tokenizers==0.20.3 \
  safetensors==0.8.0 pillow==13.0.0 einops==0.8.2 addict==2.4.0 \
  easydict==1.14 accelerate==1.16.0 requests==2.34.2 \
  huggingface_hub==0.36.0

Save the following code as infer_hf.py.

import re
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from xml.etree import ElementTree

import torch
from PIL import Image, ImageOps
from huggingface_hub import snapshot_download
from safetensors import safe_open
from safetensors.torch import load_file
from transformers import AutoModel, AutoTokenizer

model_name = "baidu/Unlimited-SVG"
image_path = sys.argv[1]


def flatten_alpha(image):
    """Composite transparent pixels onto white so they do not turn black."""
    if image.mode not in ("RGBA", "LA", "PA") and "transparency" not in image.info:
        return image.convert("RGB")
    rgba = image.convert("RGBA")
    white = Image.new("RGB", rgba.size, (255, 255, 255))
    white.paste(rgba, mask=rgba.getchannel("A"))
    return white


model_path = snapshot_download(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
options = {"low_cpu_mem_usage": True}
weights = list(Path(model_path).glob("model*.safetensors"))
if len(weights) == 1:
    with safe_open(weights[0], framework="pt", device="cpu") as shard:
        metadata = shard.metadata()
    if metadata is None:
        options = {"low_cpu_mem_usage": False, "state_dict": load_file(weights[0])}

model = AutoModel.from_pretrained(
    model_path, trust_remote_code=True, use_safetensors=True,
    torch_dtype=torch.bfloat16, attn_implementation="eager", **options,
).eval().cuda()
original_generate = model.generate

def generate(*args, **kwargs):
    kwargs.pop("temperature", None)
    kwargs.update(max_new_tokens=30000, no_repeat_ngram_size=0,
                  do_sample=False, repetition_penalty=1)
    return original_generate(*args, **kwargs)

model.generate = generate
with TemporaryDirectory() as directory:
    prepared = Path(directory) / "input.png"
    with Image.open(image_path) as image:
        ImageOps.pad(
            flatten_alpha(ImageOps.exif_transpose(image)), (2048, 2048),
            method=Image.Resampling.BICUBIC, color=(127, 127, 127),
        ).save(prepared)
    with torch.inference_mode():
        raw = model.infer(
            tokenizer, prompt="<image> SVG:", image_file=str(prepared),
            output_path=directory, base_size=2048, image_size=2048,
            crop_mode=False, eval_mode=True,
        )

Path("output.txt").write_text(raw, encoding="utf-8")
match = re.search(r"<svg\b.*?</svg>", raw, re.DOTALL)
if match is None:
    raise RuntimeError("Incomplete SVG. See output.txt.")
svg = match.group()
ElementTree.fromstring(svg)
Path("output.svg").write_text(svg, encoding="utf-8")
CUDA_VISIBLE_DEVICES=0 .venv-svg-hf/bin/python infer_hf.py /path/to/image.png

The first run downloads the model weights from Hugging Face and stores them in the local Hugging Face cache. Subsequent runs reuse the cached files.

Install dependencies.

uv venv .venv-svg-vllm --python 3.12
uv pip install --python .venv-svg-vllm/bin/python \
  vllm==0.33.0 torch==2.14.0 nvidia-cudnn-cu13==9.24.0.43 \
  openai==3.60.0 pillow==13.0.0

Set the server image processor to 2048 × 2048 without tiling.

.venv-svg-vllm/bin/python - <<'PY'
import re
import sysconfig
from pathlib import Path

path = Path(sysconfig.get_path("purelib")) / "vllm/transformers_utils/processors/deepseek_ocr.py"
source = path.read_text()
for name, value in {"BASE_SIZE": 2048, "IMAGE_SIZE": 2048, "CROP_MODE": False}.items():
    source, count = re.subn(rf"^{name} = .+$", f"{name} = {value}", source, flags=re.M)
    if count != 1:
        raise RuntimeError(f"Cannot configure {name}")
temporary = path.with_suffix(".py.tmp")
temporary.write_text(source)
temporary.replace(path)
PY

Start the server in a terminal.

VLLM_CUDNN_LIB="$PWD/.venv-svg-vllm/lib/python3.12/site-packages/nvidia/cudnn/lib"
LD_LIBRARY_PATH="$VLLM_CUDNN_LIB${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
  CUDA_VISIBLE_DEVICES=0 VLLM_USE_V2_MODEL_RUNNER=0 TRITON_ALLOW_NON_CONSTEXPR_GLOBALS=1 \
  .venv-svg-vllm/bin/vllm serve baidu/Unlimited-SVG \
  --served-model-name Unlimited-SVG --trust-remote-code \
  --no-enable-prefix-caching --mm-processor-cache-gb 0 \
  --limit-mm-per-prompt '{"image":1}' --max-model-len 32768 --max-num-seqs 1 \
  --gpu-memory-utilization 0.8 \
  --compilation-config '{"cudagraph_mode":"FULL_DECODE_ONLY","cudagraph_capture_sizes":[1,2,4,8]}' \
  --host 127.0.0.1 --port 10000

Save the following code as infer_vllm.py.

import base64
import io
import re
import sys
from pathlib import Path
from xml.etree import ElementTree

from openai import OpenAI
from PIL import Image, ImageOps


def flatten_alpha(image):
    """Composite transparent pixels onto white so they do not turn black."""
    if image.mode not in ("RGBA", "LA", "PA") and "transparency" not in image.info:
        return image.convert("RGB")
    rgba = image.convert("RGBA")
    white = Image.new("RGB", rgba.size, (255, 255, 255))
    white.paste(rgba, mask=rgba.getchannel("A"))
    return white


buffer = io.BytesIO()
with Image.open(sys.argv[1]) as image:
    ImageOps.pad(
        flatten_alpha(ImageOps.exif_transpose(image)), (2048, 2048),
        method=Image.Resampling.BICUBIC, color=(127, 127, 127),
    ).save(buffer, format="PNG")
url = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
client = OpenAI(base_url="http://127.0.0.1:10000/v1", api_key="EMPTY", timeout=6000)
raw_path = Path("output-vllm.txt")
with client.chat.completions.create(
    model="Unlimited-SVG",
    messages=[{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": url}},
        {"type": "text", "text": "<image> SVG:"},
    ]}],
    temperature=0, top_p=1, max_tokens=30000, stream=True,
    extra_body={"top_k": 0, "repetition_penalty": 1},
) as stream, raw_path.open("w", encoding="utf-8") as output:
    for chunk in stream:
        if chunk.choices:
            output.write(chunk.choices[0].delta.content or "")

match = re.search(r"<svg\b.*?</svg>", raw_path.read_text(encoding="utf-8"), re.DOTALL)
if match is None:
    raise RuntimeError("Incomplete SVG. See output-vllm.txt.")
svg = match.group()
ElementTree.fromstring(svg)
Path("output-vllm.svg").write_text(svg, encoding="utf-8")

Run inference in a second terminal once the server is ready.

.venv-svg-vllm/bin/python infer_vllm.py /path/to/image.png
@misc{unlimitedsvg2026,
  title  = {Unlimited SVG Works: Trace On -- Projection of Visual Worlds into SVG-Anything},
  author = {Baidu ERNIE, Multimodal Team},
  year   = {2026},
  url    = {https://unlimited-svg.github.io/}
}
联系我们 contact @ memedata.com