Spaces:
Running on Zero

File size: 5,392 Bytes
a369496
 
 
 
 
 
 
 
c38a7c7
a369496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eaecad
d808dae
 
 
 
 
 
 
 
 
 
 
 
a369496
 
 
 
 
 
 
 
 
 
 
c38a7c7
d808dae
 
 
 
a369496
c38a7c7
d808dae
 
 
 
c38a7c7
 
d808dae
 
a369496
c38a7c7
a369496
c38a7c7
d808dae
 
c38a7c7
a369496
d808dae
a369496
d808dae
 
 
 
a369496
 
 
 
d808dae
a369496
d808dae
a369496
f42c079
d808dae
 
c38a7c7
f42c079
d808dae
f42c079
d808dae
f42c079
 
d808dae
f42c079
d808dae
 
c38a7c7
d808dae
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
"""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)