"""Rosetta — Composable Native Multimodal (Tencent Hunyuan / HKUST). A ZeroGPU Gradio demo for tencent/Rosetta-inference (Rosetta-3.8B-A1B): * Text -> Image generation * Image + Text understanding (VLM) The upstream repo (github.com/Lxiangyue/Rosetta) is a research/eval codebase that places tensors on CUDA eagerly and uses accelerate device_map dispatch. To stay compatible with ZeroGPU's fork model, we build + load the model the first time a @spaces.GPU function runs (inside the GPU worker where real CUDA exists), then keep it resident on that warm worker. """ import os os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import spaces # noqa: E402 (must precede torch/CUDA imports) import struct import threading import urllib.request import zlib from pathlib import Path import gradio as gr import torch from huggingface_hub import snapshot_download # --------------------------------------------------------------------------- # # Paths / config # --------------------------------------------------------------------------- # REPO_ID = "tencent/Rosetta-inference" DATA_DIR = Path(os.environ.get("ROSETTA_DATA", "/tmp/rosetta_data")) CKPT_DIR = DATA_DIR / "checkpoints" / "Rosetta-3.8B-A1B" / "hf_weights" ASSETS_DIR = DATA_DIR / "public_assets" CONFIG_PATH = Path(__file__).parent / "rosetta.yaml" GEN_CFG_DIR = ASSETS_DIR / "generation_configs" # The rosetta package reads asset locations from these env vars at import time. os.environ["ASSETS_BASE"] = str(ASSETS_DIR) ZIP_URL = f"https://huggingface.co/{REPO_ID}/resolve/main/public_assets.zip" _sampler = None _load_lock = threading.Lock() # --------------------------------------------------------------------------- # # Asset download (runs once at startup, on the CPU disk) # --------------------------------------------------------------------------- # def _get_range(a, b): for attempt in range(6): try: req = urllib.request.Request(ZIP_URL, headers={"Range": f"bytes={a}-{b}"}) return urllib.request.urlopen(req, timeout=180).read() except Exception as e: # noqa: BLE001 print(f" range retry {attempt}: {e}", flush=True) raise RuntimeError("range request failed") def _parse_zip64_extra(extra, usize, csize, lho): off = 0 while off + 4 <= len(extra): hid, dsize = struct.unpack("