Spaces:
Running on Zero

thirteen7's picture
Show live inference nodes and per-stage timings
d808dae verified
Raw History Blame Contribute Delete
5.39 kB
"""Run the recorded LEVIR inference pipeline in a single ZeroGPU lease."""
from dataclasses import dataclass
import gc
from importlib import metadata, util
from importlib.machinery import SourceFileLoader
from pathlib import Path
import sys
from time import perf_counter
from huggingface_hub import hf_hub_download, snapshot_download
from pipeline import ROOT, decision, next_stage, profile
MODEL_REPO = 'thirteen7/Critique-then-Rerank'
MODEL_REVISION = 'e0332dbdd6727dfd800480ca8a7cddf1912b0c52'
BASE_REPO = 'baselabs/elephant-1'
BASE_REVISION = 'b3f8a93462fb1051a9de031e94a7ff380e254072'
VISUAL_REPO = 'lcybuaa/RSCaMa'
VISUAL_REVISION = '3e527e6656b62cc615eab1d2f3fb73777cbbf62c'
@dataclass(frozen=True)
class Checkpoints:
visual: Path
generator: Path
base: Path
adapters: Path
def prepare(token):
weights = Path(snapshot_download(
MODEL_REPO, revision=MODEL_REVISION, token=token, allow_patterns=[
'weights/levir/generator.pt',
'weights/levir/stage[12]/adapter_config.json',
'weights/levir/stage[12]/adapter_model.safetensors',
],
)) / 'weights/levir'
base = Path(snapshot_download(BASE_REPO, revision=BASE_REVISION, token=False))
visual = Path(hf_hub_download(VISUAL_REPO, 'RSCaMa.pth', revision=VISUAL_REVISION, token=False))
return Checkpoints(visual, weights / 'generator.pt', base, weights)
def install_elephant_model():
if metadata.version('transformers') != '5.19.0':
raise RuntimeError('This demo requires the pinned Transformers release.')
module_name = 'transformers.models.qwen3_5.modeling_qwen3_5'
source = ROOT / 'vendor/OneJev/modeling_qwen3_5.py.reference'
if module_name in sys.modules:
if Path(sys.modules[module_name].__file__) != source:
raise RuntimeError('Unpatched Qwen3.5 was imported before the Elephant runtime.')
return
loader = SourceFileLoader(module_name, str(source))
spec = util.spec_from_loader(module_name, loader)
module = util.module_from_spec(spec)
sys.modules[module_name] = module
try:
loader.exec_module(module)
except Exception:
del sys.modules[module_name]
raise
def trace_case(record, checkpoints):
name = record['name']
timings = {}
row = {'name': name, 'timings': timings}
def active(activity):
return {'name': name, 'activity': activity, 'timings': timings.copy()}
def finished(step, **extra):
return {**row, 'timings': timings.copy(), 'step': step, **extra}
yield active('runtime')
started = perf_counter()
import torch
from caption.runner import beam, image_features, initialize
from judge.questions import stage1_questions, stage2_questions
from judge.runner import load, score
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():
raise RuntimeError('A BF16-capable CUDA GPU is required.')
install_elephant_model()
dataset = 'levir'
media_root = ROOT / 'public'
config = profile(dataset)
initialize()
timings['runtime'] = perf_counter() - started
yield active('encode')
started = perf_counter()
features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda')
row['feature_shape'] = list(features.shape)
timings['encode'] = perf_counter() - started
yield finished('encode')
yield active('beam')
started = perf_counter()
row['captions'] = beam(dataset, features, checkpoints.generator, 'cuda')[0]
timings['beam'] = perf_counter() - started
yield finished('beam')
rows = {name: row}
first = list(stage1_questions(dataset, [record], rows))
def score_stage(stage, questions):
key = f'stage{stage}'
yield active(f'{key}_load')
started = perf_counter()
runtime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}')
timings[f'{key}_load'] = perf_counter() - started
try:
yield active(f'{key}_score')
started = perf_counter()
row[key] = score(runtime, bundle, questions)[name]
timings[f'{key}_score'] = perf_counter() - started
finally:
del bundle
gc.collect()
torch.cuda.empty_cache()
timings[key] = timings[f'{key}_load'] + (perf_counter() - started)
yield from score_stage(1, first)
anchor = max(row['stage1'], key=lambda pair: pair[1])[0]
row['anchor'] = anchor
yield finished('stage1')
yield active('gate')
_, changed = next_stage(dataset, row['captions'], anchor, config['templates'])
row['changed'] = changed
yield finished('gate')
if changed:
yield active('filter')
second = list(stage2_questions(dataset, [record], rows, config['templates']))
row['eligible'] = list(second[0]['native_candidate_indices'].values()) if second else [index for index, _ in row['stage2']]
yield {key: value for key, value in finished('filter').items() if key != 'stage2'}
if second:
yield from score_stage(2, second)
yield finished('stage2')
yield active('output')
started = perf_counter()
final = decision(dataset, row, config['beta'], config['templates'])
timings['output'] = perf_counter() - started
yield finished('done', final=final)