File size: 7,537 Bytes
3726258
 
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""Sub-tier labels: the base tiers and the variant tiers (k = 5, never-co-occurring cliques of 3 and 4
classes, small anchor), parsing of ``--tiers``, report order and per-anchor quotas.
"""
from __future__ import annotations

import zlib
from typing import Dict, List, Optional, Sequence, Tuple

import numpy as np

V1_LABELS: Tuple[str, ...] = (
    "tier1_natural_bg", "tier1_atypical_bg",
    "tier2_1typical", "tier2_1atypical",
    "tier3_2typical", "tier3_2atypical",
    "tier4_3typical", "tier4_3atypical",
    "tier5_4typical", "tier5_4atypical",
    "tier_never",
)

VARIANTS: Tuple[str, ...] = ("k5", "never_clique", "small_anchor")

VARIANT_TIERS: List[Tuple[str, str, int, str, str, str]] = [
    ("tier6_5typical", "typical", 5, "anchor_native", "k5", "tier6_5typical"),
    ("tier6_5atypical", "atypical", 5, "partner_native", "k5", "tier6_5atypical"),
    ("tier_never_k3", "never_clique", 3, "partner_native", "never_clique", "tier_never"),
    ("tier_never_k4", "never_clique", 4, "partner_native", "never_clique", "tier_never"),
    ("tier2_1typical__small_anchor", "typical", 1, "anchor_native", "small_anchor", "tier2_1typical"),
    ("tier2_1atypical__small_anchor", "atypical", 1, "partner_native", "small_anchor", "tier2_1atypical"),
]
VARIANT_OF_LABEL: Dict[str, str] = {t[0]: t[4] for t in VARIANT_TIERS}
NEVER_CLIQUE_LABELS: Tuple[str, ...] = tuple(t[0] for t in VARIANT_TIERS if t[1] == "never_clique")
SOLVER_ONLY_LABELS: Tuple[str, ...] = tuple(t[0] for t in VARIANT_TIERS if t[4] in ("k5", "never_clique"))

TIER_GROUPS: Dict[str, Tuple[str, ...]] = {
    "tier1": ("tier1_natural_bg", "tier1_atypical_bg"),
    "tier2": ("tier2_1typical", "tier2_1atypical"),
    "tier3": ("tier3_2typical", "tier3_2atypical"),
    "tier4": ("tier4_3typical", "tier4_3atypical"),
    "tier5": ("tier5_4typical", "tier5_4atypical"),
    "tier6": ("tier6_5typical", "tier6_5atypical"),
    "never": ("tier_never",),
    "never_k3": ("tier_never_k3",),
    "never_k4": ("tier_never_k4",),
    "tier2__small_anchor": ("tier2_1typical__small_anchor", "tier2_1atypical__small_anchor"),
}


def tag_label(base_label: str, variant: str) -> str:
    return f"{base_label}__{variant}"


def strip_variant(label: str) -> str:
    """``tier2_1typical__small_anchor`` -> ``tier2_1typical``; labels without a suffix pass through."""
    return label.split("__", 1)[0]


def variant_of_label(label: str) -> Optional[str]:

    parts = label.split("__", 1)
    if len(parts) == 2 and parts[1]:
        return parts[1]
    return VARIANT_OF_LABEL.get(label)


def variant_of_scene(scene: Dict) -> Optional[str]:
    """``scene["variant"]`` when the spec carries it, else derived from its sub_tier label."""
    v = scene.get("variant")
    if v:
        return str(v)
    return variant_of_label(str(scene.get("sub_tier", "")))


def prompt_base_label(label: str) -> str:

    base = strip_variant(label)
    if base in NEVER_CLIQUE_LABELS:
        return "tier_never"
    return base


def pair_label_of(label: str) -> Optional[str]:
    """The other half of a typical/atypical pair, with the same variant suffix; None for a
    never tier. ``tier1_natural_bg`` pairs with ``tier1_atypical_bg``."""
    base, sep, suffix = label.partition("__")
    tail = f"{sep}{suffix}" if sep else ""
    if base.startswith("tier_never"):
        return None
    if base == "tier1_natural_bg":
        return "tier1_atypical_bg" + tail
    if base == "tier1_atypical_bg":
        return "tier1_natural_bg" + tail
    if base.endswith("atypical"):
        return base[: -len("atypical")] + "typical" + tail
    if base.endswith("typical"):
        return base[: -len("typical")] + "atypical" + tail
    return None


def order_tiers(labels: Sequence[str]) -> List[str]:

    seen = set(labels)
    head = [t for t in V1_LABELS if t in seen]
    tail = sorted(t for t in seen if t not in V1_LABELS)
    return head + tail


def pair_tiers(labels: Sequence[str]) -> Tuple[List[Tuple[str, str]], List[str]]:
    """Split tier labels into (typical, atypical) pairs and singles. A never tier is a single;
    a pair half whose twin is absent is kept whole as a single too."""
    present = set(labels)
    pairs: List[Tuple[str, str]] = []
    singles: List[str] = []
    done = set()
    for t in order_tiers(labels):
        if t in done:
            continue
        other = pair_label_of(t)
        if other is not None and other in present and other not in done:
            typ, atyp = (t, other) if "atypical" not in strip_variant(t) else (other, t)
            pairs.append((typ, atyp))
            done.update((t, other))
        else:
            singles.append(t)
            done.add(t)
    return pairs, singles


def parse_tiers_arg(text: str) -> Dict[str, int]:
    """``"tier6=50,never_k3=100,tier2__small_anchor=50"`` -> ordered {sub_tier label: count}.

    A pair label gives ``count`` to BOTH halves (as ``--per-tier`` does for T2 to T5; unlike
    ``--per-tier``, ``tier1=N`` also gives N to each background arm rather than N/2). Unknown
    labels, repeated labels and non-integer counts raise ValueError."""
    counts: Dict[str, int] = {}
    seen_groups = set()
    for item in text.split(","):
        item = item.strip()
        if not item:
            continue
        if "=" not in item:
            raise ValueError(f"--tiers item {item!r} is not label=count")
        group, _, num = item.partition("=")
        group = group.strip()
        if group not in TIER_GROUPS:
            raise ValueError(f"--tiers: unknown label {group!r}; choose from {sorted(TIER_GROUPS)}")
        if group in seen_groups:
            raise ValueError(f"--tiers: label {group!r} given twice")
        seen_groups.add(group)
        try:
            n = int(num.strip())
        except ValueError:
            raise ValueError(f"--tiers: count for {group!r} must be an integer, got {num!r}")
        if n < 0:
            raise ValueError(f"--tiers: count for {group!r} must be >= 0")
        for label in TIER_GROUPS[group]:
            counts[label] = n
    if not counts:
        raise ValueError("--tiers is empty")
    return counts


def stable_hash(text: str) -> int:
    """Process-independent 32-bit hash (Python's ``hash`` of a str is salted per process)."""
    return zlib.crc32(text.encode("utf-8")) & 0xFFFFFFFF


def allocate_per_anchor(n_images: int, anchor_idxs: Sequence[int], seed: int,
                        tier_label: str, quota_cap: int = 0,
                        caps: Optional[Dict[int, int]] = None) -> Dict[int, int]:

    anchors = sorted(int(a) for a in anchor_idxs)
    if not anchors or n_images <= 0:
        return {}
    rng = np.random.default_rng([int(seed), stable_hash(tier_label)])
    cap_of = {a: (int(caps.get(a, 0)) if caps is not None else int(n_images)) for a in anchors}
    if quota_cap > 0:
        cap_of = {a: min(c, int(quota_cap)) for a, c in cap_of.items()}
    total_cap = sum(cap_of.values())
    n_target = min(int(n_images), total_cap)
    base = n_target // len(anchors)
    alloc = {a: min(base, cap_of[a]) for a in anchors}
    left = n_target - sum(alloc.values())
    order = [anchors[int(i)] for i in rng.permutation(len(anchors))]
    while left > 0:
        progressed = False
        for a in order:
            if left <= 0:
                break
            if alloc[a] < cap_of[a]:
                alloc[a] += 1
                left -= 1
                progressed = True
        if not progressed:
            break
    return {a: c for a, c in alloc.items() if c > 0}