Spaces:
Running on Zero

Critique-then-Rerank-ZeroGPU / judge /stage2_runtime.py
thirteen7's picture
Stage fixed-case Gradio ZeroGPU demo
a369496 verified
Raw History Blame Contribute Delete
7.05 kB
"""Isolated Elephant language and vision-merger QLoRA runtime."""
from contextlib import contextmanager
import hashlib
import json
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "vendor/OneJev"))
import torch
import bitsandbytes as bnb
from peft import LoraConfig, PeftModel
from transformers import AutoConfig, BitsAndBytesConfig, Qwen3_5ForConditionalGeneration
from qev import readout
from train import common, mm
def tensor_digest(tensor):
data = tensor.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()
return hashlib.sha256(data).hexdigest()
def load_model(base_dir, image_root, adapter=None, seed=17, sdpa_backend="math"):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.benchmark = False
# The fused SDPA backward varied by 1.1% on this SM120/BF16 stack.
# The math kernel gives exact repeated and checkpointed gradient parity.
if sdpa_backend not in ("math", "auto"):
raise ValueError(f"Unsupported SDPA backend {sdpa_backend}")
optimized_attention = sdpa_backend == "auto"
torch.backends.cuda.enable_flash_sdp(optimized_attention)
torch.backends.cuda.enable_mem_efficient_sdp(optimized_attention)
torch.backends.cuda.enable_cudnn_sdp(optimized_attention)
torch.backends.cuda.enable_math_sdp(True)
torch.set_num_threads(8)
mm.set_root(image_root)
bundle = common.load_bundle(str(base_dir), multimodal=True, load_model=False)
config = AutoConfig.from_pretrained(base_dir, local_files_only=True)
if config.modeling_overrides["attention"] != {
"full_attention": "block_bidirectional", "linear_attention": "causal",
}:
raise ValueError("The published attention overrides must be preserved")
quantization = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
llm_int8_skip_modules=["model.visual", "lm_head"],
)
model = Qwen3_5ForConditionalGeneration.from_pretrained(
base_dir,
config=config,
dtype=torch.bfloat16,
quantization_config=quantization,
device_map={"": "cuda:0"},
attn_implementation="sdpa",
local_files_only=True,
low_cpu_mem_usage=True,
)
model.requires_grad_(False)
model.config.use_cache = False
model.config.get_text_config().use_cache = False
bundle.readout = readout.Readout.attach(
model, readout.ReadoutConfig.load(base_dir), slot_ids=bundle.slot_ids,
)
if adapter is not None:
lora = LoraConfig.from_pretrained(adapter)
vision_targets = ["model.visual.merger.linear_fc1", "model.visual.merger.linear_fc2"]
lora.target_modules = set(lora.target_modules) | set(vision_targets)
model = PeftModel.from_pretrained(
model, adapter, config=lora, is_trainable=False,
)
bundle.model = model
model.eval()
base = model.get_base_model() if isinstance(model, PeftModel) else model
base.model.visual.eval()
assert all(not parameter.requires_grad or "merger." in name and "lora_" in name
for name, parameter in base.model.visual.named_parameters())
assert not any(isinstance(module, bnb.nn.Linear4bit) for module in base.model.visual.modules())
assert base.get_input_embeddings().weight.dtype == torch.bfloat16
assert base.lm_head.weight.dtype == torch.bfloat16
metadata = {
"trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad),
"trainable_tensors": sum(p.requires_grad for p in model.parameters()),
"quantized_language_linears": sum(isinstance(m, bnb.nn.Linear4bit) for m in model.modules()),
"frozen_vision_backbone": True,
"merger_lora_parameters": sum(p.numel() for n, p in model.named_parameters()
if ".visual.merger." in n and "lora_" in n),
"attention": bundle.readout.config.attention,
"sdpa_backend": sdpa_backend,
"readout": bundle.readout.config.readout,
"memory_allocated": torch.cuda.memory_allocated(),
}
print("MODEL_LOADED", json.dumps(metadata), flush=True)
return bundle, metadata
def prepare_batch(bundle, rows, seed=None):
examples = [
common.render_example(row, bundle.template_for(row), index,
seed=None if seed is None else seed + index, augment=False)
for index, row in enumerate(rows)
]
inputs, ends = mm.mm_inputs(
bundle.processor, [example.prompt for example in examples],
[row["media"] for row in rows], "cuda:0",
)
prefixes = []
for example, row, end in zip(examples, rows, ends):
ids, prefix, _ = readout.token_layout(
bundle.tokenizer, example.prompt, example.suffix_start, example.option_spans,
)
shift = bundle.counter.media_extra(row["media"])
if len(ids) + shift != end + 1:
raise ValueError("The multimodal token layout does not match the real processor")
prefixes.append(prefix + shift)
width = inputs["input_ids"].shape[1]
if width > 1024:
raise ValueError(f"Row exceeds the declared token budget: {width}")
block_ids = readout.block_ids(prefixes, [end + 1 for end in ends], width, "cuda:0")
kmax = max(len(example.labels) for example in examples)
targets = torch.zeros(len(rows), kmax, device="cuda:0")
for index, example in enumerate(examples):
targets[index, :len(example.target)] = torch.tensor(example.target, device="cuda:0")
return {
"examples": examples, "inputs": inputs, "ends": ends,
"prefixes": prefixes, "block_ids": block_ids, "targets": targets,
}
@contextmanager
def scoring_context(batch, causal=False):
# This context stays open during backward as well as forward.
with readout.blocks(None if causal else batch["block_ids"]):
with torch.autocast("cuda", dtype=torch.bfloat16):
yield
def score_batch(bundle, batch):
logits = mm.mm_readout_logits(bundle.model, batch["inputs"], batch["ends"])
ks = [len(example.labels) for example in batch["examples"]]
return common.slot_view(logits, bundle.slot_ids, ks)
@torch.no_grad()
def predict(bundle, rows, seed=None, causal=False):
batch = prepare_batch(bundle, rows, seed=seed)
with scoring_context(batch, causal=causal):
logits, mask = score_batch(bundle, batch)
probabilities = logits.softmax(dim=-1).cpu().tolist()
return [
{label: probabilities[index][position] for position, label in enumerate(example.labels)}
for index, example in enumerate(batch["examples"])
]