Complete standalone final deliverable and unaligned Q2 results
This commit is contained in:
1 parent
c6b018e5d0
commit
adc9c2064b
267 files changed
+15479
-7976
No files matched your search
@@ -0,0 +1,151 @@
|
||||
"""Full Q1 physical and official unaligned split audit; no model training."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
|
||||
from ..adapter import Q1AlignmentAdapter
|
||||
from ..q2.math.data import restricted_load
|
||||
|
||||
MODALITIES = ("text", "audio", "vision")
|
||||
RESULTS = ROOT / "output" / "q1" / "unified_adapter"
|
||||
from ..data_paths import ATTACHMENT2
|
||||
|
||||
OFFICIAL = ATTACHMENT2 / "unaligned_50.pkl"
|
||||
|
||||
|
||||
def _distribution(values: list[float]) -> dict[str, float | int]:
|
||||
arr = np.asarray(values, np.float64)
|
||||
return {"count": int(len(arr)), "min": float(arr.min()) if len(arr) else 0.0,
|
||||
"p25": float(np.percentile(arr, 25)) if len(arr) else 0.0,
|
||||
"median": float(np.median(arr)) if len(arr) else 0.0,
|
||||
"p75": float(np.percentile(arr, 75)) if len(arr) else 0.0,
|
||||
"max": float(arr.max()) if len(arr) else 0.0,
|
||||
"mean": float(arr.mean()) if len(arr) else 0.0}
|
||||
|
||||
|
||||
def _audit_split(name: str, split: dict, baseline: dict) -> dict:
|
||||
adapter = Q1AlignmentAdapter()
|
||||
n = len(split["id"])
|
||||
hashes = {m: hashlib.sha256() for m in MODALITIES}
|
||||
mask_hash = hashlib.sha256()
|
||||
lengths = {m: [] for m in MODALITIES}
|
||||
observed_bins = {m: [] for m in MODALITIES}
|
||||
all_missing_bins = Counter()
|
||||
coverages = {m: [] for m in MODALITIES}
|
||||
relations = {m: Counter() for m in MODALITIES}
|
||||
all_missing = Counter()
|
||||
conflicts = Counter()
|
||||
text_padding_nonzero = 0
|
||||
max_provenance_error = 0.0
|
||||
max_nonfinite = 0
|
||||
modes = Counter()
|
||||
shapes = {m: Counter() for m in MODALITIES}
|
||||
for i in range(n):
|
||||
sample = adapter.from_unaligned_record(split, i)
|
||||
modes[sample.metadata["coordinate_mode"]] += 1
|
||||
stacked_mask = np.stack([sample.observed[m] for m in MODALITIES], axis=-1)
|
||||
mask_hash.update(stacked_mask.tobytes(order="C"))
|
||||
attention = np.asarray(split["text_bert"][i, 1], bool)
|
||||
text_padding_nonzero += int(np.count_nonzero(np.any(split["text"][i] != 0, axis=1) & ~attention))
|
||||
for m in MODALITIES:
|
||||
x = sample.features[m]
|
||||
p = sample.provenance[m]
|
||||
hashes[m].update(x.tobytes(order="C"))
|
||||
shapes[m][str(list(x.shape))] += 1
|
||||
lengths[m].append(p.source_span)
|
||||
observed_bins[m].append(int(sample.observed[m].sum()))
|
||||
all_missing_bins[m] += int((~sample.observed[m]).sum())
|
||||
coverages[m].extend(sample.coverage[m].tolist())
|
||||
relations[m]["L<K" if p.source_span < 50 else "L=K" if p.source_span == 50 else "L>K"] += 1
|
||||
all_missing[m] += int(not sample.observed[m].any())
|
||||
conflicts[m] += int(p.length_conflict)
|
||||
if m == "vision":
|
||||
all_missing["vision_tail_ambiguous"] += int(p.tail_ambiguous)
|
||||
row_sums = np.asarray(p.source_weights.sum(axis=1)).reshape(-1)
|
||||
if sample.observed[m].any():
|
||||
max_provenance_error = max(max_provenance_error,
|
||||
float(np.max(np.abs(row_sums[sample.observed[m]] - 1.0))))
|
||||
max_provenance_error = max(max_provenance_error,
|
||||
float(np.max(np.abs(row_sums[~sample.observed[m]]))) if (~sample.observed[m]).any() else 0.0)
|
||||
max_nonfinite += int(np.count_nonzero(~np.isfinite(x)))
|
||||
actual = {m: h.hexdigest() for m, h in hashes.items()}
|
||||
expected = baseline[name]["sha256"]
|
||||
return {"samples": n, "coordinate_modes": dict(modes), "feature_shapes": {m: dict(v) for m, v in shapes.items()},
|
||||
"source_length": {m: _distribution(v) for m, v in lengths.items()},
|
||||
"source_length_vs_K": {m: dict(v) for m, v in relations.items()},
|
||||
"observed_target_bins_per_sample": {m: _distribution(v) for m, v in observed_bins.items()},
|
||||
"coverage_per_target_bin": {m: _distribution(v) for m, v in coverages.items()},
|
||||
"text_nonzero_rows_outside_attention": text_padding_nonzero,
|
||||
"length_conflict_samples": dict(conflicts),
|
||||
"tail_ambiguous_samples": all_missing["vision_tail_ambiguous"],
|
||||
"all_missing_target_bins": dict(all_missing_bins),
|
||||
"all_missing_modality_samples": {m: all_missing[m] for m in MODALITIES},
|
||||
"nonfinite_output_values": max_nonfinite,
|
||||
"max_provenance_row_sum_error": max_provenance_error,
|
||||
"sha256": actual, "legacy_sha256": expected,
|
||||
"exact_feature_equivalence": {m: actual[m] == expected[m] for m in MODALITIES},
|
||||
"mask_sha256": mask_hash.hexdigest(),
|
||||
"exact_mask_equivalence": mask_hash.hexdigest() == baseline[name]["mask_sha256"]}
|
||||
|
||||
|
||||
def _audit_physical() -> dict:
|
||||
manifest = HERE / "features_v2" / "manifest_q1.jsonl"
|
||||
ids = [json.loads(line)["sample_id"] for line in manifest.read_text(encoding="utf-8").splitlines()]
|
||||
adapter = Q1AlignmentAdapter()
|
||||
modes = Counter()
|
||||
nonfinite = 0
|
||||
provenance_error = 0.0
|
||||
shapes = {m: Counter() for m in MODALITIES}
|
||||
duration = []
|
||||
for sample_id in ids:
|
||||
sample = adapter.from_q1_sample(sample_id)
|
||||
modes[sample.metadata["coordinate_mode"]] += 1
|
||||
duration.append(sample.metadata["duration_s"])
|
||||
for m in MODALITIES:
|
||||
x = sample.features[m]
|
||||
shapes[m][str(list(x.shape))] += 1
|
||||
nonfinite += int(np.count_nonzero(~np.isfinite(x)))
|
||||
sums = np.asarray(sample.provenance[m].source_weights.sum(axis=1)).ravel()
|
||||
observed = sample.observed[m]
|
||||
if observed.any():
|
||||
provenance_error = max(provenance_error, float(np.max(np.abs(sums[observed] - 1))))
|
||||
return {"samples": len(ids), "coordinate_modes": dict(modes), "feature_shapes": {m: dict(v) for m, v in shapes.items()},
|
||||
"duration_s": _distribution(duration), "nonfinite_output_values": nonfinite,
|
||||
"max_provenance_row_sum_error": provenance_error,
|
||||
"stored_dense_0_1_s_views_untouched": True}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
RESULTS.mkdir(parents=True, exist_ok=True)
|
||||
baseline = json.loads((RESULTS / "legacy_relative_baseline.json").read_text(encoding="utf-8"))
|
||||
obj = restricted_load(OFFICIAL)
|
||||
report = {"adapter": "q1-unified-1", "official_input": str(OFFICIAL.relative_to(ROOT)),
|
||||
"relative": {name: _audit_split(name, obj[name], baseline) for name in ("train", "valid", "test")}}
|
||||
del obj
|
||||
report["physical"] = _audit_physical()
|
||||
(RESULTS / "full_audit.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
equivalence = {"comparison": "SHA-256 of full float32 feature arrays and boolean masks against frozen old adapter output",
|
||||
"splits": {name: {"samples": v["samples"], "exact_feature_equivalence": v["exact_feature_equivalence"],
|
||||
"exact_mask_equivalence": v["exact_mask_equivalence"],
|
||||
"old_feature_sha256": v["legacy_sha256"], "new_feature_sha256": v["sha256"],
|
||||
"old_mask_sha256": baseline[name]["mask_sha256"],
|
||||
"new_mask_sha256": v["mask_sha256"]}
|
||||
for name, v in report["relative"].items()}}
|
||||
(RESULTS / "equivalence_report.json").write_text(json.dumps(equivalence, indent=2), encoding="utf-8")
|
||||
print(json.dumps({"relative": {name: {"samples": v["samples"],
|
||||
"exact_feature_equivalence": v["exact_feature_equivalence"],
|
||||
"exact_mask_equivalence": v["exact_mask_equivalence"]} for name, v in report["relative"].items()},
|
||||
"physical_samples": report["physical"]["samples"]}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,417 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from scipy import sparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
Q1 = Path(__file__).resolve().parent
|
||||
from . import compare_models as cm
|
||||
|
||||
CACHE = Q1 / "cache" / "native"
|
||||
RUN = ROOT / "output" / "q1" / "model_comparison" / "run_manifest.json"
|
||||
LABELS = cm.LABEL_FILE
|
||||
OUT = ROOT / "output" / "q1" / "features_v2"
|
||||
MODALITIES = ("text", "audio", "vision")
|
||||
CONFIG = {
|
||||
"schema": "q1-v2-source-first-2026-09",
|
||||
"source_cache_schema": "q1-b0b4-v4-openface",
|
||||
"common_step_s": 0.1,
|
||||
"multi_context_windows_s": [0.1, 0.3, 0.7],
|
||||
"relative_progress_bins": 50,
|
||||
"text_encoder": "google-bert/bert-base-uncased; frozen last-four-layer mean per whitespace word; window=510, stride=384",
|
||||
"alignment": "fixed-transcript CTC monotone state graph; hard Viterbi path plus stored forward-backward occupancy; scores uncalibrated",
|
||||
"audio": "74-D: 40 log-Mel + 13 MFCC + 13 two-sided local-linear delta MFCC + [log-energy, log-F0, librosa.pyin voiced probability, spectral centroid, bandwidth, flux, zero-crossing rate, HNR dB]; 16 kHz, 400-sample window, 160-sample hop, FFT 512; HNR autocorrelation uses n=1024 at detected F0; preserve per-field validity; librosa.pyin warns cycle support is short at fmin=80 Hz for a 25 ms frame",
|
||||
"vision": "OpenFace 2.2.0 native-frame output: 17 AU intensities, Pose6, Gaze6, Geometry6; confidence threshold 0.8; actual frame PTS and indices retained",
|
||||
"quality": "B0 uses raw CTC word-path score in [0,1]; unavailable quality falls back to q*=1 and is flagged; audio/vision retain explicit unknown or detector-confidence states",
|
||||
"content_probe": "disabled; physical time/query maps remain separate from content similarity",
|
||||
"time": "left-closed/right-open seconds relative to video stream origin; source indices retained",
|
||||
"branch_states": {"sec": "primary B0 view and materialized", "B1_vision_geometry": "geometry-aware 0.1 s view materialized", "word": "materialized", "phase50": "materialized", "multi": "derived from native rows on demand by q1_io", "posterior": "native CTC posterior stored; sec projection available through q1_io", "dynamics": "materialized if continuous support is sufficient", "b4_speech": "source-cache-backed on demand through q1_io to stay within the 50 MiB feature-package cap", "query_word": "physical H_time matrices materialized", "content_probe": "disabled"},
|
||||
}
|
||||
|
||||
|
||||
def digest(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for block in iter(lambda: f.read(1024 * 1024), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def finite_boundary_summary(rows: list[dict[str, float]], offset: float, end_s: float) -> tuple[np.ndarray, str]:
|
||||
values=[]
|
||||
json_rows=[]
|
||||
for row in rows:
|
||||
vals=[row.get("start_p05_s",np.nan)+offset,row.get("start_p95_s",np.nan)+offset,row.get("end_p05_s",np.nan)+offset,row.get("end_p95_s",np.nan)+offset]
|
||||
vals=[float(np.clip(v,0.0,end_s)) if np.isfinite(v) else np.nan for v in vals]
|
||||
values.append([v if np.isfinite(v) else -1.0 for v in vals])
|
||||
absolute_fields={"start_mean_s","end_mean_s","start_p05_s","start_p95_s","end_p05_s","end_p95_s"}
|
||||
json_rows.append({k:(float(np.clip(v+offset,0.0,end_s)) if np.isfinite(v) and k in absolute_fields else (float(v) if np.isfinite(v) else None)) for k,v in row.items()})
|
||||
return np.asarray(values,np.float32),json.dumps(json_rows,ensure_ascii=False)
|
||||
|
||||
|
||||
def audio_sample_count_from_quality(sample: cm.Sample) -> int:
|
||||
"""The final partial 25 ms frame records its exact decoded sample fraction."""
|
||||
valid=np.flatnonzero(np.asarray(sample.audio_quality)>0)
|
||||
if not len(valid):
|
||||
return 0
|
||||
index=int(valid[-1])
|
||||
fraction=float(np.clip(sample.audio_quality[index],0.0,1.0))
|
||||
return index*cm.FRAME_STEP+int(round(fraction*cm.FRAME_LENGTH))
|
||||
|
||||
|
||||
def effective_text_quality(raw: np.ndarray, valid: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Use bounded raw CTC scores; q*=1 means no extra discount when unavailable."""
|
||||
raw = np.asarray(raw, np.float32)
|
||||
available = np.asarray(valid, bool) & (raw > 0) & np.isfinite(raw)
|
||||
effective = np.ones(len(raw), np.float32)
|
||||
effective[available] = np.clip(raw[available], 0.0, 1.0)
|
||||
return effective, available
|
||||
|
||||
|
||||
def intervals_from_times(times: np.ndarray, duration: float, step: float, gap_factor: float = 1.5) -> np.ndarray:
|
||||
times = np.asarray(times, dtype=np.float64)
|
||||
if not len(times):
|
||||
return np.empty((0, 2), np.float32)
|
||||
starts = np.empty(len(times), dtype=np.float64)
|
||||
ends = np.empty(len(times), dtype=np.float64)
|
||||
breaks = np.diff(times) > gap_factor * step
|
||||
for i, t in enumerate(times):
|
||||
starts[i] = (times[i - 1] + t) / 2 if i and not breaks[i - 1] else max(0.0, t - step / 2)
|
||||
ends[i] = (t + times[i + 1]) / 2 if i + 1 < len(times) and not breaks[i] else min(duration, t + step / 2)
|
||||
if starts[0] <= step:
|
||||
starts[0] = 0.0
|
||||
if ends[-1] >= duration - step:
|
||||
ends[-1] = duration
|
||||
starts = np.clip(starts, 0.0, duration)
|
||||
ends = np.clip(ends, 0.0, duration)
|
||||
return np.column_stack((starts, np.maximum(starts, ends))).astype(np.float32)
|
||||
|
||||
|
||||
def probe_media(path: Path) -> dict[str, Any]:
|
||||
command = ["ffprobe", "-v", "error", "-show_entries", "format=start_time,duration:stream=codec_type,start_time,time_base,sample_rate,avg_frame_rate", "-of", "json", str(path)]
|
||||
try:
|
||||
obj = json.loads(subprocess.run(command, check=True, capture_output=True, text=True).stdout)
|
||||
streams = obj.get("streams", [])
|
||||
fmt = obj.get("format", {})
|
||||
vs = next((s for s in streams if s.get("codec_type") == "video"), {})
|
||||
aus = next((s for s in streams if s.get("codec_type") == "audio"), {})
|
||||
v0 = float(vs.get("start_time", fmt.get("start_time", 0)) or 0)
|
||||
a0 = float(aus.get("start_time", fmt.get("start_time", 0)) or 0)
|
||||
return {"format_start_s": float(fmt.get("start_time", 0) or 0), "format_duration_s": float(fmt.get("duration", 0) or 0), "video_start_s": v0, "audio_start_s": a0, "audio_offset_from_video_s": a0 - v0, "video_time_base": vs.get("time_base"), "audio_time_base": aus.get("time_base"), "audio_sample_rate": aus.get("sample_rate"), "avg_frame_rate": vs.get("avg_frame_rate"), "status": "ok"}
|
||||
except Exception as exc:
|
||||
return {"format_start_s": 0.0, "format_duration_s": 0.0, "video_start_s": 0.0, "audio_start_s": 0.0, "audio_offset_from_video_s": 0.0, "status": f"ffprobe_error:{type(exc).__name__}"}
|
||||
|
||||
|
||||
def aggregate(values: np.ndarray, observed: np.ndarray, source_intervals: np.ndarray, quality: np.ndarray, edges: np.ndarray, quality_available: np.ndarray | None = None) -> dict[str, np.ndarray]:
|
||||
values = np.asarray(values, np.float64)
|
||||
observed = np.asarray(observed, bool)
|
||||
source_intervals = np.asarray(source_intervals, np.float64)
|
||||
quality = np.maximum(0.0, np.asarray(quality, np.float64))
|
||||
quality_available = np.zeros(len(values), dtype=bool) if quality_available is None else np.asarray(quality_available, dtype=bool)
|
||||
n, d = len(edges) - 1, values.shape[1]
|
||||
mean = np.zeros((n, d), np.float32)
|
||||
var = np.zeros((n, d), np.float32)
|
||||
count = np.zeros((n, d), np.uint8)
|
||||
coverage = np.zeros((n, d), np.float32)
|
||||
qbar = np.ones((n, d), np.float32)
|
||||
qavail = np.zeros((n, d), np.float32)
|
||||
mask = np.zeros((n, d), bool)
|
||||
for i, (left, right) in enumerate(zip(edges[:-1], edges[1:])):
|
||||
if right <= left or not len(source_intervals):
|
||||
continue
|
||||
overlap = np.maximum(0.0, np.minimum(source_intervals[:, 1], right) - np.maximum(source_intervals[:, 0], left))
|
||||
phys = overlap[:, None] * observed
|
||||
w = phys * quality[:, None]
|
||||
wsum = w.sum(axis=0)
|
||||
good = wsum > 0
|
||||
if good.any():
|
||||
sx = (values * w).sum(axis=0)
|
||||
sx2 = (np.square(values) * w).sum(axis=0)
|
||||
mean[i, good] = (sx[good] / wsum[good]).astype(np.float32)
|
||||
var[i, good] = np.maximum(0.0, sx2[good] / wsum[good] - mean[i, good].astype(np.float64) ** 2).astype(np.float32)
|
||||
mask[i, good] = True
|
||||
coverage[i] = np.minimum(1.0, phys.sum(axis=0) / (right - left)).astype(np.float32)
|
||||
count[i] = np.minimum(255, ((overlap[:, None] > 0) & observed).sum(axis=0)).astype(np.uint8)
|
||||
base = phys.sum(axis=0)
|
||||
valid = base > 0
|
||||
qbar[i, valid] = ((phys * quality[:, None]).sum(axis=0)[valid] / base[valid]).astype(np.float32)
|
||||
qavail[i, valid] = ((phys * quality_available[:, None]).sum(axis=0)[valid] / base[valid]).astype(np.float32)
|
||||
# Audio HNR/prosodic rows can have genuinely large within-window variance;
|
||||
# retain variance in float32 rather than silently overflowing float16.
|
||||
return {"x": mean.astype(np.float16), "var": var.astype(np.float32), "count": count, "coverage_u8": np.rint(coverage * 255).astype(np.uint8), "mask": mask, "qbar": qbar.astype(np.float16), "quality_available_fraction": qavail.astype(np.float16)}
|
||||
|
||||
|
||||
def sparse_overlap(source_intervals: np.ndarray, target_intervals: np.ndarray, quality: np.ndarray | None = None) -> sparse.csr_matrix:
|
||||
rows, cols, vals = [], [], []
|
||||
q = np.ones(len(source_intervals), np.float32) if quality is None else np.asarray(quality, np.float32)
|
||||
for i, (left, right) in enumerate(target_intervals):
|
||||
overlap = np.maximum(0.0, np.minimum(source_intervals[:, 1], right) - np.maximum(source_intervals[:, 0], left)) * q
|
||||
js = np.flatnonzero(overlap > 0)
|
||||
rows.extend([i] * len(js)); cols.extend(js.tolist()); vals.extend(overlap[js].tolist())
|
||||
return sparse.csr_matrix((np.asarray(vals, np.float32), (rows, cols)), shape=(len(target_intervals), len(source_intervals)))
|
||||
|
||||
|
||||
def sparse_word_map(word_intervals: np.ndarray, source_intervals: np.ndarray, chi: np.ndarray) -> sparse.csr_matrix:
|
||||
rows, cols, vals = [], [], []
|
||||
for k, (left, right) in enumerate(word_intervals):
|
||||
if right <= left:
|
||||
continue
|
||||
overlap = np.maximum(0.0, np.minimum(source_intervals[:, 1], right) - np.maximum(source_intervals[:, 0], left)) * chi
|
||||
js = np.flatnonzero(overlap > 0)
|
||||
total = float(overlap[js].sum())
|
||||
if total > 0:
|
||||
rows.extend([k] * len(js)); cols.extend(js.tolist()); vals.extend((overlap[js] / total).tolist())
|
||||
return sparse.csr_matrix((np.asarray(vals, np.float32), (rows, cols)), shape=(len(word_intervals), len(source_intervals)))
|
||||
|
||||
|
||||
def pack_csr(arrays: dict[str, Any], prefix: str, matrix: sparse.csr_matrix) -> None:
|
||||
arrays[prefix + "_data"] = matrix.data.astype(np.float16)
|
||||
arrays[prefix + "_indices"] = matrix.indices.astype(np.int32)
|
||||
arrays[prefix + "_indptr"] = matrix.indptr.astype(np.int32)
|
||||
arrays[prefix + "_shape"] = np.asarray(matrix.shape, np.int32)
|
||||
|
||||
|
||||
def text_provenance(record: dict[str, Any], words: list[str], tokenizer: Any) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
text = record["text"]
|
||||
spans = np.full((len(words), 2), -1, np.int32)
|
||||
subword = np.zeros((len(words), 2), np.int32)
|
||||
all_ids: list[int] = []
|
||||
cursor = 0
|
||||
for i, word in enumerate(words):
|
||||
start = text.find(word, cursor)
|
||||
if start >= 0:
|
||||
spans[i] = (start, start + len(word)); cursor = start + len(word)
|
||||
ids = tokenizer(word, add_special_tokens=False)["input_ids"] if tokenizer is not None else []
|
||||
subword[i] = (len(all_ids), len(all_ids) + len(ids))
|
||||
all_ids.extend(int(v) for v in ids)
|
||||
return spans, subword, np.asarray(all_ids, np.int32)
|
||||
|
||||
|
||||
def make_dynamics(sample: cm.Sample, audio_intervals: np.ndarray, vision_intervals: np.ndarray, edges: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
# Time-augmented level-2 log-signature on continuous 0.7 s contexts; this is auxiliary only.
|
||||
names = [("audio", 67, 66), ("vision", 10, 31)]
|
||||
output = np.zeros((len(edges)-1, 2, 6), np.float32)
|
||||
valid = np.zeros((len(edges)-1, 2), bool)
|
||||
bounds = np.zeros((len(edges)-1, 2, 2), np.float32)
|
||||
for t,(l,r) in enumerate(zip(edges[:-1],edges[1:])):
|
||||
center=(l+r)/2
|
||||
a=max(0.0,center-0.35); b=min(sample.duration_s,center+0.35)
|
||||
bounds[t,:,:]=[a,b]
|
||||
for branch,(mod,j,k) in enumerate(names):
|
||||
if mod=="audio":
|
||||
times=sample.audio_times; x=sample.audio_features.astype(np.float32); mask=sample.audio_observed
|
||||
ints=audio_intervals; required=mask[:,[j,k]].all(axis=1)
|
||||
else:
|
||||
times=sample.vision_times; x=sample.vision_features.astype(np.float32); mask=sample.vision_observed
|
||||
ints=vision_intervals; required=mask[:,[j,k]].all(axis=1)
|
||||
ix=np.flatnonzero((ints[:,0]>=a-1e-7)&(ints[:,1]<=b+1e-7)&required)
|
||||
if len(ix)<3: continue
|
||||
# Break the path at missing or unusually long source gaps.
|
||||
expected=0.01 if mod=="audio" else max(float(np.median(np.diff(times))),1e-6)
|
||||
if np.any(np.diff(times[ix])>1.5*expected): continue
|
||||
vals=np.column_stack(((times[ix]-a)/max(b-a,1e-6),x[ix,j],x[ix,k])).astype(np.float64)
|
||||
dz=np.diff(vals,axis=0)
|
||||
first=dz.sum(axis=0)
|
||||
area=np.zeros(3,np.float64); pairs=((0,1),(0,2),(1,2))
|
||||
for p,(u,v) in enumerate(pairs):
|
||||
area[p]=0.5*sum(dz[a0,u]*dz[b0,v]-dz[a0,v]*dz[b0,u] for a0 in range(len(dz)) for b0 in range(a0+1,len(dz)))
|
||||
output[t,branch]=np.concatenate((first,area)).astype(np.float32)
|
||||
valid[t,branch]=True
|
||||
return output.astype(np.float16),valid,bounds
|
||||
|
||||
|
||||
def geometry_aware_vision(sample: cm.Sample, intervals: np.ndarray, bounds: np.ndarray, base: dict[str, np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""B1 SO(3) mean for head pose and unit-vector means for gaze channels."""
|
||||
values = base["x"].astype(np.float32).copy()
|
||||
masks = base["mask"].astype(bool).copy()
|
||||
raw = sample.vision_features.astype(np.float32)
|
||||
observed = sample.vision_observed
|
||||
for target_index, (left, right) in enumerate(bounds):
|
||||
overlap = np.maximum(0.0, np.minimum(intervals[:, 1], right) - np.maximum(intervals[:, 0], left))
|
||||
weighted_overlap=overlap*sample.vision_quality
|
||||
pose_rows = (weighted_overlap > 0) & observed[:, 17:20].all(axis=1)
|
||||
if pose_rows.any():
|
||||
mean_rot = cm._so3_weighted_mean(raw[pose_rows, 17:20], weighted_overlap[pose_rows])
|
||||
if mean_rot is not None:
|
||||
values[target_index, 17:20] = mean_rot
|
||||
masks[target_index, 17:20] = True
|
||||
for start in (23, 26):
|
||||
rows = (weighted_overlap > 0) & observed[:, start:start + 3].all(axis=1)
|
||||
if not rows.any():
|
||||
continue
|
||||
mean = np.average(raw[rows, start:start + 3], axis=0, weights=weighted_overlap[rows])
|
||||
norm = float(np.linalg.norm(mean))
|
||||
if norm > 1e-6:
|
||||
values[target_index, start:start + 3] = mean / norm
|
||||
masks[target_index, start:start + 3] = True
|
||||
else:
|
||||
values[target_index, start:start + 3] = 0.0
|
||||
masks[target_index, start:start + 3] = False
|
||||
return values.astype(np.float16), masks
|
||||
|
||||
|
||||
def main() -> None:
|
||||
global CACHE, RUN, LABELS, OUT
|
||||
parser = argparse.ArgumentParser(description="Build the Q1 physical-time feature package from native caches.")
|
||||
parser.add_argument("--data-dir", type=Path, default=cm.DATA_DIR)
|
||||
parser.add_argument("--cache-dir", type=Path, default=CACHE)
|
||||
parser.add_argument("--run-manifest", type=Path, default=RUN)
|
||||
parser.add_argument("--output-dir", type=Path, default=OUT)
|
||||
args = parser.parse_args()
|
||||
cm.DATA_DIR = args.data_dir.resolve()
|
||||
cm.LABEL_FILE = cm.DATA_DIR / "label-100.xlsx"
|
||||
CACHE = args.cache_dir.resolve()
|
||||
RUN = args.run_manifest.resolve()
|
||||
LABELS = cm.LABEL_FILE
|
||||
OUT = args.output_dir.resolve()
|
||||
if not CACHE.is_dir() or not RUN.is_file():
|
||||
raise FileNotFoundError("Existing Q1 native cache and run manifest are required")
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
run = json.loads(RUN.read_text(encoding="utf-8"))
|
||||
records = cm._read_labels(LABELS)
|
||||
if len(records) != 100:
|
||||
raise ValueError(f"expected 100 attachment-1 rows, got {len(records)}")
|
||||
tokenizer = None
|
||||
try:
|
||||
tokenizer = cm.AutoTokenizer.from_pretrained(cm.TEXT_MODEL_ID, use_fast=True, local_files_only=True)
|
||||
except Exception:
|
||||
pass
|
||||
config_text = json.dumps(CONFIG, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
config_hash = hashlib.sha256(config_text.encode("utf-8")).hexdigest()
|
||||
grid_rows: list[dict[str, Any]] = []
|
||||
sample_rows: list[dict[str, Any]] = []
|
||||
manifest_lines: list[dict[str, Any]] = []
|
||||
for record in records:
|
||||
sid=record["sample_id"]
|
||||
source_hash=run["inputs"]["video_sha256_by_sample"][sid]
|
||||
cache=CACHE/f"{cm._safe_name(record['video_id'])}__{cm._safe_name(record['clip_id'])}.npz"
|
||||
sample=cm._load_cache(cache,record,source_hash,"q1-b0b4-v4-openface")
|
||||
video_path=cm.DATA_DIR/record["video_id"]/f"{record['clip_id']}.mp4"
|
||||
media=probe_media(video_path)
|
||||
audio_offset=float(media.get("audio_offset_from_video_s",0.0))
|
||||
sample_count=audio_sample_count_from_quality(sample)
|
||||
audio_end_s=float(np.clip(audio_offset+sample_count/cm.SAMPLE_RATE,0.0,sample.duration_s))
|
||||
audio_times=sample.audio_times.astype(np.float32)+audio_offset
|
||||
ctc_times=sample.ctc_times.astype(np.float32)+audio_offset
|
||||
hard=sample.hard_intervals.astype(np.float32).copy()+np.float32(audio_offset)
|
||||
hard=np.clip(hard,0.0,audio_end_s)
|
||||
hard_valid=sample.hard_valid & (hard[:,1]>hard[:,0])
|
||||
text_intervals=np.where(hard_valid[:,None],hard,0.0)
|
||||
audio_starts=np.arange(len(audio_times),dtype=np.int64)*cm.FRAME_STEP
|
||||
audio_ranges=np.column_stack((audio_starts,np.minimum(audio_starts+cm.FRAME_LENGTH,sample_count))).astype(np.int32)
|
||||
audio_intervals=intervals_from_times(audio_times,audio_end_s,cm.FRAME_STEP/cm.SAMPLE_RATE)
|
||||
audio_intervals=np.clip(audio_intervals,0.0,sample.duration_s)
|
||||
video_step=float(np.median(np.diff(sample.vision_times))) if len(sample.vision_times)>1 else 1.0/30.0
|
||||
vision_intervals=intervals_from_times(sample.vision_times,sample.duration_s,video_step)
|
||||
frame_indices=sample.vision_frame_indices.astype(np.int32)
|
||||
words=sample.text_words
|
||||
char_spans,subword_spans,subword_ids=text_provenance(record,words,tokenizer)
|
||||
duration=sample.duration_s
|
||||
sec_edges=cm._grid_edges(duration)
|
||||
sec_bounds=np.column_stack((sec_edges[:-1],sec_edges[1:])).astype(np.float32)
|
||||
phase_edges=np.linspace(0.0,duration,51,dtype=np.float64)
|
||||
phase_bounds=np.column_stack((phase_edges[:-1],phase_edges[1:])).astype(np.float32)
|
||||
word_bounds=text_intervals.copy()
|
||||
# Keep the media timestamps in the video-origin timebase for dynamics too.
|
||||
sample.audio_times = audio_times
|
||||
text_quality, text_quality_available = effective_text_quality(sample.hard_quality, hard_valid)
|
||||
source={
|
||||
"text":(sample.text_features.astype(np.float32),np.broadcast_to(sample.text_valid[:,None],sample.text_features.shape).copy(),text_intervals,text_quality,text_quality_available),
|
||||
"audio":(sample.audio_features.astype(np.float32),sample.audio_observed,audio_intervals,sample.audio_quality,sample.audio_quality_available),
|
||||
"vision":(sample.vision_features.astype(np.float32),sample.vision_observed,vision_intervals,sample.vision_quality,sample.vision_quality_available),
|
||||
}
|
||||
sec={name:aggregate(source[name][0],source[name][1],source[name][2],source[name][3],sec_edges,source[name][4]) for name in MODALITIES}
|
||||
phase={name:aggregate(source[name][0],source[name][1],source[name][2],source[name][3],phase_edges,source[name][4]) for name in MODALITIES}
|
||||
vision_b1_x,vision_b1_mask=geometry_aware_vision(sample,vision_intervals,sec_bounds,sec["vision"])
|
||||
|
||||
# Word-level physical correspondence and query matrices.
|
||||
word_views={}
|
||||
for name in MODALITIES:
|
||||
result={k:[] for k in ("x","var","count","coverage_u8","mask","qbar","quality_available_fraction")}
|
||||
for aa,bb in word_bounds:
|
||||
v=aggregate(source[name][0],source[name][1],source[name][2],source[name][3],np.asarray([aa,bb],np.float64),source[name][4])
|
||||
for k in result: result[k].append(v[k][0])
|
||||
word_views[name]={k:np.asarray(v) for k,v in result.items()}
|
||||
# Sparse target-to-native overlap maps for the primary physical view.
|
||||
maps={name:sparse_overlap(source[name][2],sec_bounds) for name in MODALITIES}
|
||||
# Query channels are fixed for display only: acoustic log-energy and OpenFace AU12.
|
||||
h_audio=sparse_word_map(word_bounds,audio_intervals,sample.audio_observed[:,66].astype(np.float32))
|
||||
h_vision=sparse_word_map(word_bounds,vision_intervals,sample.vision_observed[:,10].astype(np.float32))
|
||||
dyn,dyn_valid,dyn_bounds=make_dynamics(sample,audio_intervals,vision_intervals,sec_edges)
|
||||
delta_centers=np.arange(len(audio_times),dtype=np.int64)
|
||||
delta_left=np.maximum(0,delta_centers-2)*cm.FRAME_STEP
|
||||
delta_right=np.minimum(sample_count,np.minimum(len(audio_times)-1,delta_centers+2)*cm.FRAME_STEP+cm.FRAME_LENGTH)
|
||||
delta_ranges=np.column_stack((delta_left,delta_right)).astype(np.int32)
|
||||
boundary_p05_p95,boundary_summary_json=finite_boundary_summary(sample.boundary_summary,audio_offset,audio_end_s)
|
||||
cache_file=OUT/f"{cm._safe_name(record['video_id'])}__{cm._safe_name(record['clip_id'])}.npz"
|
||||
payload:dict[str,Any]={
|
||||
"meta_json":np.asarray(json.dumps({"sample_id":sid,"video_id":record["video_id"],"clip_id":record["clip_id"],"duration_s":duration,"sentiment":sample.sentiment,"polarity":sample.polarity,"annotation":record["annotation"],"source_video_sha256":source_hash,"media":media,"config_hash":config_hash,"vision_backend":"OpenFace 2.2.0 FeatureExtraction","quality_available":{"text":bool(text_quality_available.any()),"audio":bool(sample.audio_quality_available.any()),"vision":bool(sample.vision_quality_available.any())}},ensure_ascii=False)),
|
||||
"native_text_words":np.asarray(words,dtype=str),"native_text_features":sample.text_features.astype(np.float16),"native_text_observed":sample.text_valid.astype(bool),"native_text_intervals":text_intervals.astype(np.float32),"native_text_hard_quality_uncalibrated":sample.hard_quality.astype(np.float16),"native_text_quality_effective":text_quality.astype(np.float16),"native_text_quality_available":text_quality_available,"native_text_boundary_p05_p95":boundary_p05_p95,"native_text_char_spans":char_spans,"native_text_subword_spans":subword_spans,"native_text_subword_ids":subword_ids,
|
||||
"native_audio_times":audio_times,"native_audio_features":sample.audio_features.astype(np.float16),"native_audio_mask":sample.audio_observed.astype(bool),"native_audio_quality":sample.audio_quality.astype(np.float16),"native_audio_quality_available":sample.audio_quality_available.astype(bool),"native_audio_source_range_samples":audio_ranges,"native_audio_delta_calc_range_samples":delta_ranges,"native_audio_intervals":audio_intervals,
|
||||
"native_vision_times":sample.vision_times.astype(np.float32),"native_vision_features":sample.vision_features.astype(np.float16),"native_vision_mask":sample.vision_observed.astype(bool),"native_vision_quality":sample.vision_quality.astype(np.float16),"native_vision_quality_available":sample.vision_quality_available.astype(bool),"native_vision_frame_index":frame_indices,"native_vision_intervals":vision_intervals,
|
||||
"native_ctc_times":ctc_times,"native_ctc_occupancy":sample.ctc_occupancy.astype(np.float16),"native_ctc_boundary_summary_json":np.asarray(boundary_summary_json),
|
||||
"views_sec_time_bounds_s":sec_bounds,"views_phase50_time_bounds_s":phase_bounds,"views_word_time_bounds_s":word_bounds,
|
||||
"views_sec_vision_b1_x":vision_b1_x,"views_sec_vision_b1_mask":vision_b1_mask,
|
||||
"views_dynamics_x":dyn,"views_dynamics_mask":dyn_valid,"views_dynamics_time_bounds_s":dyn_bounds,
|
||||
}
|
||||
for name in MODALITIES:
|
||||
for k,v in sec[name].items(): payload[f"views_sec_{name}_{k}"]=v
|
||||
for k,v in phase[name].items(): payload[f"views_phase50_{name}_{k}"]=v
|
||||
for k,v in word_views[name].items(): payload[f"views_word_{name}_{k}"]=v
|
||||
pack_csr(payload,f"alignment_map_{name}",maps[name])
|
||||
pack_csr(payload,"query_word_audio_H_time",h_audio)
|
||||
pack_csr(payload,"query_word_vision_H_time",h_vision)
|
||||
np.savez_compressed(cache_file,**payload)
|
||||
feature_hash=digest(cache_file)
|
||||
observed_summary={}
|
||||
for name in MODALITIES:
|
||||
vals,mask,ints,q,q_available=source[name]
|
||||
support=np.zeros(mask.shape[1],np.float64)
|
||||
for r,(a,b) in enumerate(ints):
|
||||
support += max(0.0,float(b-a))*mask[r]*(q[r]>0)
|
||||
coverage=np.clip(support/max(duration,1e-9),0,1)
|
||||
observed_summary[name]={"observed_duration_mean_s":float(np.mean(coverage)*duration),"mean_coverage":float(np.mean(coverage)),"row_count":int(len(vals)),"dimension":int(vals.shape[1]),"quality_available":bool(q_available.any()),"quality_available_fraction":float(q_available.mean()) if len(q_available) else 0.0}
|
||||
gran={"text":"word-level, variable duration; fixed-transcript CTC source interval","audio":"native 10 ms feature step; 25 ms windows; context ranges retained separately","vision":"native OpenFace frame timestamps and frame indices"}[name]
|
||||
unobserved_rows=int((~mask.any(axis=1)).sum()) if len(mask) else 0
|
||||
if name=="text":
|
||||
missing_reason=f"{int((~hard_valid).sum())} word intervals are not reliable under the fixed-transcript CTC path" if (~hard_valid).any() else "none"
|
||||
elif name=="audio":
|
||||
undefined_pitch=int((~mask[:,67]).sum()) if mask.shape[1]>67 else 0
|
||||
missing_reason=f"F0/HNR naturally undefined or unavailable in {undefined_pitch} rows; support masks retained"
|
||||
else:
|
||||
missing_reason=f"OpenFace confidence/success gate rejected {unobserved_rows} native frames" if unobserved_rows else "none"
|
||||
grid_rows.append({"sample_id":sid,"video_id":record["video_id"],"clip_id":record["clip_id"],"modality":name,"source_duration_s":duration,"observed_duration_s":observed_summary[name]["observed_duration_mean_s"],"native_length":len(vals),"native_dim":vals.shape[1],"aligned_length":len(sec_bounds),"aligned_dim":vals.shape[1],"alignment_type":"fixed 0.1 s physical grid; direct native interval projection","granularity":gran,"mean_coverage":observed_summary[name]["mean_coverage"],"missing_reason":missing_reason,"quality_available":observed_summary[name]["quality_available"],"quality_available_fraction":observed_summary[name]["quality_available_fraction"],"quality_path":f"{cache_file.name}::native_{name}_*quality*","query_map_path":f"{cache_file.name}::query_word_{name}_H_time" if name in ("audio","vision") else "not_applicable","probe_status":"content probe disabled" if name in ("audio","vision") else "not_applicable","feature_path":f"features_v2/{cache_file.name}","source_hash":source_hash,"status":"success" if mask.any() else "failed_or_unavailable","config_hash":config_hash})
|
||||
sample_status="success" if all(source[m][1].any() for m in MODALITIES) else "partial"
|
||||
sample_rows.append({"sample_id":sid,"video_id":record["video_id"],"clip_id":record["clip_id"],"source_duration_s":duration,"source_video_sha256":source_hash,"feature_path":f"features_v2/{cache_file.name}","feature_sha256":feature_hash,"sec_length":len(sec_bounds),"word_count":len(words),"hard_aligned_word_count":int(hard_valid.sum()),"unlocated_word_count":int((~hard_valid).sum()),"status":sample_status,"config_hash":config_hash})
|
||||
manifest_lines.append({"sample_id":sid,"video_id":record["video_id"],"clip_id":record["clip_id"],"feature_path":f"features_v2/{cache_file.name}","source_video_sha256":source_hash,"feature_sha256":feature_hash,"duration_s":duration,"status":sample_rows[-1]["status"],"config_hash":config_hash})
|
||||
print(f"{sid}: {len(words)} words, {len(sec_bounds)} sec steps, {cache_file.stat().st_size/1024:.1f} KiB")
|
||||
|
||||
def write_csv(path:Path,rows:list[dict[str,Any]])->None:
|
||||
with path.open("w",encoding="utf-8-sig",newline="") as f:
|
||||
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
|
||||
write_csv(OUT/"sample_summary.csv",sample_rows)
|
||||
write_csv(OUT/"modality_summary.csv",grid_rows)
|
||||
(OUT/"manifest_q1.jsonl").write_text("\n".join(json.dumps(x,ensure_ascii=False) for x in manifest_lines)+"\n",encoding="utf-8")
|
||||
configuration={"config":CONFIG,"config_hash":config_hash,"source_run_manifest":str(RUN),"source_cache_schema":"q1-b0b4-v4-openface","source_label_sha256":digest(LABELS),"python":run.get("python"),"packages":run.get("packages",{}),"models":run.get("models",{}),"samples":len(records),"modalities":300,"total_bytes":sum(p.stat().st_size for p in OUT.iterdir() if p.is_file())}
|
||||
(OUT/"feature_manifest.json").write_text(json.dumps(configuration,ensure_ascii=False,indent=2),encoding="utf-8")
|
||||
median_sample=sorted(sample_rows,key=lambda x:x["source_duration_s"])[len(sample_rows)//2]
|
||||
with np.load(OUT / Path(median_sample["feature_path"]).name, allow_pickle=False) as d:
|
||||
k=int(min(5,len(d["native_text_words"])-1)); sid=median_sample["sample_id"]
|
||||
card={"sample_id":sid,"source_video_sha256":median_sample["source_video_sha256"],"duration_s":median_sample["source_duration_s"],"word":str(d["native_text_words"][k]),"word_char_span":d["native_text_char_spans"][k].tolist(),"hard_interval_s":d["native_text_intervals"][k].tolist(),"boundary_interval_90_s":d["native_text_boundary_p05_p95"][k].tolist(),"audio_source_rows":sparse.csr_matrix((d["query_word_audio_H_time_data"].astype(np.float32),d["query_word_audio_H_time_indices"],d["query_word_audio_H_time_indptr"]),shape=tuple(d["query_word_audio_H_time_shape"])).getrow(k).indices.tolist(),"vision_source_rows":sparse.csr_matrix((d["query_word_vision_H_time_data"].astype(np.float32),d["query_word_vision_H_time_indices"],d["query_word_vision_H_time_indptr"]),shape=tuple(d["query_word_vision_H_time_shape"])).getrow(k).indices.tolist(),"manual_boundary_audit":"not available; no empirical boundary error or calibration claimed","vision_backend":"OpenFace 2.2.0"}
|
||||
(OUT/"typical_alignment_card.json").write_text(json.dumps(card,ensure_ascii=False,indent=2),encoding="utf-8")
|
||||
configuration["total_bytes"]=sum(p.stat().st_size for p in OUT.rglob("*") if p.is_file())
|
||||
(OUT/"feature_manifest.json").write_text(json.dumps(configuration,ensure_ascii=False,indent=2),encoding="utf-8")
|
||||
print(f"Wrote {len(sample_rows)} samples and {len(grid_rows)} modality rows; total {configuration['total_bytes']/1024**2:.2f} MiB")
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,315 @@
|
||||
"""Evaluate the Q1 V2 B0-B4 branches with leakage-safe video-group folds."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from sklearn.linear_model import LogisticRegression, Ridge
|
||||
from sklearn.metrics import accuracy_score, f1_score, mean_absolute_error, mean_squared_error
|
||||
from sklearn.model_selection import GroupKFold
|
||||
|
||||
from . import compare_models as cm
|
||||
from . import q1_io
|
||||
|
||||
Q1 = Path(__file__).resolve().parent
|
||||
OUT = Q1.parent / "output" / "q1" / "model_comparison_v2"
|
||||
MODALITIES = ("text", "audio", "vision", "speech")
|
||||
METHODS = ("B0", "B1", "B2", "B3", "B4")
|
||||
|
||||
|
||||
def digest(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def edges_from_bounds(bounds: np.ndarray) -> np.ndarray:
|
||||
return np.concatenate((bounds[:1, 0], bounds[:, 1])).astype(np.float32)
|
||||
|
||||
|
||||
def as_view(views: dict[str, dict[str, np.ndarray]], bounds: np.ndarray) -> cm.View:
|
||||
return cm.View(
|
||||
features={name: views[name]["x"].astype(np.float32) for name in MODALITIES},
|
||||
observed={name: views[name]["mask"].astype(bool) for name in MODALITIES},
|
||||
coverage={name: views[name]["coverage"].astype(np.float32) for name in MODALITIES},
|
||||
edges=edges_from_bounds(bounds),
|
||||
)
|
||||
|
||||
|
||||
def load_rows(records: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[cm.View], list[dict[str, np.ndarray]], list[cm.View], list[cm.View]]:
|
||||
rows, views, dynamics = [], [], []
|
||||
feature_ids = {json.loads(line)["sample_id"] for line in (q1_io.FEATURE_DIR / "manifest_q1.jsonl").read_text(encoding="utf-8").splitlines()}
|
||||
record_ids = [record["sample_id"] for record in records]
|
||||
if len(set(record_ids)) != len(record_ids) or set(record_ids) != feature_ids:
|
||||
raise ValueError("Q1 labels and V2 feature manifest keys are not a one-to-one match")
|
||||
for record in records:
|
||||
sample = q1_io.load_sample(record["sample_id"])
|
||||
base = {name: q1_io.get_view(sample, name, "sec") for name in ("text", "audio", "vision")}
|
||||
base["speech"] = q1_io.get_view(sample, "speech", "sec")
|
||||
vision_b1 = q1_io.get_view(sample, "vision", "sec", geometry_aware=True)
|
||||
b1 = {**base, "vision": vision_b1}
|
||||
posterior = {**b1, "text": q1_io.get_view(sample, "text", "posterior")}
|
||||
rows.append({**record, "duration_s": float(sample["_meta"]["duration_s"])})
|
||||
# Every model branch shares the same physical primary time bounds.
|
||||
bounds = sample["views_sec_time_bounds_s"].astype(np.float32)
|
||||
views.append(as_view(base, bounds))
|
||||
views.append(as_view(b1, bounds))
|
||||
views.append(as_view(posterior, bounds))
|
||||
with np.load(sample["_path"], allow_pickle=False) as artifact:
|
||||
dynamics.append({"x": artifact["views_dynamics_x"].astype(np.float32), "mask": artifact["views_dynamics_mask"].astype(bool), "bounds": artifact["views_dynamics_time_bounds_s"].astype(np.float32)})
|
||||
# Flatten rows as [B0,B1,B2] per sample into three separate lists.
|
||||
n = len(records)
|
||||
return rows, [views[3*i] for i in range(n)], dynamics, [views[3*i+1] for i in range(n)], [views[3*i+2] for i in range(n)]
|
||||
|
||||
|
||||
def fit_scaler(views: list[cm.View], indices: np.ndarray, mode: str) -> dict[str, tuple[np.ndarray, np.ndarray]]:
|
||||
scalers = {}
|
||||
for name in MODALITIES:
|
||||
d = views[int(indices[0])].features[name].shape[1]
|
||||
center = np.zeros(d, np.float64)
|
||||
scale = np.ones(d, np.float64)
|
||||
for j in range(d):
|
||||
chunks = [views[int(i)].features[name][:, j][views[int(i)].observed[name][:, j]] for i in indices]
|
||||
chunks = [x for x in chunks if len(x)]
|
||||
if not chunks:
|
||||
continue
|
||||
values = np.concatenate(chunks).astype(np.float64)
|
||||
if mode == "robust":
|
||||
center[j] = np.median(values)
|
||||
mad = 1.4826 * np.median(np.abs(values - center[j]))
|
||||
scale[j] = mad if mad > 1e-8 else (np.std(values) if np.std(values) > 1e-8 else 1.0)
|
||||
else:
|
||||
center[j] = np.mean(values)
|
||||
scale[j] = np.std(values) if np.std(values) > 1e-8 else 1.0
|
||||
scalers[name] = (center.astype(np.float32), scale.astype(np.float32))
|
||||
return scalers
|
||||
|
||||
|
||||
def scale_view(view: cm.View, scalers: dict[str, tuple[np.ndarray, np.ndarray]], robust: bool) -> cm.View:
|
||||
result = {}
|
||||
for name in MODALITIES:
|
||||
center, scale = scalers[name]
|
||||
values = (view.features[name] - center) / scale
|
||||
if robust:
|
||||
values = np.clip(values, -8.0, 8.0)
|
||||
result[name] = np.where(view.observed[name], values, 0.0).astype(np.float32)
|
||||
return cm.View(result, view.observed, view.coverage, view.edges)
|
||||
|
||||
|
||||
def pool_progress(view: cm.View, include_speech: bool) -> np.ndarray:
|
||||
duration = float(view.edges[-1])
|
||||
progress = np.linspace(0.0, duration, 6)
|
||||
centers = (view.edges[:-1] + view.edges[1:]) / 2
|
||||
lengths = np.diff(view.edges)
|
||||
pooled = []
|
||||
names = ("text", "audio", "vision") + (("speech",) if include_speech else ())
|
||||
for name in names:
|
||||
values = view.features[name]
|
||||
mask = view.observed[name]
|
||||
coverage = view.coverage[name]
|
||||
segments = []
|
||||
for left, right in zip(progress[:-1], progress[1:]):
|
||||
overlap = np.maximum(0.0, np.minimum(view.edges[1:], right) - np.maximum(view.edges[:-1], left))
|
||||
weight = overlap[:, None] * coverage * mask
|
||||
den = weight.sum(axis=0)
|
||||
out = np.zeros(values.shape[1], np.float32)
|
||||
good = den > 0
|
||||
if good.any():
|
||||
out[good] = (values * weight).sum(axis=0)[good] / den[good]
|
||||
segments.append(out)
|
||||
pooled.append(np.stack(segments).reshape(-1))
|
||||
return np.concatenate(pooled).astype(np.float32)
|
||||
|
||||
|
||||
def pool_dynamics(item: dict[str, np.ndarray], duration: float) -> np.ndarray:
|
||||
bounds = item["bounds"]
|
||||
values = item["x"]
|
||||
valid = item["mask"]
|
||||
centers = bounds[:, 0].mean(axis=1)
|
||||
grid_length = bounds[:, 0, 1] - bounds[:, 0, 0]
|
||||
progress = np.linspace(0.0, duration, 6)
|
||||
result = []
|
||||
for left, right in zip(progress[:-1], progress[1:]):
|
||||
sel = (centers >= left) & (centers < right)
|
||||
for branch in range(2):
|
||||
ok = sel & valid[:, branch]
|
||||
weights = grid_length[ok]
|
||||
if ok.any() and weights.sum() > 0:
|
||||
result.extend(np.average(values[ok, branch], axis=0, weights=weights).tolist())
|
||||
result.append(float(min(1.0, weights.sum() / max(right - left, 1e-8))))
|
||||
else:
|
||||
result.extend([0.0] * 6)
|
||||
result.append(0.0)
|
||||
return np.asarray(result, np.float32)
|
||||
|
||||
|
||||
def fit_dynamic_scaler(values: np.ndarray, indices: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
center = np.zeros(values.shape[1], np.float32)
|
||||
scale = np.ones(values.shape[1], np.float32)
|
||||
is_signature = np.ones(values.shape[1], bool)
|
||||
# In each 14-column block, the final column is a measured coverage fraction.
|
||||
is_signature[np.arange(6, values.shape[1], 7)] = False
|
||||
for j in np.flatnonzero(is_signature):
|
||||
coverage_j = (j // 7) * 7 + 6
|
||||
observed = values[indices, coverage_j] > 0
|
||||
vals = values[indices[observed], j]
|
||||
if not len(vals):
|
||||
continue
|
||||
center[j] = np.median(vals)
|
||||
mad = 1.4826 * np.median(np.abs(vals - center[j]))
|
||||
scale[j] = mad if mad > 1e-8 else (np.std(vals) if np.std(vals) > 1e-8 else 1.0)
|
||||
return center, scale, is_signature
|
||||
|
||||
|
||||
def scale_dynamic(values: np.ndarray, params: tuple[np.ndarray, np.ndarray, np.ndarray]) -> np.ndarray:
|
||||
center, scale, signature = params
|
||||
result = values.copy()
|
||||
result[:, signature] = np.clip((result[:, signature] - center[signature]) / scale[signature], -8.0, 8.0)
|
||||
# Preserve zeros in missing signature blocks.
|
||||
for block in range(10):
|
||||
coverage_col = block * 7 + 6
|
||||
result[result[:, coverage_col] <= 0, block * 7:block * 7 + 6] = 0.0
|
||||
return result.astype(np.float32)
|
||||
|
||||
|
||||
def metrics(y_class: np.ndarray, p_class: np.ndarray, y_value: np.ndarray, p_value: np.ndarray) -> dict[str, float]:
|
||||
pearson = float(np.corrcoef(y_value, p_value)[0, 1]) if np.std(p_value) > 1e-12 else math.nan
|
||||
return {
|
||||
"accuracy": float(accuracy_score(y_class, p_class)),
|
||||
"macro_f1": float(f1_score(y_class, p_class, labels=[0, 1, 2], average="macro", zero_division=0)),
|
||||
"mae": float(mean_absolute_error(y_value, p_value)),
|
||||
"rmse": float(np.sqrt(mean_squared_error(y_value, p_value))),
|
||||
"pearson": pearson,
|
||||
}
|
||||
|
||||
|
||||
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8-sig", newline="") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
global OUT
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--bootstrap-repeats", type=int, default=2000)
|
||||
parser.add_argument("--data-dir", type=Path, default=cm.DATA_DIR)
|
||||
parser.add_argument("--feature-dir", type=Path, default=q1_io.FEATURE_DIR)
|
||||
parser.add_argument("--output-dir", type=Path, default=OUT)
|
||||
args = parser.parse_args()
|
||||
cm.DATA_DIR = args.data_dir.resolve()
|
||||
cm.LABEL_FILE = cm.DATA_DIR / "label-100.xlsx"
|
||||
q1_io.FEATURE_DIR = args.feature_dir.resolve()
|
||||
OUT = args.output_dir.resolve()
|
||||
records = cm._read_labels(cm.LABEL_FILE)
|
||||
rows, b0, dynamics, b1, b2 = load_rows(records)
|
||||
y_class = np.asarray([r["polarity"] for r in rows], np.int64)
|
||||
y_value = np.asarray([r["sentiment"] for r in rows], np.float64)
|
||||
groups = np.asarray([r["video_id"] for r in rows], str)
|
||||
durations = np.asarray([r["duration_s"] for r in rows], np.float64)
|
||||
dynamic_values = np.stack([pool_dynamics(d, durations[i]) for i, d in enumerate(dynamics)])
|
||||
variants = {"B0": b0, "B1": b1, "B2": b2, "B3": b1, "B4": b1}
|
||||
splitter = GroupKFold(n_splits=cm.N_FOLDS)
|
||||
folds = list(splitter.split(np.zeros(len(rows)), y_class, groups))
|
||||
class_pred = {m: np.full(len(rows), -1, np.int64) for m in METHODS}
|
||||
value_pred = {m: np.full(len(rows), np.nan, np.float64) for m in METHODS}
|
||||
fold_rows = []
|
||||
split_rows = []
|
||||
for fold, (train_idx, valid_idx) in enumerate(folds, start=1):
|
||||
if set(groups[train_idx]) & set(groups[valid_idx]):
|
||||
raise ValueError("video group leakage in Q1 folds")
|
||||
for i in valid_idx:
|
||||
split_rows.append({"sample_id": rows[i]["sample_id"], "video_id": groups[i], "fold": fold, "split": "valid_oof"})
|
||||
for method in METHODS:
|
||||
source = variants[method]
|
||||
robust = method != "B0"
|
||||
scaler = fit_scaler(source, train_idx, "robust" if robust else "standard")
|
||||
scaled = [scale_view(v, scaler, robust) for v in source]
|
||||
include_speech = method == "B4"
|
||||
x_train = np.stack([pool_progress(scaled[i], include_speech) for i in train_idx])
|
||||
x_valid = np.stack([pool_progress(scaled[i], include_speech) for i in valid_idx])
|
||||
if method == "B3":
|
||||
dyn_scaler = fit_dynamic_scaler(dynamic_values, train_idx)
|
||||
dyn_scaled = scale_dynamic(dynamic_values, dyn_scaler)
|
||||
x_train = np.column_stack((x_train, dyn_scaled[train_idx]))
|
||||
x_valid = np.column_stack((x_valid, dyn_scaled[valid_idx]))
|
||||
clf = LogisticRegression(C=0.05, max_iter=2500, solver="lbfgs", random_state=cm.SEED)
|
||||
clf.fit(x_train, y_class[train_idx])
|
||||
p_cls = clf.predict(x_valid)
|
||||
reg = Ridge(alpha=25.0, solver="lsqr")
|
||||
reg.fit(x_train, y_value[train_idx])
|
||||
p_val = np.clip(reg.predict(x_valid), -3.0, 3.0)
|
||||
class_pred[method][valid_idx] = p_cls
|
||||
value_pred[method][valid_idx] = p_val
|
||||
met = metrics(y_class[valid_idx], p_cls, y_value[valid_idx], p_val)
|
||||
fold_rows.append({"method": method, "fold": fold, "train_samples": len(train_idx), "valid_samples": len(valid_idx), "train_video_groups": len(set(groups[train_idx])), "valid_video_groups": len(set(groups[valid_idx])), "feature_dimension": int(x_train.shape[1]), **met})
|
||||
print(f"fold {fold}/{cm.N_FOLDS} complete", flush=True)
|
||||
|
||||
summary = []
|
||||
prediction_rows = []
|
||||
for method in METHODS:
|
||||
overall = metrics(y_class, class_pred[method], y_value, value_pred[method])
|
||||
fold = [r for r in fold_rows if r["method"] == method]
|
||||
row = {"method": method, "sample_count": len(rows), "video_group_count": len(set(groups)), **{f"oof_{k}": v for k, v in overall.items()}}
|
||||
for key in ("accuracy", "macro_f1", "mae", "rmse", "pearson"):
|
||||
vals = np.asarray([r[key] for r in fold], np.float64)
|
||||
row[f"fold_{key}_mean"] = float(np.nanmean(vals))
|
||||
row[f"fold_{key}_sd"] = float(np.nanstd(vals, ddof=1))
|
||||
summary.append(row)
|
||||
for i, record in enumerate(rows):
|
||||
line = {"sample_id": record["sample_id"], "video_id": record["video_id"], "clip_id": record["clip_id"], "true_polarity": int(y_class[i]), "true_sentiment": float(y_value[i])}
|
||||
for method in METHODS:
|
||||
line[f"{method}_predicted_polarity"] = int(class_pred[method][i])
|
||||
line[f"{method}_predicted_sentiment"] = float(value_pred[method][i])
|
||||
prediction_rows.append(line)
|
||||
|
||||
rng = np.random.default_rng(cm.SEED + 880)
|
||||
unique_groups = np.unique(groups)
|
||||
group_ix = {g: np.flatnonzero(groups == g) for g in unique_groups}
|
||||
deltas = []
|
||||
reference = "B1"
|
||||
for method in METHODS:
|
||||
if method == reference:
|
||||
continue
|
||||
samples = {metric: [] for metric in ("accuracy", "macro_f1", "mae", "rmse", "pearson")}
|
||||
for _ in range(args.bootstrap_repeats):
|
||||
selected_groups = rng.choice(unique_groups, size=len(unique_groups), replace=True)
|
||||
ix = np.concatenate([group_ix[g] for g in selected_groups])
|
||||
base = metrics(y_class[ix], class_pred[reference][ix], y_value[ix], value_pred[reference][ix])
|
||||
alt = metrics(y_class[ix], class_pred[method][ix], y_value[ix], value_pred[method][ix])
|
||||
for key in samples:
|
||||
samples[key].append(alt[key] - base[key])
|
||||
for key, values in samples.items():
|
||||
vals = np.asarray(values, np.float64)
|
||||
deltas.append({"comparison": f"{method}-{reference}", "metric": key, "reference": reference, "estimate_delta": float(np.nanmedian(vals)), "ci95_low": float(np.nanpercentile(vals, 2.5)), "ci95_high": float(np.nanpercentile(vals, 97.5)), "bootstrap_repeats": args.bootstrap_repeats, "unit": "video_id"})
|
||||
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
write_csv(OUT / "comparison_summary.csv", summary)
|
||||
write_csv(OUT / "fold_metrics.csv", fold_rows)
|
||||
write_csv(OUT / "oof_predictions.csv", prediction_rows)
|
||||
write_csv(OUT / "split_assignments.csv", sorted(split_rows, key=lambda r: r["sample_id"]))
|
||||
write_csv(OUT / "group_bootstrap_deltas.csv", deltas)
|
||||
manifest = {"version": "E题V2 Q1 B0-B4", "samples": len(rows), "video_groups": int(len(unique_groups)), "folds": cm.N_FOLDS, "grouping": "video_id GroupKFold; train/valid group disjoint", "scalers": "B0 train-fold mean/std; B1-B4 train-fold median/MAD; no held-fold fitting", "classifier": "LogisticRegression C=0.05", "regressor": "Ridge alpha=25", "branches": {"B0": "quality-weighted physical projection", "B1": "B0 plus train-fold robust scale and SO(3)/unit-gaze aggregation", "B2": "B1 plus CTC forward-backward text occupancy", "B3": "B1 plus native-row level-2 dynamics", "B4": "B1 plus frozen Wav2Vec2 auxiliary representation"}, "B5": "query H_time audit only; not predictive score", "B6": "content probe disabled", "feature_manifest_sha256": digest(q1_io.FEATURE_DIR / "feature_manifest.json"), "source_run_manifest": "features_v2/manifest_q1.jsonl", "bootstrap_repeats": args.bootstrap_repeats}
|
||||
(OUT / "run_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
report = ["# Q1 V2 B0-B4 对照", "", "本报告使用 `features_v2/` 的 100 个样本,以 `video_id` 做五折 GroupKFold。B0–B4 的缩放器只在各折训练部分拟合。分数是情感信息探针,不是真实对齐边界准确率。", "", "| 分支 | OOF Accuracy | OOF Macro-F1 | OOF MAE | OOF RMSE | OOF Pearson |", "|---|---:|---:|---:|---:|---:|"]
|
||||
for row in summary:
|
||||
report.append(f"| {row['method']} | {row['oof_accuracy']:.4f} | {row['oof_macro_f1']:.4f} | {row['oof_mae']:.4f} | {row['oof_rmse']:.4f} | {row['oof_pearson']:.4f} |")
|
||||
report += ["", "B5 通过词查询 CSR 矩阵进行物理来源核查;没有人工边界真值,因此未报告边界误差或后验校准率。B6 内容探针未启用。视觉 17 维来自 OpenFace 2.2.0 AU 输出,不是 MediaPipe 代理。"]
|
||||
(OUT / "report.md").write_text("\n".join(report) + "\n", encoding="utf-8")
|
||||
print("Q1 V2 comparison:", [(r["method"], round(r["oof_accuracy"], 4), round(r["oof_macro_f1"], 4), round(r["oof_mae"], 4)) for r in summary], flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Read and derive Q1 V2 feature views from the native-source artifacts."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from scipy import sparse
|
||||
|
||||
Q1_DIR = Path(__file__).resolve().parent
|
||||
FEATURE_DIR = Q1_DIR.parent / "output" / "q1" / "features_v2"
|
||||
MODALITIES = ("text", "audio", "vision")
|
||||
FEATURE_DIMS = {"text": 768, "audio": 74, "vision": 35, "speech": 768}
|
||||
|
||||
|
||||
def load_sample(sample_id: str, feature_dir: Path = FEATURE_DIR) -> dict[str, Any]:
|
||||
"""Load one sample by `video_id/clip_id` and return arrays plus metadata."""
|
||||
manifest = feature_dir / "manifest_q1.jsonl"
|
||||
found = None
|
||||
for line in manifest.read_text(encoding="utf-8").splitlines():
|
||||
row = json.loads(line)
|
||||
if row["sample_id"] == sample_id:
|
||||
found = row
|
||||
break
|
||||
if found is None:
|
||||
raise KeyError(f"sample_id not found: {sample_id}")
|
||||
path = feature_dir / Path(found["feature_path"]).name
|
||||
with np.load(path, allow_pickle=False) as archive:
|
||||
result = {name: archive[name] for name in archive.files}
|
||||
result["_path"] = path
|
||||
result["_manifest"] = found
|
||||
result["_meta"] = json.loads(str(result["meta_json"]))
|
||||
return result
|
||||
|
||||
|
||||
def csr_from_sample(sample: dict[str, Any], prefix: str) -> sparse.csr_matrix:
|
||||
"""Reconstruct a stored sparse alignment/query map."""
|
||||
shape = tuple(int(v) for v in sample[f"{prefix}_shape"])
|
||||
return sparse.csr_matrix(
|
||||
(
|
||||
sample[f"{prefix}_data"].astype(np.float32),
|
||||
sample[f"{prefix}_indices"].astype(np.int32),
|
||||
sample[f"{prefix}_indptr"].astype(np.int32),
|
||||
),
|
||||
shape=shape,
|
||||
)
|
||||
|
||||
|
||||
def _native(sample: dict[str, Any], modality: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
||||
if modality == "text":
|
||||
return (
|
||||
sample["native_text_features"].astype(np.float32),
|
||||
np.broadcast_to(sample["native_text_observed"][:, None], sample["native_text_features"].shape),
|
||||
sample["native_text_intervals"].astype(np.float32),
|
||||
sample["native_text_quality_effective"].astype(np.float32),
|
||||
sample["native_text_quality_available"].astype(bool),
|
||||
)
|
||||
if modality in ("audio", "vision"):
|
||||
return (
|
||||
sample[f"native_{modality}_features"].astype(np.float32),
|
||||
sample[f"native_{modality}_mask"].astype(bool),
|
||||
sample[f"native_{modality}_intervals"].astype(np.float32),
|
||||
sample[f"native_{modality}_quality"].astype(np.float32),
|
||||
np.asarray(sample[f"native_{modality}_quality_available"], dtype=bool),
|
||||
)
|
||||
if modality == "speech":
|
||||
meta = sample["_meta"]
|
||||
safe = lambda value: re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value))
|
||||
path = Q1_DIR / "cache" / "native" / f"{safe(meta['video_id'])}__{safe(meta['clip_id'])}.npz"
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"B4 speech source cache is unavailable: {path}")
|
||||
with np.load(path, allow_pickle=False) as archive:
|
||||
values = archive["speech_features"].astype(np.float32)
|
||||
times = sample["native_ctc_times"].astype(np.float32)
|
||||
if len(values) != len(times):
|
||||
raise ValueError("B4 speech rows do not match the stored CTC timestamps")
|
||||
step = 320.0 / 16000.0
|
||||
intervals = np.column_stack((np.maximum(0.0, times - step / 2), np.minimum(float(meta["duration_s"]), times + step / 2))).astype(np.float32)
|
||||
return values, np.isfinite(values), intervals, np.ones(len(values), np.float32), np.zeros(len(values), bool)
|
||||
raise ValueError(f"unknown modality: {modality}")
|
||||
|
||||
|
||||
def _aggregate(
|
||||
values: np.ndarray,
|
||||
observed: np.ndarray,
|
||||
source_intervals: np.ndarray,
|
||||
quality: np.ndarray,
|
||||
target_intervals: np.ndarray,
|
||||
quality_available: np.ndarray | None = None,
|
||||
) -> dict[str, np.ndarray]:
|
||||
"""Quality-weight B0 means while keeping physical coverage and availability separate."""
|
||||
n, d = len(target_intervals), values.shape[1]
|
||||
mean = np.zeros((n, d), np.float32)
|
||||
var = np.zeros((n, d), np.float32)
|
||||
count = np.zeros((n, d), np.uint8)
|
||||
coverage = np.zeros((n, d), np.float32)
|
||||
qbar = np.ones((n, d), np.float32)
|
||||
qavail = np.zeros((n, d), np.float32)
|
||||
available = np.zeros(len(values), bool) if quality_available is None else np.asarray(quality_available, bool)
|
||||
mask = np.zeros((n, d), bool)
|
||||
for i, (left, right) in enumerate(target_intervals):
|
||||
width = float(right - left)
|
||||
if width <= 0 or not len(source_intervals):
|
||||
continue
|
||||
overlap = np.maximum(
|
||||
0.0,
|
||||
np.minimum(source_intervals[:, 1], right) - np.maximum(source_intervals[:, 0], left),
|
||||
)
|
||||
physical = overlap[:, None] * observed
|
||||
weighted = physical * quality[:, None]
|
||||
total = weighted.sum(axis=0)
|
||||
valid = total > 0
|
||||
if valid.any():
|
||||
weighted_sum = (values * weighted).sum(axis=0)
|
||||
weighted_sq = (np.square(values) * weighted).sum(axis=0)
|
||||
mean[i, valid] = (weighted_sum[valid] / total[valid]).astype(np.float32)
|
||||
var[i, valid] = np.maximum(0.0, weighted_sq[valid] / total[valid] - mean[i, valid] ** 2)
|
||||
mask[i, valid] = True
|
||||
physical_total = physical.sum(axis=0)
|
||||
physical_valid = physical_total > 0
|
||||
qbar[i, physical_valid] = weighted.sum(axis=0)[physical_valid] / physical_total[physical_valid]
|
||||
qavail[i, physical_valid] = (physical * available[:, None]).sum(axis=0)[physical_valid] / physical_total[physical_valid]
|
||||
coverage[i] = np.minimum(1.0, physical_total / width)
|
||||
count[i] = np.minimum(255, ((overlap[:, None] > 0) & observed).sum(axis=0)).astype(np.uint8)
|
||||
return {
|
||||
"x": mean.astype(np.float16),
|
||||
"var": var.astype(np.float32),
|
||||
"count": count,
|
||||
"coverage": coverage,
|
||||
"mask": mask,
|
||||
"quality_mean": qbar.astype(np.float32),
|
||||
"quality_available_fraction": qavail.astype(np.float32),
|
||||
}
|
||||
|
||||
|
||||
def get_view(
|
||||
sample: dict[str, Any],
|
||||
modality: str,
|
||||
view: str = "sec",
|
||||
context_s: float | None = None,
|
||||
geometry_aware: bool = False,
|
||||
) -> dict[str, np.ndarray]:
|
||||
"""Return `sec`, `phase50`, `word`, `multi`, or `posterior` features.
|
||||
|
||||
`multi` is always aggregated from native rows around each 0.1 s bin midpoint.
|
||||
For it, set `context_s` to one of 0.1, 0.3, or 0.7.
|
||||
"""
|
||||
if modality not in (*MODALITIES, "speech"):
|
||||
raise ValueError(f"unknown modality: {modality}")
|
||||
if view in ("sec", "phase50", "word"):
|
||||
bounds = sample[f"views_{view}_time_bounds_s"].astype(np.float32)
|
||||
if modality == "speech":
|
||||
values, observed, intervals, quality, available = _native(sample, modality)
|
||||
return {**_aggregate(values, observed, intervals, quality, bounds, available), "time_bounds_s": bounds}
|
||||
prefix = f"views_{view}_{modality}_"
|
||||
result = {
|
||||
"x": sample[prefix + "x"],
|
||||
"var": sample[prefix + "var"],
|
||||
"count": sample[prefix + "count"],
|
||||
"coverage": sample[prefix + "coverage_u8"].astype(np.float32) / 255.0,
|
||||
"mask": sample[prefix + "mask"].astype(bool),
|
||||
"quality_mean": sample[prefix + "qbar"].astype(np.float32),
|
||||
"quality_available_fraction": sample[prefix + "quality_available_fraction"].astype(np.float32),
|
||||
"time_bounds_s": bounds,
|
||||
}
|
||||
if view == "sec" and modality == "vision" and geometry_aware:
|
||||
result["x"] = sample["views_sec_vision_b1_x"]
|
||||
result["mask"] = sample["views_sec_vision_b1_mask"].astype(bool)
|
||||
return result
|
||||
if view == "multi":
|
||||
if context_s not in (0.1, 0.3, 0.7):
|
||||
raise ValueError("context_s must be one of 0.1, 0.3, or 0.7")
|
||||
centers = sample["views_sec_time_bounds_s"].astype(np.float32).mean(axis=1)
|
||||
duration = float(sample["_meta"]["duration_s"])
|
||||
bounds = np.column_stack((np.maximum(0.0, centers - context_s / 2), np.minimum(duration, centers + context_s / 2))).astype(np.float32)
|
||||
values, observed, intervals, quality, available = _native(sample, modality)
|
||||
return {**_aggregate(values, observed, intervals, quality, bounds, available), "time_bounds_s": bounds}
|
||||
if view == "posterior":
|
||||
if modality != "text":
|
||||
raise ValueError("posterior projection is defined for text only")
|
||||
return posterior_text_view(sample)
|
||||
raise ValueError(f"unknown view: {view}")
|
||||
|
||||
|
||||
def posterior_text_view(sample: dict[str, Any]) -> dict[str, np.ndarray]:
|
||||
"""Project CTC forward-backward word occupancy directly to the 0.1 s grid."""
|
||||
edges = sample["views_sec_time_bounds_s"].astype(np.float32)
|
||||
words = sample["native_text_features"].astype(np.float32)
|
||||
word_ok = sample["native_text_observed"].astype(bool)
|
||||
occupancy = sample["native_ctc_occupancy"].astype(np.float32)
|
||||
times = sample["native_ctc_times"].astype(np.float32)
|
||||
if occupancy.ndim != 2 or occupancy.shape[1] != len(words):
|
||||
raise ValueError("CTC occupancy word dimension does not match the native text rows")
|
||||
step = 320.0 / 16000.0
|
||||
half = step / 2
|
||||
duration = float(sample["_meta"]["duration_s"])
|
||||
source = np.column_stack((np.maximum(0.0, times - half), np.minimum(duration, times + half))).astype(np.float32)
|
||||
n, d = len(edges), words.shape[1]
|
||||
result = np.zeros((n, d), np.float32)
|
||||
var = np.zeros((n, d), np.float32)
|
||||
count = np.zeros(n, np.uint8)
|
||||
coverage = np.zeros(n, np.float32)
|
||||
mask = np.zeros(n, bool)
|
||||
mass_by_word = np.zeros((n, len(words)), np.float32)
|
||||
for i, (left, right) in enumerate(edges):
|
||||
overlap = np.maximum(0.0, np.minimum(source[:, 1], right) - np.maximum(source[:, 0], left))
|
||||
mass_by_word[i] = (occupancy * overlap[:, None]).sum(axis=0)
|
||||
w = mass_by_word[i] * word_ok
|
||||
total = float(w.sum())
|
||||
if total > 0:
|
||||
normalized = w / total
|
||||
result[i] = normalized @ words
|
||||
centered = words - result[i]
|
||||
var[i] = (normalized[:, None] * np.square(centered)).sum(axis=0)
|
||||
mask[i] = True
|
||||
count[i] = min(255, int(np.count_nonzero(w > 0)))
|
||||
coverage[i] = min(1.0, total / max(float(right - left), 1e-8))
|
||||
return {
|
||||
"x": result.astype(np.float16),
|
||||
"var": var,
|
||||
"count": np.broadcast_to(count[:, None], result.shape).copy(),
|
||||
"coverage": np.broadcast_to(coverage[:, None], result.shape).copy(),
|
||||
"mask": np.broadcast_to(mask[:, None], result.shape).copy(),
|
||||
"quality_mean": np.ones_like(result, dtype=np.float32),
|
||||
"quality_available_fraction": np.zeros_like(result, dtype=np.float32),
|
||||
"word_posterior_mass": mass_by_word,
|
||||
"time_bounds_s": edges,
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$VideoRelativePath,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$OutputName
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$q1Directory = $PSScriptRoot
|
||||
$repositoryDirectory = Split-Path $q1Directory -Parent
|
||||
$packageDirectory = Join-Path $q1Directory 'cache/openface/OpenFace_2.2.0_win_x64'
|
||||
$executable = Join-Path $packageDirectory 'FeatureExtraction.exe'
|
||||
if ([System.IO.Path]::IsPathRooted($VideoRelativePath)) {
|
||||
$videoPath = $VideoRelativePath
|
||||
}
|
||||
else {
|
||||
$videoPath = Join-Path $repositoryDirectory ($VideoRelativePath -replace '/', '\')
|
||||
}
|
||||
$outputDirectory = Join-Path $q1Directory 'cache/openface_outputs'
|
||||
$null = New-Item -ItemType Directory -Force -Path $outputDirectory
|
||||
|
||||
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) {
|
||||
throw "OpenFace 2.2.0 executable not found: $executable"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $videoPath -PathType Leaf)) {
|
||||
throw "Input video not found: $videoPath"
|
||||
}
|
||||
|
||||
Push-Location $packageDirectory
|
||||
try {
|
||||
& $executable -mloc model/main_clnf_general.txt -f $videoPath -out_dir $outputDirectory -of $OutputName -2Dfp -pose -aus -gaze
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "OpenFace FeatureExtraction failed with exit code $LASTEXITCODE for $VideoRelativePath"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Projection invariants from E题V2: quality weights means, not physical coverage."""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import compare_models as cm
|
||||
|
||||
|
||||
class ProjectionCoverageTests(unittest.TestCase):
|
||||
def test_quality_changes_mean_but_not_physical_coverage(self) -> None:
|
||||
values = np.asarray([[0.0], [10.0]], dtype=np.float32)
|
||||
observed = np.ones_like(values, dtype=bool)
|
||||
intervals = np.asarray([[0.0, 0.5], [0.5, 1.0]], dtype=np.float32)
|
||||
qualities = np.asarray([1.0, 1e-8], dtype=np.float32)
|
||||
edges = np.asarray([0.0, 1.0], dtype=np.float32)
|
||||
projected, mask, coverage = cm._project_rows(values, observed, intervals, qualities, edges)
|
||||
self.assertTrue(bool(mask[0, 0]))
|
||||
self.assertAlmostEqual(float(projected[0, 0]), 10.0 * 1e-8 / (1.0 + 1e-8), places=6)
|
||||
self.assertAlmostEqual(float(coverage[0, 0]), 1.0, places=6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Render a selected Q1 word-to-source alignment example."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
matplotlib.rcParams["font.family"] = ["FandolHei", "DejaVu Sans"]
|
||||
matplotlib.rcParams["axes.unicode_minus"] = False
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from matplotlib.colors import PowerNorm
|
||||
|
||||
Q1_DIR = Path(__file__).resolve().parent
|
||||
from .q1_io import csr_from_sample, load_sample
|
||||
|
||||
|
||||
def time_edges(centers: np.ndarray, intervals: np.ndarray, duration_s: float) -> np.ndarray:
|
||||
"""Make non-overlapping display bins centered on each native source row."""
|
||||
centers = np.asarray(centers, dtype=np.float64).reshape(-1)
|
||||
intervals = np.asarray(intervals, dtype=np.float64)
|
||||
if not len(centers):
|
||||
return np.asarray([0.0, duration_s], dtype=np.float64)
|
||||
if len(centers) == 1:
|
||||
half_width = max(float(intervals[0, 1] - intervals[0, 0]) / 2, 1e-3)
|
||||
return np.asarray(
|
||||
[max(0.0, centers[0] - half_width), min(duration_s, centers[0] + half_width)],
|
||||
dtype=np.float64,
|
||||
)
|
||||
if np.any(np.diff(centers) <= 0):
|
||||
raise ValueError("native source timestamps must be strictly increasing")
|
||||
middle = (centers[:-1] + centers[1:]) / 2
|
||||
first = max(0.0, centers[0] - (middle[0] - centers[0]))
|
||||
last = min(duration_s, centers[-1] + (centers[-1] - middle[-1]))
|
||||
return np.concatenate(([first], middle, [last]))
|
||||
|
||||
|
||||
def read_records() -> list[dict[str, Any]]:
|
||||
path = Q1_DIR / "features_v2" / "manifest_q1.jsonl"
|
||||
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def choose_sample(sample_id: str) -> tuple[dict[str, Any], dict[str, Any], Any, Any]:
|
||||
record = next((item for item in read_records() if item["sample_id"] == sample_id), None)
|
||||
if record is None:
|
||||
raise ValueError(f"sample_id not found in Q1 manifest: {sample_id}")
|
||||
sample = load_sample(sample_id)
|
||||
audio_map = csr_from_sample(sample, "query_word_audio_H_time")
|
||||
vision_map = csr_from_sample(sample, "query_word_vision_H_time")
|
||||
if not audio_map.nnz or not vision_map.nnz:
|
||||
raise ValueError(f"sample has no valid audio or vision query rows: {sample_id}")
|
||||
return record, sample, audio_map, vision_map
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--sample-id", default="-iRBcNs9oI8/8")
|
||||
parser.add_argument("--output", type=Path, default=None)
|
||||
args = parser.parse_args()
|
||||
|
||||
record, sample, audio_map, vision_map = choose_sample(args.sample_id)
|
||||
words = [str(word) for word in sample["native_text_words"]]
|
||||
if audio_map.shape[0] != len(words) or vision_map.shape[0] != len(words):
|
||||
raise ValueError("query matrix word rows do not match the stored transcript")
|
||||
duration_s = float(sample["_meta"]["duration_s"])
|
||||
|
||||
modalities = [
|
||||
(
|
||||
"原始音频位置",
|
||||
audio_map,
|
||||
sample["native_audio_intervals"],
|
||||
"音频窗中心时间 (s)",
|
||||
"音频窗",
|
||||
),
|
||||
(
|
||||
"原始视频帧位置",
|
||||
vision_map,
|
||||
sample["native_vision_intervals"],
|
||||
"视频帧中心时间 (s)",
|
||||
"视频帧",
|
||||
),
|
||||
]
|
||||
matrices = [item[1].toarray().astype(np.float32) for item in modalities]
|
||||
for matrix in (audio_map, vision_map):
|
||||
row_sums = np.asarray(matrix.sum(axis=1)).reshape(-1)
|
||||
populated = row_sums > 0
|
||||
if populated.any() and not np.allclose(row_sums[populated], 1.0, atol=2e-3):
|
||||
raise ValueError("each populated word-query row should sum to one")
|
||||
nonzero = np.concatenate([matrix[matrix > 0] for matrix in matrices if np.any(matrix > 0)])
|
||||
color_max = max(float(nonzero.max()), 1e-6)
|
||||
|
||||
height = max(10.5, min(26.0, 4.0 + 0.22 * len(words)))
|
||||
tick_size = max(5.5, min(8.5, 8.8 - 0.045 * len(words)))
|
||||
fig = plt.figure(figsize=(15, height))
|
||||
grid = fig.add_gridspec(4, 1, height_ratios=(4.0, 1.35, 4.0, 1.35), hspace=0.35)
|
||||
y_edges = np.arange(len(words) + 1, dtype=np.float64)
|
||||
text_intervals = np.asarray(sample["native_text_intervals"], dtype=np.float64)
|
||||
text_valid = text_intervals[:, 1] > text_intervals[:, 0]
|
||||
text_centers = text_intervals.mean(axis=1)
|
||||
meshes = []
|
||||
heat_axes = []
|
||||
|
||||
for plot_index, ((title, _sparse_matrix, intervals, _xlabel, row_name), matrix) in enumerate(zip(modalities, matrices)):
|
||||
axis = fig.add_subplot(grid[2 * plot_index])
|
||||
text_axis = fig.add_subplot(grid[2 * plot_index + 1], sharex=axis)
|
||||
heat_axes.append(axis)
|
||||
intervals = np.asarray(intervals, dtype=np.float64)
|
||||
centers = intervals.mean(axis=1)
|
||||
x_edges = time_edges(centers, intervals, duration_s)
|
||||
mesh = axis.pcolormesh(
|
||||
x_edges,
|
||||
y_edges,
|
||||
matrix,
|
||||
shading="flat",
|
||||
cmap="magma",
|
||||
norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=color_max),
|
||||
rasterized=True,
|
||||
)
|
||||
meshes.append(mesh)
|
||||
axis.set_xlim(0.0, duration_s)
|
||||
axis.set_ylim(len(words), 0)
|
||||
axis.set_xticks([])
|
||||
axis.set_yticks([])
|
||||
axis.set_xlabel("")
|
||||
axis.set_ylabel("")
|
||||
axis.grid(False)
|
||||
axis.set_frame_on(False)
|
||||
for spine in axis.spines.values():
|
||||
spine.set_visible(False)
|
||||
axis.text(
|
||||
0.0,
|
||||
1.025,
|
||||
f"{title}(列为{row_name};有效源行的词内权重和为 1)",
|
||||
transform=axis.transAxes,
|
||||
ha="left",
|
||||
va="bottom",
|
||||
fontsize=11,
|
||||
clip_on=False,
|
||||
)
|
||||
for word_index, word in enumerate(words):
|
||||
axis.text(
|
||||
-0.012,
|
||||
word_index + 0.5,
|
||||
word,
|
||||
transform=axis.get_yaxis_transform(),
|
||||
ha="right",
|
||||
va="center",
|
||||
fontsize=tick_size,
|
||||
clip_on=False,
|
||||
)
|
||||
|
||||
# Place actual transcript words along the source-time axis using the
|
||||
# center of each stored CTC word interval.
|
||||
text_axis.set_xlim(0.0, duration_s)
|
||||
text_axis.set_ylim(0.0, 1.0)
|
||||
text_axis.set_xticks([])
|
||||
text_axis.set_yticks([])
|
||||
text_axis.set_frame_on(False)
|
||||
for spine in text_axis.spines.values():
|
||||
spine.set_visible(False)
|
||||
for center, word, valid in zip(text_centers, words, text_valid):
|
||||
if valid:
|
||||
text_axis.text(
|
||||
center,
|
||||
0.96,
|
||||
word,
|
||||
rotation=90,
|
||||
ha="center",
|
||||
va="top",
|
||||
fontsize=tick_size,
|
||||
clip_on=False,
|
||||
)
|
||||
text_axis.grid(False)
|
||||
|
||||
fig.subplots_adjust(left=0.17, right=0.88, top=0.91, bottom=0.08)
|
||||
colorbar = fig.colorbar(meshes[0], ax=heat_axes, fraction=0.025, pad=0.02)
|
||||
colorbar.ax.set_title("重叠\n权重", fontsize=8, pad=8)
|
||||
sample_id = record["sample_id"]
|
||||
fig.suptitle(
|
||||
f"词到原始音频/视频位置查询矩阵|样本 {sample_id}",
|
||||
fontsize=14,
|
||||
y=0.97,
|
||||
)
|
||||
fig.text(
|
||||
0.17,
|
||||
0.02,
|
||||
"横轴为真实源时间 (s),每个文本标注位于对应词区间中心。颜色表示每个词内归一化的物理时间交叠权重,不是学习得到的内容相似度。",
|
||||
fontsize=8,
|
||||
ha="left",
|
||||
)
|
||||
|
||||
output = args.output or (Q1_DIR.parent / "output" / "q1" / "alignment_query_example.png")
|
||||
output = output.resolve()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
fig.savefig(output, dpi=220, facecolor="white")
|
||||
plt.close(fig)
|
||||
|
||||
metadata = {
|
||||
"sample_id": sample_id,
|
||||
"selection": "manually selected example with valid audio and vision query maps",
|
||||
"duration_s": duration_s,
|
||||
"word_count": len(words),
|
||||
"words": words,
|
||||
"audio_query_shape": list(audio_map.shape),
|
||||
"audio_query_nnz": int(audio_map.nnz),
|
||||
"audio_query_mapped_words": int(np.count_nonzero(np.asarray(audio_map.sum(axis=1)).reshape(-1))),
|
||||
"vision_query_shape": list(vision_map.shape),
|
||||
"vision_query_nnz": int(vision_map.nnz),
|
||||
"vision_query_mapped_words": int(np.count_nonzero(np.asarray(vision_map.sum(axis=1)).reshape(-1))),
|
||||
"audio_query_feature_validity_channel": "log_energy (audio feature dimension 66)",
|
||||
"vision_query_feature_validity_channel": "OpenFace AU12 intensity (vision feature dimension 10)",
|
||||
"alignment_semantics": "per-word normalized overlap between stored CTC word intervals and native source intervals; no learned content similarity",
|
||||
"coordinate_axes_shown": False,
|
||||
"color_scale": "shared square-root intensity transform for visibility; original overlap weights retained",
|
||||
"word_label_positions": "actual transcript labels placed at their CTC word-interval centers on the source-time axis",
|
||||
"image": str(output),
|
||||
}
|
||||
metadata_path = output.with_suffix(".json")
|
||||
metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(metadata, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user