MGI / task_template.py
nimasafa's picture
task template for participants
a2d7e3e verified
Raw
History Blame Contribute Delete
6.97 kB
"""
Sample submission script for the MGI task.
End-to-end pipeline:
1. Download the 900 reference images from the SprintML/MGI dataset repo
on Hugging Face (data/img_000.png .. data/img_899.png).
2. Download the RAR-XL generator weights (yucornetto/RAR) and the
MaskGIT-VQ tokenizer weights.
3. Build a valid 1800-slot submission.npz, following the same six-block
transition convention in the task description:
0000-0299 M->N 0300-0599 M->G 0600-0899 N->M
0900-1199 N->G 1200-1499 G->M 1500-1799 G->N
4. Submit it to the evaluation API.
build_submission() below is a placeholder that just returns random noise for
every slot. This is for familiarzing you with submission shape/format.
Please replace your own attack in its place.
"""
import os
import sys
import numpy as np
import requests
from pathlib import Path
from PIL import Image
from huggingface_hub import hf_hub_download, snapshot_download
BASE_DIR = Path(__file__).resolve().parent
# --- submission / API config -------------------------------------------------
BASE_URL = "http://35.192.205.84"
API_KEY = "YOUR_API_KEY_HERE"
TASK_ID = "29-mgi"
OUTPUT_PATH = "submission.npz"
# --- submission format ---------------------------------------------------
# 1800 slots, six 300-image blocks for the six required misclassifications:
# 0000-0299 M->N 0300-0599 M->G 0600-0899 N->M
# 0900-1199 N->G 1200-1499 G->M 1500-1799 G->N
BASE_IMAGES = 900 # underlying reference dataset (img_000.png .. img_899.png)
IMAGE_SIZE = 256
TOTAL_IMAGES = 1800 # submission slots
EXPECTED_NAMES = tuple(f"{index:04d}" for index in range(TOTAL_IMAGES))
# --- Hugging Face sources -----------------------------------------------------
HF_DATASET_REPO = "SprintML/MGI"
HF_DATA_SUBFOLDER = "data"
HF_RAR_REPO = "yucornetto/RAR" # RAR generator checkpoints (rar_xl.bin, ...)
HF_MASKGIT_REPO = "fun-research/TiTok" # MaskGIT-VQ tokenizer weight used by RAR
RAR_MODEL_SIZE = "rar_xl"
MODEL_DIR = BASE_DIR / "model"
# RAR-XL architecture config: the hyperparameters RAR/demo_util.py needs to
# build the model class match those in the official RAR repo's
# configs/training/generator/rar.yaml for the XL size (see rar/README_RAR.md).
# Written locally only if not already present.
RAR_XL_CONFIG = """\
experiment:
generator_checkpoint: ""
model:
vq_model:
codebook_size: 1024
token_size: 256
num_latent_tokens: 256
finetune_decoder: False
pretrained_tokenizer_weight: ""
generator:
hidden_size: 1280
num_hidden_layers: 32
num_attention_heads: 16
intermediate_size: 5120
dropout: 0.1
attn_drop: 0.1
class_label_dropout: 0.1
image_seq_len: 256
condition_num_classes: 1000
use_checkpoint: False
"""
def ensure_dataset() -> Path:
"""Download the 900 reference images from the HF dataset repo, if missing."""
local_dir = snapshot_download(
repo_id=HF_DATASET_REPO,
repo_type="dataset",
allow_patterns=[f"{HF_DATA_SUBFOLDER}/*.png"],
)
data_dir = Path(local_dir) / HF_DATA_SUBFOLDER
print(f"Reference dataset ready: {data_dir}")
return data_dir
def ensure_model_weights() -> tuple[Path, Path, Path]:
"""Download RAR-XL + MaskGIT-VQ weights and write a matching config, if missing."""
MODEL_DIR.mkdir(parents=True, exist_ok=True)
generator_ckpt = Path(
hf_hub_download(repo_id=HF_RAR_REPO, filename=f"{RAR_MODEL_SIZE}.bin")
)
tokenizer_ckpt = Path(
hf_hub_download(
repo_id=HF_MASKGIT_REPO, filename="maskgit-vqgan-imagenet-f16-256.bin"
)
)
config_path = MODEL_DIR / "rar.yaml"
if not config_path.exists():
config_path.write_text(RAR_XL_CONFIG)
print(f"Model weights ready: generator={generator_ckpt}, tokenizer={tokenizer_ckpt}")
return config_path, generator_ckpt, tokenizer_ckpt
def load_reference_images(data_dir: Path) -> np.ndarray:
"""Load the 900 reference dataset images as uint8 (BASE_IMAGES, 256, 256, 3)."""
images = np.empty((BASE_IMAGES, IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
for i in range(BASE_IMAGES):
with Image.open(data_dir / f"img_{i:03d}.png") as img:
images[i] = np.asarray(
img.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE), Image.BILINEAR),
dtype=np.uint8,
)
return images
def build_submission(original: np.ndarray, seed: int = 0) -> np.ndarray:
"""
Placeholder -- fill this in with your own attack.
Returns random noise for every one of the 1800 slots, just to show the
submission shape/format you need to produce. Scores 0 as-is.
"""
rng = np.random.default_rng(seed)
return rng.integers(
0, 256, size=(TOTAL_IMAGES, IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8
)
def make_submission_file(images: np.ndarray, output_path: str) -> None:
assert images.shape == (TOTAL_IMAGES, IMAGE_SIZE, IMAGE_SIZE, 3), images.shape
assert images.dtype == np.uint8, images.dtype
names = np.array(EXPECTED_NAMES)
np.savez_compressed(output_path, images=images, names=names)
print(f"Saved submission -> {output_path}")
def die(msg: str) -> None:
print(msg, file=sys.stderr)
sys.exit(1)
def submit(file_path: str) -> None:
if not os.path.isfile(file_path):
die(f"File not found: {file_path}")
try:
with open(file_path, "rb") as f:
files = {
"file": (os.path.basename(file_path), f, "application/octet-stream"),
}
resp = requests.post(
f"{BASE_URL}/submit/{TASK_ID}",
headers={"X-API-Key": API_KEY},
files=files,
)
try:
body = resp.json()
except Exception:
body = {"raw_text": resp.text}
if resp.status_code == 413:
die("Upload rejected: file too large (HTTP 413). Reduce size and try again.")
resp.raise_for_status()
submission_id = body.get("submission_id")
print("Successfully submitted.")
print("Server response:", body)
if submission_id:
print(f"Submission ID: {submission_id}")
except requests.exceptions.RequestException as e:
detail = getattr(e, "response", None)
print(f"Submission error: {e}")
if detail is not None:
try:
print("Server response:", detail.json())
except Exception:
print("Server response (text):", detail.text)
sys.exit(1)
if __name__ == "__main__":
data_dir = ensure_dataset()
ensure_model_weights() # downloads RAR-XL + MaskGIT-VQ weights for your own attack
original = load_reference_images(data_dir)
submitted = build_submission(original)
make_submission_file(submitted, OUTPUT_PATH)
submit(OUTPUT_PATH)