iqd2rad 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- iqd2rad/__init__.py +3 -0
- iqd2rad/analysis/__init__.py +5 -0
- iqd2rad/analysis/cli.py +109 -0
- iqd2rad/analysis/core.py +314 -0
- iqd2rad/analysis/plotting.py +42 -0
- iqd2rad/data/__init__.py +6 -0
- iqd2rad/data/cli.py +75 -0
- iqd2rad/data/frames.py +51 -0
- iqd2rad/data/manifests.py +115 -0
- iqd2rad/data/prepare.py +432 -0
- iqd2rad/evaluation/__init__.py +5 -0
- iqd2rad/evaluation/cli.py +44 -0
- iqd2rad/evaluation/core.py +193 -0
- iqd2rad/models/__init__.py +1 -0
- iqd2rad/models/encode.py +124 -0
- iqd2rad/models/qwen.py +269 -0
- iqd2rad/training/__init__.py +1 -0
- iqd2rad/training/cli.py +43 -0
- iqd2rad/training/config.py +110 -0
- iqd2rad/training/data.py +89 -0
- iqd2rad/training/loss.py +127 -0
- iqd2rad/training/trainer.py +313 -0
- iqd2rad-0.1.0.dist-info/METADATA +242 -0
- iqd2rad-0.1.0.dist-info/RECORD +28 -0
- iqd2rad-0.1.0.dist-info/WHEEL +4 -0
- iqd2rad-0.1.0.dist-info/entry_points.txt +6 -0
- iqd2rad-0.1.0.dist-info/licenses/LICENSE +201 -0
- iqd2rad-0.1.0.dist-info/licenses/NOTICE +10 -0
iqd2rad/__init__.py
ADDED
iqd2rad/analysis/cli.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Run offline IQD measurement on an explicitly aligned embedding archive."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from .core import analyze_sweep, load_embeddings
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _csv_ints(text: str) -> list[int]:
|
|
17
|
+
try:
|
|
18
|
+
values = [int(item.strip()) for item in text.split(",")]
|
|
19
|
+
except ValueError as exc:
|
|
20
|
+
raise argparse.ArgumentTypeError("Expected comma-separated integers") from exc
|
|
21
|
+
if not values:
|
|
22
|
+
raise argparse.ArgumentTypeError("Expected at least one integer")
|
|
23
|
+
return values
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
27
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
28
|
+
parser.add_argument("--embeddings", type=Path, required=True, help="NPZ with query_embeddings, candidate_embeddings, correct_indices")
|
|
29
|
+
parser.add_argument("--output-dir", type=Path, required=True)
|
|
30
|
+
parser.add_argument("--config", type=Path, help="JSON sweep manifest; explicit flags override its analysis fields")
|
|
31
|
+
parser.add_argument("--dims", type=_csv_ints, help="Explicit prefix dimensions, e.g. 128,256,512,2048; no native dimension is appended")
|
|
32
|
+
parser.add_argument("--bits", type=_csv_ints, help="Bit widths, default 1,2,4,8,16")
|
|
33
|
+
parser.add_argument("--k", type=int, help="Recall@k and density neighborhood, default 10")
|
|
34
|
+
parser.add_argument("--symmetric", action=argparse.BooleanOptionalAction, default=None,
|
|
35
|
+
help="Average forward/reverse metrics for a bijective pair pool; default false")
|
|
36
|
+
parser.add_argument("--block-size", type=int, default=512, help="Similarity rows per CPU block")
|
|
37
|
+
parser.add_argument("--plots", action="store_true", help="Write correlation heatmaps (requires matplotlib)")
|
|
38
|
+
parser.add_argument("--overwrite", action="store_true", help="Replace analysis outputs in an existing result directory")
|
|
39
|
+
return parser
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _file_hash(path: Path) -> str:
|
|
43
|
+
digest = hashlib.sha256()
|
|
44
|
+
with path.open("rb") as source:
|
|
45
|
+
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
|
46
|
+
digest.update(chunk)
|
|
47
|
+
return digest.hexdigest()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def run(args: argparse.Namespace) -> Path:
|
|
51
|
+
manifest = {}
|
|
52
|
+
if args.config:
|
|
53
|
+
manifest = json.loads(args.config.read_text(encoding="utf-8"))
|
|
54
|
+
if not isinstance(manifest, dict):
|
|
55
|
+
raise ValueError("The IQD config must be a JSON object")
|
|
56
|
+
if manifest.get("quantization", "iqd_fixed_symmetric_grid") != "iqd_fixed_symmetric_grid":
|
|
57
|
+
raise ValueError("Expected quantization='iqd_fixed_symmetric_grid'")
|
|
58
|
+
dims = args.dims if args.dims is not None else manifest.get("dims")
|
|
59
|
+
if dims is None:
|
|
60
|
+
raise ValueError("Specify --dims or a config containing an explicit dims list")
|
|
61
|
+
bits = args.bits if args.bits is not None else manifest.get("bits", [1, 2, 4, 8, 16])
|
|
62
|
+
k = args.k if args.k is not None else manifest.get("k", 10)
|
|
63
|
+
symmetric = args.symmetric if args.symmetric is not None else manifest.get("symmetric", False)
|
|
64
|
+
if not isinstance(symmetric, bool):
|
|
65
|
+
raise ValueError("Config symmetric must be a JSON boolean")
|
|
66
|
+
data = load_embeddings(args.embeddings)
|
|
67
|
+
native_dim = manifest.get("native_dimension")
|
|
68
|
+
if native_dim is not None and native_dim != data.query_embeddings.shape[1]:
|
|
69
|
+
raise ValueError(f"Config expects native_dimension={native_dim}, archive has {data.query_embeddings.shape[1]}")
|
|
70
|
+
expected_count = manifest.get("expected_query_count")
|
|
71
|
+
if expected_count is not None and expected_count != len(data.query_embeddings):
|
|
72
|
+
raise ValueError(f"Config expects {expected_count} queries, archive has {len(data.query_embeddings)}")
|
|
73
|
+
summary_path = args.output_dir / "summary.json"
|
|
74
|
+
if not args.overwrite and (summary_path.exists() or (args.output_dir.exists() and any(args.output_dir.glob("samples_d*_b*.npz")))):
|
|
75
|
+
raise FileExistsError("Analysis outputs already exist; choose a new output directory or use --overwrite")
|
|
76
|
+
plot = None
|
|
77
|
+
if args.plots:
|
|
78
|
+
# Check optional dependencies before writing partial analysis outputs.
|
|
79
|
+
from .plotting import plot_correlations
|
|
80
|
+
plot = plot_correlations
|
|
81
|
+
provenance = manifest.get("encoding_provenance_status")
|
|
82
|
+
if provenance == "unverified":
|
|
83
|
+
print("Warning: this manifest's embedding-export provenance has not been verified; the run is an analysis, not a certified paper reproduction.", file=sys.stderr)
|
|
84
|
+
summary, samples = analyze_sweep(data, dims, bits, k=k, symmetric=symmetric, block_size=args.block_size)
|
|
85
|
+
summary["source"] = {"file": args.embeddings.name, "sha256": _file_hash(args.embeddings)}
|
|
86
|
+
if manifest:
|
|
87
|
+
summary["manifest"] = manifest
|
|
88
|
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
for key, arrays in samples.items():
|
|
90
|
+
np.savez_compressed(args.output_dir / f"samples_{key}.npz", **arrays)
|
|
91
|
+
summary_path.write_text(json.dumps(summary, indent=2, allow_nan=False) + "\n", encoding="utf-8")
|
|
92
|
+
if plot is not None:
|
|
93
|
+
plot(summary, args.output_dir / "predictor_correlations.png")
|
|
94
|
+
return summary_path
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def main(argv: list[str] | None = None) -> int:
|
|
98
|
+
parser = build_parser()
|
|
99
|
+
args = parser.parse_args(argv)
|
|
100
|
+
try:
|
|
101
|
+
output = run(args)
|
|
102
|
+
except (OSError, ValueError, TypeError, ImportError) as exc:
|
|
103
|
+
parser.error(str(exc))
|
|
104
|
+
print(f"IQD results: {output}")
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__":
|
|
109
|
+
raise SystemExit(main())
|
iqd2rad/analysis/core.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""IQD definitions extracted from the research implementation.
|
|
2
|
+
|
|
3
|
+
Derived from ``scripts/finetune/validate_iqd.py`` and
|
|
4
|
+
``scripts/finetune/validate_iqd_gt.py`` of HiQ, under Apache-2.0.
|
|
5
|
+
The original candidate-side density/LID, fixed-grid quantization, rank ties,
|
|
6
|
+
and loss-gap definitions are retained. Ground truth is always explicit.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Iterable
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from scipy.stats import spearmanr
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
PREDICTORS = (
|
|
20
|
+
"quant_error", "density", "iqd_combined", "margin_float",
|
|
21
|
+
"margin_erosion", "lid", "inv_margin_float", "focal_weight", "online_diff",
|
|
22
|
+
)
|
|
23
|
+
STRATIFIERS = (
|
|
24
|
+
"iqd_combined", "margin_erosion", "focal_weight", "online_diff",
|
|
25
|
+
"inv_margin_float", "lid",
|
|
26
|
+
)
|
|
27
|
+
QUANTIZATION = {
|
|
28
|
+
"name": "iqd_fixed_symmetric_grid",
|
|
29
|
+
"input_normalization": "L2 per vector after prefix truncation",
|
|
30
|
+
"range": [-1.0, 1.0],
|
|
31
|
+
"one_bit": "numpy.sign; exact zeros remain zero",
|
|
32
|
+
"multi_bit": "2**bits uniformly spaced levels, numpy.round",
|
|
33
|
+
"similarity": "cosine after L2-normalizing quantized vectors",
|
|
34
|
+
"calibration": "none",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _matrix(value: np.ndarray, name: str) -> np.ndarray:
|
|
39
|
+
value = np.asarray(value)
|
|
40
|
+
if value.ndim != 2 or not all(value.shape):
|
|
41
|
+
raise ValueError(f"{name} must be a non-empty 2D array")
|
|
42
|
+
if value.dtype.kind not in "fiu":
|
|
43
|
+
raise ValueError(f"{name} must contain real numbers")
|
|
44
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
45
|
+
value = value.astype(np.float32)
|
|
46
|
+
if not np.isfinite(value).all():
|
|
47
|
+
raise ValueError(f"{name} must contain only finite float32 values")
|
|
48
|
+
if np.any(np.linalg.norm(value, axis=1) == 0):
|
|
49
|
+
raise ValueError(f"{name} contains a zero-length embedding")
|
|
50
|
+
return value
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _ids(value: np.ndarray | None, n: int, name: str) -> np.ndarray | None:
|
|
54
|
+
if value is None:
|
|
55
|
+
return None
|
|
56
|
+
value = np.asarray(value)
|
|
57
|
+
if value.shape != (n,) or value.dtype.kind not in "US":
|
|
58
|
+
raise ValueError(f"{name} must be a length-{n} string array (not object dtype)")
|
|
59
|
+
value = value.astype(str)
|
|
60
|
+
if len(np.unique(value)) != n:
|
|
61
|
+
raise ValueError(f"{name} must be unique")
|
|
62
|
+
return value
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class EmbeddingData:
|
|
67
|
+
query_embeddings: np.ndarray
|
|
68
|
+
candidate_embeddings: np.ndarray
|
|
69
|
+
correct_indices: np.ndarray
|
|
70
|
+
query_ids: np.ndarray | None = None
|
|
71
|
+
candidate_ids: np.ndarray | None = None
|
|
72
|
+
|
|
73
|
+
def __post_init__(self) -> None:
|
|
74
|
+
self.query_embeddings = _matrix(self.query_embeddings, "query_embeddings")
|
|
75
|
+
self.candidate_embeddings = _matrix(self.candidate_embeddings, "candidate_embeddings")
|
|
76
|
+
n, d = self.query_embeddings.shape
|
|
77
|
+
m, cd = self.candidate_embeddings.shape
|
|
78
|
+
if d != cd:
|
|
79
|
+
raise ValueError("Query and candidate embedding dimensions must match")
|
|
80
|
+
if m < 2:
|
|
81
|
+
raise ValueError("IQD requires at least two candidates")
|
|
82
|
+
gold = np.asarray(self.correct_indices)
|
|
83
|
+
if gold.shape != (n,) or gold.dtype.kind not in "iu":
|
|
84
|
+
raise ValueError("correct_indices must be one integer candidate index per query")
|
|
85
|
+
if np.any(gold < 0) or np.any(gold >= m):
|
|
86
|
+
raise ValueError("Missing or out-of-range ground truth in correct_indices")
|
|
87
|
+
self.correct_indices = gold.astype(np.int64)
|
|
88
|
+
self.query_ids = _ids(self.query_ids, n, "query_ids")
|
|
89
|
+
self.candidate_ids = _ids(self.candidate_ids, m, "candidate_ids")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def load_embeddings(path: str | Path) -> EmbeddingData:
|
|
93
|
+
"""Load an NPZ without executing pickle content or inferring diagonal GT."""
|
|
94
|
+
required = ("query_embeddings", "candidate_embeddings", "correct_indices")
|
|
95
|
+
with np.load(path, allow_pickle=False) as archive:
|
|
96
|
+
missing = [name for name in required if name not in archive]
|
|
97
|
+
if missing:
|
|
98
|
+
raise ValueError(f"Embedding NPZ is missing: {', '.join(missing)}")
|
|
99
|
+
return EmbeddingData(
|
|
100
|
+
**{name: archive[name] for name in required},
|
|
101
|
+
query_ids=archive["query_ids"] if "query_ids" in archive else None,
|
|
102
|
+
candidate_ids=archive["candidate_ids"] if "candidate_ids" in archive else None,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def l2_normalize(x: np.ndarray) -> np.ndarray:
|
|
107
|
+
return x / np.clip(np.linalg.norm(x, axis=1, keepdims=True), 1e-12, None)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def uniform_quantize(x: np.ndarray, bits: int) -> np.ndarray:
|
|
111
|
+
"""IQD's fixed grid; it does not fit per-vector or per-channel extrema."""
|
|
112
|
+
if isinstance(bits, bool) or not isinstance(bits, (int, np.integer)) or not 1 <= bits <= 16:
|
|
113
|
+
raise ValueError("bits must be an integer in [1, 16]")
|
|
114
|
+
x = l2_normalize(np.asarray(x, dtype=np.float32))
|
|
115
|
+
if bits == 1:
|
|
116
|
+
return np.sign(x)
|
|
117
|
+
levels = (1 << int(bits)) - 1
|
|
118
|
+
return np.round(np.clip((x + 1.0) / 2.0, 0.0, 1.0) * levels) / levels * 2.0 - 1.0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _candidate_geometry(candidates: np.ndarray, k: int, block_size: int) -> tuple[np.ndarray, np.ndarray]:
|
|
122
|
+
"""Density and clipped LID on the candidate pool, excluding self."""
|
|
123
|
+
z = l2_normalize(candidates)
|
|
124
|
+
n = len(z)
|
|
125
|
+
density_k, lid_k = min(k, n - 1), min(20, n - 1)
|
|
126
|
+
density = np.empty(n, dtype=np.float32)
|
|
127
|
+
lid = np.empty(n, dtype=np.float32)
|
|
128
|
+
for start in range(0, n, block_size):
|
|
129
|
+
stop = min(start + block_size, n)
|
|
130
|
+
sim = z[start:stop] @ z.T
|
|
131
|
+
sim[np.arange(stop - start), np.arange(start, stop)] = -np.inf
|
|
132
|
+
nearest = np.partition(-sim, kth=density_k - 1, axis=1)[:, :density_k]
|
|
133
|
+
density[start:stop] = -nearest.mean(axis=1)
|
|
134
|
+
distances = np.sqrt(np.maximum(2.0 - 2.0 * sim, 0.0))
|
|
135
|
+
nearest_d = np.sort(np.partition(distances, kth=lid_k - 1, axis=1)[:, :lid_k], axis=1)
|
|
136
|
+
ratios = np.clip(nearest_d / np.clip(nearest_d[:, -1:], 1e-12, None), 1e-12, 1.0)
|
|
137
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
138
|
+
estimates = -lid_k / np.log(ratios).sum(axis=1)
|
|
139
|
+
# Preserve the research estimator, including its [0, 1000] clipping.
|
|
140
|
+
lid[start:stop] = np.clip(estimates, 0.0, 1000.0)
|
|
141
|
+
return density, lid
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _directional_metrics(
|
|
145
|
+
qf: np.ndarray, cf: np.ndarray, qq: np.ndarray, cq: np.ndarray,
|
|
146
|
+
correct: np.ndarray, k: int, block_size: int,
|
|
147
|
+
) -> dict[str, np.ndarray]:
|
|
148
|
+
keys = ("rank_float", "rank_quant", "hit_float", "hit_quant", "margin_float", "margin_quant", "focal_weight", "online_diff")
|
|
149
|
+
result = {name: np.empty(len(qf), dtype=np.float32) for name in keys}
|
|
150
|
+
for start in range(0, len(qf), block_size):
|
|
151
|
+
stop = min(start + block_size, len(qf))
|
|
152
|
+
gold = correct[start:stop]
|
|
153
|
+
rows = np.arange(stop - start)
|
|
154
|
+
sf, sq = qf[start:stop] @ cf.T, qq[start:stop] @ cq.T
|
|
155
|
+
for suffix, sims in (("float", sf), ("quant", sq)):
|
|
156
|
+
positive = sims[rows, gold]
|
|
157
|
+
result[f"rank_{suffix}"][start:stop] = (sims > positive[:, None]).sum(axis=1)
|
|
158
|
+
# Match the historical top-k membership rule, including its tie behavior.
|
|
159
|
+
topk = np.argpartition(-sims, kth=min(k, sims.shape[1] - 1), axis=1)[:, :k]
|
|
160
|
+
result[f"hit_{suffix}"][start:stop] = (topk == gold[:, None]).any(axis=1)
|
|
161
|
+
negative = sims.copy()
|
|
162
|
+
negative[rows, gold] = -np.inf
|
|
163
|
+
result[f"margin_{suffix}"][start:stop] = positive - negative.max(axis=1)
|
|
164
|
+
lf, lq = sf / 0.07, sq / 0.07
|
|
165
|
+
lf -= lf.max(axis=1, keepdims=True)
|
|
166
|
+
lq -= lq.max(axis=1, keepdims=True)
|
|
167
|
+
logpf = lf[rows, gold] - np.log(np.exp(lf).sum(axis=1))
|
|
168
|
+
logpq = lq[rows, gold] - np.log(np.exp(lq).sum(axis=1))
|
|
169
|
+
result["online_diff"][start:stop] = logpf - logpq
|
|
170
|
+
result["focal_weight"][start:stop] = (1.0 - np.exp(logpq)) ** 2.0
|
|
171
|
+
result["rank_drop"] = result["rank_quant"] - result["rank_float"]
|
|
172
|
+
result["recall_drop"] = result["hit_float"] * (1.0 - result["hit_quant"])
|
|
173
|
+
return result
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def correlation_summary(values: np.ndarray, target: np.ndarray, min_samples: int = 10) -> dict:
|
|
177
|
+
"""Spearman over finite pairs, with explicit undefined-correlation states."""
|
|
178
|
+
values, target = np.asarray(values), np.asarray(target)
|
|
179
|
+
valid = np.isfinite(values) & np.isfinite(target)
|
|
180
|
+
x, y = values[valid], target[valid]
|
|
181
|
+
result = {"n_valid": int(valid.sum()), "spearman_rho": None, "p_value": None}
|
|
182
|
+
if len(x) < min_samples:
|
|
183
|
+
result["status"] = "insufficient_samples"
|
|
184
|
+
elif np.std(y) < 1e-8:
|
|
185
|
+
result["status"] = "constant_rank_drop"
|
|
186
|
+
elif np.ptp(x) == 0:
|
|
187
|
+
result["status"] = "constant_predictor"
|
|
188
|
+
else:
|
|
189
|
+
rho, p = spearmanr(x, y)
|
|
190
|
+
if np.isfinite(rho) and np.isfinite(p):
|
|
191
|
+
result.update(spearman_rho=float(rho), p_value=float(p), status="ok")
|
|
192
|
+
else:
|
|
193
|
+
result["status"] = "undefined"
|
|
194
|
+
finite_values = values[np.isfinite(values)]
|
|
195
|
+
result["mean"] = float(finite_values.mean()) if len(finite_values) else None
|
|
196
|
+
result["std"] = float(finite_values.std()) if len(finite_values) else None
|
|
197
|
+
return result
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def stratify(values: np.ndarray, samples: dict[str, np.ndarray]) -> dict:
|
|
201
|
+
"""Value-based thirds; ties need not produce equally sized groups."""
|
|
202
|
+
valid = np.isfinite(values) & np.isfinite(samples["rank_drop"]) & np.isfinite(samples["recall_drop"])
|
|
203
|
+
if not valid.any():
|
|
204
|
+
return {"thresholds": None, "n_valid": 0, "groups": {}}
|
|
205
|
+
lower, upper = np.quantile(values[valid], [1 / 3, 2 / 3])
|
|
206
|
+
groups = {}
|
|
207
|
+
for name, condition in (
|
|
208
|
+
("easy", values <= lower),
|
|
209
|
+
("medium", (values > lower) & (values <= upper)),
|
|
210
|
+
("hard", values > upper),
|
|
211
|
+
):
|
|
212
|
+
mask = valid & condition
|
|
213
|
+
count = int(mask.sum())
|
|
214
|
+
groups[name] = {
|
|
215
|
+
"n": count,
|
|
216
|
+
"recall_drop_rate": float(samples["recall_drop"][mask].mean()) if count else None,
|
|
217
|
+
"mean_rank_drop": float(samples["rank_drop"][mask].mean()) if count else None,
|
|
218
|
+
"recall_float": float(samples["hit_float"][mask].mean()) if count else None,
|
|
219
|
+
"recall_quant": float(samples["hit_quant"][mask].mean()) if count else None,
|
|
220
|
+
}
|
|
221
|
+
return {"thresholds": [float(lower), float(upper)], "n_valid": int(valid.sum()), "groups": groups}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def analyze_setting(
|
|
225
|
+
data: EmbeddingData, dim: int, bits: int, *, k: int = 10,
|
|
226
|
+
symmetric: bool = False, block_size: int = 512,
|
|
227
|
+
) -> tuple[dict, dict[str, np.ndarray]]:
|
|
228
|
+
"""Measure one explicit dimension/bit cell, aligned to the query order."""
|
|
229
|
+
if isinstance(dim, bool) or not isinstance(dim, (int, np.integer)) or not 1 <= dim <= data.query_embeddings.shape[1]:
|
|
230
|
+
raise ValueError("dim must be an integer within the embedding dimension")
|
|
231
|
+
if not isinstance(k, int) or isinstance(k, bool) or k < 1:
|
|
232
|
+
raise ValueError("k must be a positive integer")
|
|
233
|
+
if not isinstance(block_size, int) or block_size < 1:
|
|
234
|
+
raise ValueError("block_size must be a positive integer")
|
|
235
|
+
q, c = data.query_embeddings[:, :dim], data.candidate_embeddings[:, :dim]
|
|
236
|
+
if np.any(np.linalg.norm(q, axis=1) == 0) or np.any(np.linalg.norm(c, axis=1) == 0):
|
|
237
|
+
raise ValueError(f"A prefix embedding has zero norm at dim={dim}")
|
|
238
|
+
if symmetric and (len(q) != len(c) or len(np.unique(data.correct_indices)) != len(c)):
|
|
239
|
+
raise ValueError("Symmetric IQD requires a bijective one-to-one query/candidate pairing")
|
|
240
|
+
qf, cf = l2_normalize(q), l2_normalize(c)
|
|
241
|
+
qraw, craw = uniform_quantize(q, bits), uniform_quantize(c, bits)
|
|
242
|
+
qq, cq = l2_normalize(qraw), l2_normalize(craw)
|
|
243
|
+
samples = _directional_metrics(qf, cf, qq, cq, data.correct_indices, k, block_size)
|
|
244
|
+
if symmetric:
|
|
245
|
+
inverse = np.empty(len(c), dtype=np.int64)
|
|
246
|
+
inverse[data.correct_indices] = np.arange(len(q))
|
|
247
|
+
reverse = _directional_metrics(cf, qf, cq, qq, inverse, k, block_size)
|
|
248
|
+
for name in samples:
|
|
249
|
+
samples[name] = (samples[name] + reverse[name][data.correct_indices]) / 2.0
|
|
250
|
+
density, lid = _candidate_geometry(c, k, block_size)
|
|
251
|
+
samples["quant_error"] = np.linalg.norm(qf - qraw, axis=1)
|
|
252
|
+
samples["density"] = density[data.correct_indices]
|
|
253
|
+
samples["lid"] = lid[data.correct_indices]
|
|
254
|
+
samples["iqd_combined"] = samples["quant_error"] * samples["density"]
|
|
255
|
+
samples["margin_erosion"] = samples["margin_float"] - samples["margin_quant"]
|
|
256
|
+
samples["inv_margin_float"] = 1.0 / np.clip(samples["margin_float"], 1e-6, None)
|
|
257
|
+
measures = {name: correlation_summary(samples[name], samples["rank_drop"]) for name in PREDICTORS}
|
|
258
|
+
valid_rhos = {name: entry["spearman_rho"] for name, entry in measures.items() if entry["spearman_rho"] is not None}
|
|
259
|
+
best = max(valid_rhos, key=lambda name: abs(valid_rhos[name])) if valid_rhos else None
|
|
260
|
+
summary = {
|
|
261
|
+
"dim": int(dim), "bits": int(bits), "n_queries": len(q), "n_candidates": len(c),
|
|
262
|
+
"k": k, "effective_k": min(k, len(c)), "symmetric": symmetric,
|
|
263
|
+
"density_k": min(k, len(c) - 1), "lid_k": min(20, len(c) - 1),
|
|
264
|
+
"mean_rank_drop": float(samples["rank_drop"].mean()),
|
|
265
|
+
"recall_drop_rate": float(samples["recall_drop"].mean()),
|
|
266
|
+
"measures": measures, "best_predictor": best,
|
|
267
|
+
"best_abs_rho": abs(valid_rhos[best]) if best is not None else None,
|
|
268
|
+
"stratified": {name: stratify(samples[name], samples) for name in STRATIFIERS},
|
|
269
|
+
}
|
|
270
|
+
samples["correct_indices"] = data.correct_indices.copy()
|
|
271
|
+
if data.query_ids is not None:
|
|
272
|
+
samples["query_ids"] = data.query_ids.copy()
|
|
273
|
+
if data.candidate_ids is not None:
|
|
274
|
+
samples["candidate_ids"] = data.candidate_ids.copy()
|
|
275
|
+
return summary, samples
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _grid(values: Iterable[int], name: str, upper: int) -> list[int]:
|
|
279
|
+
result = list(values)
|
|
280
|
+
if not result or any(isinstance(v, bool) or not isinstance(v, (int, np.integer)) or not 1 <= v <= upper for v in result):
|
|
281
|
+
raise ValueError(f"{name} must be a non-empty list of integers in [1, {upper}]")
|
|
282
|
+
if len(result) != len(set(result)):
|
|
283
|
+
raise ValueError(f"{name} must not contain duplicates")
|
|
284
|
+
return [int(v) for v in result]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def analyze_sweep(
|
|
288
|
+
data: EmbeddingData, dims: Iterable[int], bits: Iterable[int], *,
|
|
289
|
+
k: int = 10, symmetric: bool = False, block_size: int = 512,
|
|
290
|
+
) -> tuple[dict, dict[str, dict[str, np.ndarray]]]:
|
|
291
|
+
"""Run only the requested cells; native dimension is never appended."""
|
|
292
|
+
dims = _grid(dims, "dims", data.query_embeddings.shape[1])
|
|
293
|
+
bits = _grid(bits, "bits", 16)
|
|
294
|
+
cells, per_sample = [], {}
|
|
295
|
+
for dim in dims:
|
|
296
|
+
for bit in bits:
|
|
297
|
+
cell, samples = analyze_setting(data, dim, bit, k=k, symmetric=symmetric, block_size=block_size)
|
|
298
|
+
key = f"d{dim}_b{bit}"
|
|
299
|
+
cell["samples_file"] = f"samples_{key}.npz"
|
|
300
|
+
cells.append(cell)
|
|
301
|
+
per_sample[key] = samples
|
|
302
|
+
summary = {
|
|
303
|
+
"schema_version": 1, "quantization": QUANTIZATION.copy(),
|
|
304
|
+
"ground_truth": "explicit single-positive correct_indices",
|
|
305
|
+
"rank_definition": "zero-based count of candidate scores strictly greater than the gold score",
|
|
306
|
+
"recall_definition": "float top-k hit lost after quantization, not signed recall difference",
|
|
307
|
+
"topk_ties": "numpy.argpartition membership; candidate order matters at tied boundary",
|
|
308
|
+
"correlation_min_samples": 10, "contrastive_temperature": 0.07, "focal_gamma": 2.0,
|
|
309
|
+
"numeric_dtype": "float32", "dims": dims, "bits": bits,
|
|
310
|
+
"k": k, "symmetric": symmetric, "n_queries": len(data.query_embeddings),
|
|
311
|
+
"n_candidates": len(data.candidate_embeddings), "native_dimension": data.query_embeddings.shape[1],
|
|
312
|
+
"settings_tested": len(cells), "per_setting": cells,
|
|
313
|
+
}
|
|
314
|
+
return summary, per_sample
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Optional plots of the measured IQD correlations, without model dependencies."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import matplotlib
|
|
6
|
+
|
|
7
|
+
matplotlib.use("Agg")
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from .core import PREDICTORS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def plot_correlations(summary: dict, path: str | Path) -> None:
|
|
15
|
+
dims, bits = summary["dims"], summary["bits"]
|
|
16
|
+
cells = {(cell["dim"], cell["bits"]): cell for cell in summary["per_setting"]}
|
|
17
|
+
figure, axes = plt.subplots(3, 3, figsize=(13, 10), constrained_layout=True)
|
|
18
|
+
cmap = plt.get_cmap("RdBu_r").copy()
|
|
19
|
+
cmap.set_bad("0.88")
|
|
20
|
+
for name, ax in zip(PREDICTORS, axes.flat):
|
|
21
|
+
values = np.full((len(dims), len(bits)), np.nan)
|
|
22
|
+
for i, dim in enumerate(dims):
|
|
23
|
+
for j, bit in enumerate(bits):
|
|
24
|
+
rho = cells[(dim, bit)]["measures"][name]["spearman_rho"]
|
|
25
|
+
if rho is not None:
|
|
26
|
+
values[i, j] = rho
|
|
27
|
+
shown = ax.imshow(np.ma.masked_invalid(values), cmap=cmap, vmin=-1, vmax=1, aspect="auto")
|
|
28
|
+
ax.set_title(name)
|
|
29
|
+
ax.set_xticks(range(len(bits)), bits)
|
|
30
|
+
ax.set_yticks(range(len(dims)), dims)
|
|
31
|
+
ax.set_xlabel("Quantization precision (bits / dimension)")
|
|
32
|
+
ax.set_ylabel("Embedding dimensions")
|
|
33
|
+
for i, j in np.argwhere(np.isfinite(values)):
|
|
34
|
+
rho = values[i, j]
|
|
35
|
+
ax.text(j, i, f"{rho:+.2f}", ha="center", va="center", fontsize=9,
|
|
36
|
+
color="white" if abs(rho) > 0.65 else "black")
|
|
37
|
+
figure.colorbar(shown, ax=axes.ravel().tolist(), shrink=0.7, label="Spearman ρ with rank degradation")
|
|
38
|
+
dataset = summary.get("manifest", {}).get("dataset", "explicit-GT embedding pool")
|
|
39
|
+
figure.suptitle(f"IQD predictor correlations · {dataset}\n"
|
|
40
|
+
f"{summary['n_queries']} queries · fixed symmetric grid · gray = undefined correlation")
|
|
41
|
+
figure.savefig(path, dpi=160)
|
|
42
|
+
plt.close(figure)
|
iqd2rad/data/__init__.py
ADDED
iqd2rad/data/cli.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Prepare local annotation files; validate splits; sample local video frames."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .frames import extract_frames
|
|
8
|
+
from .manifests import check_disjoint, load_ids, load_jsonl, validate_retrieval
|
|
9
|
+
from .prepare import DATASETS, prepare_dataset
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv=None):
|
|
13
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
14
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
15
|
+
prepare = commands.add_parser("prepare", help="Convert local annotations to portable manifests")
|
|
16
|
+
prepare.add_argument("--config", type=Path, help="JSON preparation config; CLI flags override its values")
|
|
17
|
+
prepare.add_argument("--dataset", choices=DATASETS)
|
|
18
|
+
prepare.add_argument("--annotations")
|
|
19
|
+
prepare.add_argument("--raw-root")
|
|
20
|
+
prepare.add_argument("--output-dir")
|
|
21
|
+
prepare.add_argument("--split")
|
|
22
|
+
prepare.add_argument("--annotation-format", choices=["auto", "native", "mmeb", "anymodal-flickr30k", "coco-captions"])
|
|
23
|
+
prepare.add_argument("--mode", choices=["train", "retrieval"])
|
|
24
|
+
prepare.add_argument("--caption-mode", choices=["auto", "all", "first", "paragraph"])
|
|
25
|
+
prepare.add_argument("--query-instruction", help="Explicit retrieval instruction for native annotations")
|
|
26
|
+
for flag in ("split-ids", "exclude-ids", "query-ids", "candidate-ids", "media-map", "frames-subdir"):
|
|
27
|
+
prepare.add_argument(f"--{flag}")
|
|
28
|
+
prepare.add_argument("--num-frames", type=int)
|
|
29
|
+
prepare.add_argument("--expected-queries", type=int)
|
|
30
|
+
prepare.add_argument("--expected-candidates", type=int)
|
|
31
|
+
prepare.add_argument("--include-restval", action=argparse.BooleanOptionalAction, default=None)
|
|
32
|
+
splits = commands.add_parser("check-splits", help="Check media-ID disjointness")
|
|
33
|
+
splits.add_argument("--split", action="append", required=True, metavar="NAME=IDS_PATH")
|
|
34
|
+
frames = commands.add_parser("extract-frames", help="Sample a locally acquired video with ffmpeg")
|
|
35
|
+
frames.add_argument("--video", required=True)
|
|
36
|
+
frames.add_argument("--output-dir", required=True)
|
|
37
|
+
frames.add_argument("--num-frames", type=int, default=64)
|
|
38
|
+
validate = commands.add_parser("validate", help="Validate prepared retrieval manifests and local media")
|
|
39
|
+
validate.add_argument("--queries", required=True)
|
|
40
|
+
validate.add_argument("--candidates", required=True)
|
|
41
|
+
validate.add_argument("--raw-root", required=True)
|
|
42
|
+
args = parser.parse_args(argv)
|
|
43
|
+
if args.command == "prepare":
|
|
44
|
+
options = json.loads(args.config.read_text()) if args.config else {}
|
|
45
|
+
if not isinstance(options, dict):
|
|
46
|
+
parser.error("Preparation config must be a JSON object")
|
|
47
|
+
options.update({key: value for key, value in vars(args).items()
|
|
48
|
+
if key not in {"command", "config"} and value is not None})
|
|
49
|
+
missing = [key for key in ("dataset", "annotations", "raw_root", "output_dir") if not options.get(key)]
|
|
50
|
+
if missing:
|
|
51
|
+
parser.error(f"Missing preparation options: {', '.join(missing)}")
|
|
52
|
+
result = prepare_dataset(**options)
|
|
53
|
+
elif args.command == "check-splits":
|
|
54
|
+
named = {}
|
|
55
|
+
for definition in args.split:
|
|
56
|
+
if "=" not in definition:
|
|
57
|
+
parser.error("--split must have the form NAME=IDS_PATH")
|
|
58
|
+
name, path = definition.split("=", 1)
|
|
59
|
+
if not name or name in named:
|
|
60
|
+
parser.error("Split names must be nonempty and unique")
|
|
61
|
+
named[name] = load_ids(path)
|
|
62
|
+
result = check_disjoint(named)
|
|
63
|
+
elif args.command == "extract-frames":
|
|
64
|
+
paths = extract_frames(args.video, args.output_dir, args.num_frames)
|
|
65
|
+
result = {"frames": len(paths), "output_dir": args.output_dir}
|
|
66
|
+
else:
|
|
67
|
+
queries, candidates = load_jsonl(args.queries), load_jsonl(args.candidates)
|
|
68
|
+
validate_retrieval(queries, candidates, args.raw_root)
|
|
69
|
+
result = {"queries": len(queries), "candidates": len(candidates), "valid": True}
|
|
70
|
+
print(json.dumps(result, indent=2))
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
raise SystemExit(main())
|
iqd2rad/data/frames.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Deterministic frame sampling from locally acquired videos."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def extract_frames(video, output_dir, num_frames=64):
|
|
12
|
+
"""Sample uniformly spaced decoded frame indices, including both endpoints.
|
|
13
|
+
|
|
14
|
+
Extraction uses a temporary sibling directory; a partial failure cannot leave
|
|
15
|
+
a directory that looks complete. Existing output directories are rejected.
|
|
16
|
+
"""
|
|
17
|
+
import tempfile
|
|
18
|
+
|
|
19
|
+
video, output = Path(video), Path(output_dir)
|
|
20
|
+
if not video.is_file():
|
|
21
|
+
raise FileNotFoundError(video)
|
|
22
|
+
if num_frames < 1:
|
|
23
|
+
raise ValueError("num_frames must be positive")
|
|
24
|
+
if output.exists():
|
|
25
|
+
raise FileExistsError(f"Frame directory already exists: {output}")
|
|
26
|
+
if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:
|
|
27
|
+
raise RuntimeError("Install ffmpeg and ffprobe to extract frames; pre-extracted frames also work")
|
|
28
|
+
info = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames",
|
|
29
|
+
"-show_entries", "stream=nb_read_frames", "-of", "json", str(video)],
|
|
30
|
+
capture_output=True, text=True, check=True)
|
|
31
|
+
streams = json.loads(info.stdout).get("streams", [])
|
|
32
|
+
if not streams:
|
|
33
|
+
raise ValueError("Video has no decodable video stream")
|
|
34
|
+
count = int(streams[0]["nb_read_frames"])
|
|
35
|
+
if count < 1:
|
|
36
|
+
raise ValueError("Video has no decodable frames")
|
|
37
|
+
take = min(num_frames, count)
|
|
38
|
+
indices = np.linspace(0, count - 1, take, dtype=int)
|
|
39
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
with tempfile.TemporaryDirectory(prefix=".frames-", dir=output.parent) as temporary:
|
|
41
|
+
staging = Path(temporary)
|
|
42
|
+
selection = "+".join(f"eq(n\\,{index})" for index in indices)
|
|
43
|
+
subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", str(video),
|
|
44
|
+
"-map", "0:v:0", "-vf", f"select={selection}", "-vsync", "0",
|
|
45
|
+
"-q:v", "2", "-start_number", "0", str(staging / "frame_%06d.jpg")],
|
|
46
|
+
check=True, capture_output=True)
|
|
47
|
+
decoded = sorted(staging.glob("frame_*.jpg"))
|
|
48
|
+
if len(decoded) != take or any(path.stat().st_size == 0 for path in decoded):
|
|
49
|
+
raise RuntimeError("ffmpeg did not return the requested decoded frame sample")
|
|
50
|
+
staging.rename(output)
|
|
51
|
+
return sorted(output.glob("frame_*.jpg"))
|