Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

Measure ambiguous assignments tracks and visit decisions in Go

Baurzhan Atynov4dbef984c9d5
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.yml
index 970e0c1..bf08643 100644
--- a/.github/workflows/go-gallery.yml
+++ b/.github/workflows/go-gallery.yml
@@ -62,7 +62,7 @@ jobs:
np.vstack((near_and_boundary, random)).astype("<f4").tofile(output / "queries")
PY
cd go/facex
- go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale|MathModelFixture|MathWorkloads)$' -count=1 ./...
+ go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale|MathModelFixture|MathWorkloads|DecisionModelReplay|DecisionWorkloads)$' -count=1 ./...
- name: Verify concurrent engine replies against serial inference
working-directory: go/facex
env:
diff --git a/docs/research/25_go_decisions_ru.md b/docs/research/25_go_decisions_ru.md
new file mode 100644
index 0000000..9baa106
--- /dev/null
+++ b/docs/research/25_go_decisions_ru.md
@@ -0,0 +1,45 @@
+# 25 задач для принятия и проверки решений FaceX
+
+Реализация на Go использует стандартную библиотеку. Команды ниже запускаются из go/facex. Новые методы доступны отдельно от обычного Identify. Подбор параметров, приоритет ручной проверки и статистический аудит выполняются на явно переданных данных.
+
+| № | Задача | Метод и результат |
+|---|---|---|
+| 1 | Суммировать веса всех допустимых назначений лиц с возможностью пропуска | InferAssignments возвращает логарифм нормирующей суммы. Динамика по маске уже занятых кандидатов использует log-sum-exp. |
+| 2 | Узнать модельную вероятность каждого ID и пропуска для каждой строки | Прямой и обратный проход по маскам суммируют массы всех совместимых решений. |
+| 3 | Получить распределение числа совпадений в кадре | Массы финальных масок складываются по числу занятых столбцов. |
+| 4 | Измерить неопределённость всего кадра с учётом конкуренции за ID | Энтропия совместного распределения равна log Z минус ожидаемый суммарный лог-вес. |
+| 5 | Минимизировать ожидаемое число неверных решений по строкам | Вторая динамика максимизирует сумму маргинальных вероятностей при уникальности ID. Пропуск тоже является решением. |
+| 6 | Найти лучшую последовательность состояний трека при штрафе за смену | SolveTrackPath восстанавливает оптимальный путь по указателям предшественников. |
+| 7 | Оценить цену вынужденной смены решения в конкретном кадре | Прямая и обратная полезности дают лучший путь, в котором этот кадр имеет другое состояние. Нулевая потеря означает равносильную альтернативу. |
+| 8 | Построить оптимум для каждого точного числа переключений | Динамика по времени, числу переключений и состоянию сохраняет двух лучших разных предшественников. |
+| 9 | Найти минимальный штраф, при котором оптимален постоянный ID | Сравниваем лучший постоянный путь со всеми точками кривой «число смен — полезность». При граничном штрафе возможна ничья. |
+| 10 | Найти диапазон штрафов для каждого возможного числа переключений | Пересечение линейных неравенств показывает также числа смен, которые нельзя сделать оптимальными ни одним штрафом. |
+| 11 | Разбить видеотрек на k непрерывных сегментов с минимумом суммарного искажения | SegmentDirections использует стоимость отрезка 2(L − ‖Σu‖) для единичных векторов, затем восстанавливает оптимальные границы. |
+| 12 | Минимизировать искажение самого плохого сегмента | Отдельный minimax-переход учитывает худшую локальную ошибку. |
+| 13 | Выбрать количество сегментов с учётом цены каждой новой границы | Минимизируем оптимальное суммарное искажение плюс штраф за k−1 границ. |
+| 14 | Найти наименьшее число сегментов при локальном ограничении искажения | Проверяем minimax-кривую; 0 означает, что ни одно разрешённое число сегментов не подходит. |
+| 15 | Найти стоимость второго, отличного разбиения при фиксированном k | Два лучших различных пути на ячейку сохраняют вторую стоимость, включая равную первой. При единственном разбиении стоимость альтернативы бесконечна. |
+| 16 | Построить полный обмен между объёмом проверки, снятыми ошибками и задержанными правильными ID | AnalyzeReview сортирует принятые решения и обрабатывает все равные приоритеты одним блоком. Один элемент — один размеченный визит. |
+| 17 | Снять максимум ошибок при лимите задержанных правильных решений | Выбираем достижимый детерминированный порог по полной кривой. |
+| 18 | Найти наименьший объём ручной проверки при допустимом числе оставшихся ошибок | Первый достижимый порог, удовлетворяющий целевому остатку. |
+| 19 | Найти порог с минимальной суммарной ценой проверки и оставшихся ошибок | Перебираем все пороги, включая отсутствие проверки. |
+| 20 | Сравнить приоритеты проверки сразу по всем уровням покрытия | Дискретная площадь риск–покрытие усредняет ожидаемую долю ошибок для каждого непустого размера оставшейся выборки. Внутри равного приоритета порядок равновероятен. |
+| 21 | Оценить интервал частоты ошибок по числу визитов | VisitErrorInterval обращает биномиальные хвосты для центрального интервала Клоппера–Пирсона. |
+| 22 | Проверить изменение частоты ошибок двух правил на одних и тех же визитах | AuditPairedVisits вычисляет двусторонний точный критерий Мак-Немара по числу исправленных и внесённых ошибок. |
+| 23 | Ограничить абсолютное снижение риска ошибок в парном эксперименте | Одновременные биномиальные интервалы для двух направлений расхождения по поправке Бонферрони дают консервативный интервал разности. |
+| 24 | Определить объём независимой проверки при нуле наблюдаемых ошибок | ZeroErrorVisits обращает (1−p)^n для односторонней доверительной границы. |
+| 25 | Оценить отношение вероятностей «стало лучше / стало хуже» | Условный биномиальный интервал по расходящимся парам переводится в интервал шансов. При отсутствии расхождений интервал от 0 до бесконечности. |
+
+## Границы применимости
+
+Лог-веса назначения задаются относительно пропуска. Для вероятностной интерпретации на камерах их необходимо калибровать отдельно. Расчёт точный в рамках заданной конечной модели с обычным округлением float64, экспоненциален по числу кандидатов и ограничен 16 кандидатами и 2²⁰ ячейками на таблицу. Трек допускает до 256 кадров и 64 состояний. Добавьте отдельный столбец для неизвестного, если это предусмотрено моделью трека. Сегментация допускает до 256 кадров, сравнивает все разбиения через динамическое программирование и занимает O(T²d + KT²) времени. Нулевые векторы для неё недопустимы.
+
+Для аудита двух правил нужны одни и те же размеченные визиты, заранее зафиксированные правила и независимость между визитами. Кадры одного визита нельзя считать отдельными независимыми наблюдениями. Интервалы по визитам поддерживают от 1 до 1 000 000 наблюдений. Детерминированное снятие ID означает передачу на проверку; исход работы оператора моделируется отдельно.
+
+## Воспроизведение
+
+- `go test -race -run '^TestDecision' ./...` — независимые проверки по малым задачам и граничным случаям.
+- `FACEX_GALLERY_SCALE=1 go test -v -run '^TestDecisionWorkloads$'` — замеры на фиксированных синтетических входах.
+- В CI TestDecisionModelReplay использует прежние векторы EdgeFace XS: 10 исходных людей в регистрации, 5 оставлены неизвестными. Первый по сходству ID служит базовой линией. Фиксированный порог отрыва 0,1 передаёт спорный ответ на перепроверку. Это стенд на фотографиях, а не разметка реальных посещений.
+
+Справка по условному парному тесту и интервалу шансов: [R exact2x2](https://search.r-project.org/CRAN/refmans/exact2x2/html/exact2x2.html).
diff --git a/go/facex/assignment_posterior.go b/go/facex/assignment_posterior.go
new file mode 100644
index 0000000..48681cd
--- /dev/null
+++ b/go/facex/assignment_posterior.go
@@ -0,0 +1,135 @@
+package facex
+
+import (
+ "errors"
+ "math"
+ "math/bits"
+)
+
+// AssignmentPosterior describes the Gibbs distribution on partial matchings.
+// Each row may abstain with log weight zero. The last marginal column is abstention.
+type AssignmentPosterior struct {
+ LogNormalizer, Entropy float64
+ Marginals [][]float64
+ CountProbability []float64
+ MinimumHamming []int
+}
+
+func logPlus(a, b float64) float64 {
+ if a < b {
+ a, b = b, a
+ }
+ if math.IsInf(b, -1) {
+ return a
+ }
+ return a + math.Log1p(math.Exp(b-a))
+}
+
+// InferAssignments accepts log weights relative to abstention, in [-100,100],
+// or negative infinity for forbidden edges. Scores need external calibration
+// before the model probabilities can be interpreted as observed frequencies.
+func InferAssignments(w [][]float64) (AssignmentPosterior, error) {
+ n := len(w)
+ m := 0
+ if n > 0 {
+ m = len(w[0])
+ }
+ if m > 16 || n+1 > (1<<20)/(1<<m) {
+ return AssignmentPosterior{}, errors.New("facex: posterior state limit exceeded")
+ }
+ size := 1 << m
+ for _, r := range w {
+ if len(r) != m {
+ return AssignmentPosterior{}, errors.New("facex: jagged weights")
+ }
+ for _, v := range r {
+ if !math.IsInf(v, -1) && !(v >= -100 && v <= 100) {
+ return AssignmentPosterior{}, errors.New("facex: invalid log weight")
+ }
+ }
+ }
+ f := make([]float64, (n+1)*size)
+ for i := 1; i < len(f); i++ {
+ f[i] = math.Inf(-1)
+ }
+ for i, row := range w {
+ for mask, v := range f[i*size : (i+1)*size] {
+ if math.IsInf(v, -1) {
+ continue
+ }
+ next := f[(i+1)*size : (i+2)*size]
+ next[mask] = logPlus(next[mask], v)
+ for j, edge := range row {
+ bit := 1 << j
+ if mask&bit == 0 {
+ next[mask|bit] = logPlus(next[mask|bit], v+edge)
+ }
+ }
+ }
+ }
+ last := f[n*size:]
+ z := math.Inf(-1)
+ for _, v := range last {
+ z = logPlus(z, v)
+ }
+ out := AssignmentPosterior{LogNormalizer: z, Entropy: z, Marginals: make([][]float64, n), CountProbability: make([]float64, min(n, m)+1), MinimumHamming: make([]int, n)}
+ for mask, v := range last {
+ if !math.IsInf(v, -1) {
+ out.CountProbability[bits.OnesCount(uint(mask))] += math.Exp(v - z)
+ }
+ }
+ back, temp := make([]float64, size), make([]float64, size)
+ for i := n - 1; i >= 0; i-- {
+ p := make([]float64, m+1)
+ out.Marginals[i] = p
+ for mask, b := range back {
+ prefix := f[i*size+mask] - z
+ p[m] += math.Exp(prefix + b)
+ s := b
+ for j, edge := range w[i] {
+ bit := 1 << j
+ if mask&bit != 0 || math.IsInf(edge, -1) {
+ continue
+ }
+ v := edge + back[mask|bit]
+ p[j] += math.Exp(prefix + v)
+ s = logPlus(s, v)
+ }
+ temp[mask] = s
+ }
+ for j, edge := range w[i] {
+ if !math.IsInf(edge, -1) {
+ out.Entropy -= p[j] * edge
+ }
+ }
+ back, temp = temp, back
+ }
+ out.Entropy = max(0., out.Entropy)
+ // Maximize expected correct row decisions under the same exclusion rules.
+ clear(back)
+ policy := make([]int8, n*size)
+ for i := n - 1; i >= 0; i-- {
+ for mask := range back {
+ best := out.Marginals[i][m] + back[mask]
+ choice := int8(-1)
+ for j, p := range out.Marginals[i][:m] {
+ bit := 1 << j
+ if mask&bit == 0 && !math.IsInf(w[i][j], -1) && p+back[mask|bit] > best {
+ best, choice = p+back[mask|bit], int8(j)
+ }
+ }
+ temp[mask] = best
+ policy[i*size+mask] = choice
+ }
+ back, temp = temp, back
+ }
+ mask := 0
+ for i := range out.MinimumHamming {
+ j := int(policy[i*size+mask])
+ out.MinimumHamming[i] = j
+ if j >= 0 {
+ mask |= 1 << j
+ }
+ }
+ return out, nil
+}
diff --git a/go/facex/decision_math_test.go b/go/facex/decision_math_test.go
new file mode 100644
index 0000000..2359195
--- /dev/null
+++ b/go/facex/decision_math_test.go
@@ -0,0 +1,544 @@
+package facex
+
+import (
+ "encoding/binary"
+ "math"
+ "math/rand"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+ "time"
+)
+
+func near25(t *testing.T, a, b float64) {
+ t.Helper()
+ if a == b {
+ return
+ }
+ if math.IsNaN(a) || math.IsNaN(b) || math.Abs(a-b) > 2e-9 {
+ t.Fatalf("got %.14g want %.14g", a, b)
+ }
+}
+func TestDecisionPosteriorOracle(t *testing.T) {
+ r := rand.New(rand.NewSource(125))
+ for trial := 0; trial < 180; trial++ {
+ n, m := 1+r.Intn(5), r.Intn(5)
+ w := make([][]float64, n)
+ for i := range w {
+ w[i] = make([]float64, m)
+ for j := range w[i] {
+ x := r.Intn(7) - 3
+ w[i][j] = float64(x)
+ if x == 3 {
+ w[i][j] = math.Inf(-1)
+ }
+ }
+ }
+ got, e := InferAssignments(w)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var choices [][]int
+ var weight []float64
+ var visit func([]int, int, float64)
+ visit = func(a []int, used int, l float64) {
+ if len(a) == n {
+ choices = append(choices, slices.Clone(a))
+ weight = append(weight, math.Exp(l))
+ return
+ }
+ i := len(a)
+ visit(append(a, -1), used, l)
+ for j, x := range w[i] {
+ if used&(1<<j) == 0 && !math.IsInf(x, -1) {
+ visit(append(a, j), used|(1<<j), l+x)
+ }
+ }
+ }
+ visit(nil, 0, 0)
+ z := 0.
+ for _, v := range weight {
+ z += v
+ }
+ near25(t, got.LogNormalizer, math.Log(z))
+ marg := make([][]float64, n)
+ for i := range marg {
+ marg[i] = make([]float64, m+1)
+ }
+ count := make([]float64, min(n, m)+1)
+ entropy := 0.
+ for l, a := range choices {
+ p := weight[l] / z
+ entropy -= p * math.Log(p)
+ k := 0
+ for i, j := range a {
+ if j < 0 {
+ j = m
+ } else {
+ k++
+ }
+ marg[i][j] += p
+ }
+ count[k] += p
+ }
+ near25(t, got.Entropy, entropy)
+ for k, x := range count {
+ near25(t, got.CountProbability[k], x)
+ }
+ for i, v := range marg {
+ for j, p := range v {
+ near25(t, got.Marginals[i][j], p)
+ }
+ }
+ objective := func(a []int) float64 {
+ s := 0.
+ for i, j := range a {
+ if j < 0 {
+ j = m
+ }
+ s += marg[i][j]
+ }
+ return s
+ }
+ best := 0.
+ valid := false
+ for _, a := range choices {
+ best = max(best, objective(a))
+ valid = valid || slices.Equal(a, got.MinimumHamming)
+ }
+ if !valid {
+ t.Fatal("infeasible Hamming decision")
+ }
+ near25(t, best, objective(got.MinimumHamming))
+ }
+}
+
+func TestDecisionTrackOracle(t *testing.T) {
+ r := rand.New(rand.NewSource(225))
+ for trial := 0; trial < 220; trial++ {
+ n, k := 1+r.Intn(6), 1+r.Intn(4)
+ s := make([][]int, n)
+ for i := range s {
+ s[i] = make([]int, k)
+ for j := range s[i] {
+ s[i][j] = r.Intn(9) - 4
+ }
+ }
+ lambda := r.Intn(9)
+ got, e := SolveTrackPath(s, lambda)
+ if e != nil {
+ t.Fatal(e)
+ }
+ by := make([]int64, len(got.BestBySwitchCount))
+ for i := range by {
+ by[i] = pathAbsent
+ }
+ alt := make([]int64, n)
+ for i := range alt {
+ alt[i] = pathAbsent
+ }
+ best := pathAbsent
+ path := make([]int, n)
+ var visit func(int, int, int64)
+ visit = func(i, c int, sum int64) {
+ if i == n {
+ by[c] = max(by[c], sum)
+ u := sum - int64(c*lambda)
+ best = max(best, u)
+ for j, x := range path {
+ if x != got.States[j] {
+ alt[j] = max(alt[j], u)
+ }
+ }
+ return
+ }
+ for h, x := range s[i] {
+ next := c
+ if i > 0 && path[i-1] != h {
+ next++
+ }
+ path[i] = h
+ visit(i+1, next, sum+int64(x))
+ }
+ }
+ visit(0, 0, 0)
+ if !slices.Equal(by, got.BestBySwitchCount) || got.Utility != best {
+ t.Fatal(trial, by, got)
+ }
+ var score int64
+ for j, h := range got.States {
+ score += int64(s[j][h])
+ if j > 0 && h != got.States[j-1] {
+ score -= int64(lambda)
+ }
+ loss := int64(-1)
+ if alt[j] != pathAbsent {
+ loss = best - alt[j]
+ }
+ if got.AlternativeLoss[j] != loss {
+ t.Fatal(trial, j)
+ }
+ }
+ if score != best {
+ t.Fatal("wrong path")
+ }
+ for steps := 0; steps < 50; steps++ {
+ p := float64(steps) / 3
+ opt := math.Inf(-1)
+ for c, x := range by {
+ opt = max(opt, float64(x)-float64(c)*p)
+ }
+ for c, x := range by {
+ v := got.PenaltyIntervals[c]
+ inside := v.Possible && p >= v.Low && p <= v.High
+ tie := math.Abs(float64(x)-float64(c)*p-opt) < 1e-10
+ if inside != tie {
+ t.Fatal(trial, c, p, v)
+ }
+ }
+ if (p >= got.ConstantPenalty) != (math.Abs(float64(by[0])-opt) < 1e-10) {
+ t.Fatal("constant penalty")
+ }
+ }
+ }
+}
+
+func TestDecisionSegmentsOracle(t *testing.T) {
+ r := rand.New(rand.NewSource(325))
+ for trial := 0; trial < 90; trial++ {
+ n := 1 + r.Intn(8)
+ rows := make([][]float32, n)
+ for i := range rows {
+ rows[i] = basis(r.Intn(4))
+ }
+ penalty, limit := r.Float64()*2, r.Float64()*3
+ g, e := SegmentDirections(rows, n, penalty, limit)
+ if e != nil {
+ t.Fatal(e)
+ }
+ costs := make([][]float64, n)
+ worst := make([]float64, n)
+ for i := range worst {
+ worst[i] = math.Inf(1)
+ }
+ loss := func(start, end int) float64 {
+ var sum [4]float64
+ for _, v := range rows[start:end] {
+ for j := range sum {
+ sum[j] += float64(v[j])
+ }
+ }
+ l := math.Sqrt(directionDot(sum[:], sum[:]))
+ s := 0.
+ for _, v := range rows[start:end] {
+ for j, c := range sum {
+ d := float64(v[j]) - c/l
+ s += d * d
+ }
+ }
+ return s
+ }
+ for mask := 0; mask < 1<<(n-1); mask++ {
+ k, start := 0, 0
+ total, mx := 0., 0.
+ for i := 1; i <= n; i++ {
+ if i == n || mask&(1<<(i-1)) != 0 {
+ x := loss(start, i)
+ total += x
+ mx = max(mx, x)
+ start = i
+ k++
+ }
+ }
+ costs[k-1] = append(costs[k-1], total)
+ worst[k-1] = min(worst[k-1], mx)
+ }
+ choice, target := 0, 0
+ best := math.Inf(1)
+ for j, c := range costs {
+ slices.Sort(c)
+ fit := g.ByCount[j]
+ near25(t, fit.Loss, c[0])
+ near25(t, fit.WorstLoss, worst[j])
+ second := math.Inf(1)
+ if len(c) > 1 {
+ second = c[1]
+ }
+ near25(t, fit.SecondLoss, second)
+ total, start := 0., 0
+ for _, end := range fit.Ends {
+ if end <= start {
+ t.Fatal("empty segment")
+ }
+ total += loss(start, end)
+ start = end
+ }
+ near25(t, total, fit.Loss)
+ if start != n || len(fit.Ends) != j+1 {
+ t.Fatal(fit.Ends)
+ }
+ if v := c[0] + float64(j)*penalty; v < best {
+ choice, best = j+1, v
+ }
+ if target == 0 && worst[j] <= limit {
+ target = j + 1
+ }
+ }
+ if choice != g.PenalizedCount || target != g.CountForBound {
+ t.Fatal(choice, target, g)
+ }
+ }
+}
+
+func TestDecisionReviewOracle(t *testing.T) {
+ r := rand.New(rand.NewSource(425))
+ for trial := 0; trial < 140; trial++ {
+ n := 1 + r.Intn(7)
+ v := make([]ReviewVisit, n)
+ for i := range v {
+ v[i] = ReviewVisit{float64(r.Intn(3)), r.Intn(2) == 0}
+ }
+ budget, target := r.Intn(n+1), r.Intn(n+1)
+ g, e := AnalyzeReview(v, budget, target, 1, 3)
+ if e != nil {
+ t.Fatal(e)
+ }
+ cap, least, bestCost := -1, n+1, math.MaxInt
+ for _, p := range g.Curve {
+ withheld, removed, left := 0, 0, 0
+ for _, x := range v {
+ if x.Priority >= p.Threshold {
+ if x.Wrong {
+ removed++
+ } else {
+ withheld++
+ }
+ } else if x.Wrong {
+ left++
+ }
+ }
+ if p.Reviewed != withheld+removed || p.RemainingWrong != left || p.WrongRemoved != removed || p.CorrectWithheld != withheld {
+ t.Fatal(p)
+ }
+ if withheld <= budget {
+ cap = max(cap, removed)
+ }
+ if left <= target {
+ least = min(least, p.Reviewed)
+ }
+ bestCost = min(bestCost, p.Reviewed+3*left)
+ }
+ if cap != g.BestWithinCorrectBudget.WrongRemoved || least != g.LeastForErrorTarget.Reviewed || bestCost != g.MinimumCost.Reviewed+3*g.MinimumCost.RemainingWrong {
+ t.Fatal(g)
+ }
+ // Enumerate all priority-respecting retained orders, including tied visits.
+ sum := 0.
+ orders := 0
+ var perm func(int, int, int, float64, float64)
+ perm = func(depth, used, wrong int, last, area float64) {
+ if depth == n {
+ orders++
+ sum += area / float64(n)
+ return
+ }
+ for i, x := range v {
+ if used&(1<<i) != 0 || x.Priority < last {
+ continue
+ }
+ err := wrong
+ if x.Wrong {
+ err++
+ }
+ perm(depth+1, used|(1<<i), err, x.Priority, area+float64(err)/float64(depth+1))
+ }
+ }
+ perm(0, 0, 0, math.Inf(-1), 0)
+ near25(t, g.RiskCoverageArea, sum/float64(orders))
+ }
+}
+
+func TestDecisionVisitStatistics(t *testing.T) {
+ for _, v := range []struct {
+ n, k int
+ lo, hi float64
+ }{{10, 3, .06673951117773447, .652452850060008}, {50, 0, 0, .07112173646420458}, {1000000, 12, .000006200589987895605, .000020961491123670386}, {1000000, 500000, .4990195191953118, .5009804808046883}} {
+ got, e := VisitErrorInterval(v.n, v.k, .05)
+ if e != nil {
+ t.Fatal(e)
+ }
+ near25(t, got.Low, v.lo)
+ near25(t, got.High, v.hi)
+ }
+ g, e := AuditPairedVisits(100, 8, 2, .05)
+ if e != nil {
+ t.Fatal(e)
+ }
+ near25(t, g.McNemarP, .109375)
+ near25(t, g.DiscordantOdds.Low, .7982524004966308)
+ near25(t, g.DiscordantOdds.High, 38.6656560797152)
+ near25(t, g.ErrorReduction.Low, -.047882280472540936)
+ near25(t, g.ErrorReduction.High, .1608739820078152)
+ n, e := ZeroErrorVisits(.001, .05)
+ if e != nil || n != 2995 {
+ t.Fatal(n, e)
+ }
+ g, e = AuditPairedVisits(100, 0, 0, .05)
+ if e != nil || g.McNemarP != 1 || !math.IsInf(g.DiscordantOdds.High, 1) {
+ t.Fatal(g, e)
+ }
+}
+
+func TestDecisionWorkloads(t *testing.T) {
+ if os.Getenv("FACEX_GALLERY_SCALE") != "1" {
+ t.Skip("scale workload")
+ }
+ r := rand.New(rand.NewSource(25))
+ w := make([][]float64, 12)
+ for i := range w {
+ w[i] = make([]float64, 12)
+ for j := range w[i] {
+ w[i][j] = r.NormFloat64()
+ }
+ }
+ now := time.Now()
+ if _, e := InferAssignments(w); e != nil {
+ t.Fatal(e)
+ }
+ t.Log("exact posterior 12 by 12", time.Since(now))
+ s := make([][]int, 180)
+ for i := range s {
+ s[i] = make([]int, 20)
+ for j := range s[i] {
+ s[i][j] = r.Intn(101)
+ }
+ }
+ now = time.Now()
+ if _, e := SolveTrackPath(s, 25); e != nil {
+ t.Fatal(e)
+ }
+ t.Log("track 180 frames 20 states", time.Since(now))
+ rows := make([][]float32, 128)
+ for i := range rows {
+ rows[i] = basis(r.Intn(30))
+ }
+ now = time.Now()
+ if _, e := SegmentDirections(rows, 12, 1, 3); e != nil {
+ t.Fatal(e)
+ }
+ t.Log("segmentation 128 frames", time.Since(now))
+ visits := make([]ReviewVisit, 100000)
+ for i := range visits {
+ visits[i] = ReviewVisit{float64(r.Intn(1000)), r.Intn(10) == 0}
+ }
+ now = time.Now()
+ if _, e := AnalyzeReview(visits, 1000, 500, 1, 10); e != nil {
+ t.Fatal(e)
+ }
+ t.Log("review 100000 visits", time.Since(now))
+}
+
+// Each fixture photo contributes one query. Ten people are enrolled, five
+// are held out. This is a replay of still images, not independent visits.
+func TestDecisionModelReplay(t *testing.T) {
+ dir := os.Getenv("FACEX_GALLERY_FIXTURE")
+ if dir == "" {
+ t.Skip("requires model fixture")
+ }
+ rows, e := os.Open(filepath.Join(dir, "rows"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer rows.Close()
+ qf, e := os.Open(filepath.Join(dir, "queries"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer qf.Close()
+ axes := make([][]float64, 10)
+ for i := range axes {
+ if _, e = rows.Seek(int64(i)*4369*OutputSize*4, 0); e != nil {
+ t.Fatal(e)
+ }
+ views := make([][]float32, 8)
+ for j := range views {
+ views[j] = make([]float32, OutputSize)
+ if e = binary.Read(rows, binary.LittleEndian, views[j]); e != nil {
+ t.Fatal(e)
+ }
+ }
+ f, e := FitDirections(views, nil)
+ if e != nil || f.Template == nil {
+ t.Fatal(e)
+ }
+ axes[i] = f.Template
+ }
+ var visits []ReviewVisit
+ fixed, withheld, remaining := 0, 0, 0
+ for truth := 0; truth < 15; truth++ {
+ q := make([]float32, OutputSize)
+ if e = binary.Read(qf, binary.LittleEndian, q); e != nil {
+ t.Fatal(e)
+ }
+ u, e := unitViews([][]float32{q})
+ if e != nil {
+ t.Fatal(e)
+ }
+ best, next, id := -2., -2., -1
+ for j, a := range axes {
+ x := directionDot(a, u[0])
+ if x > best {
+ next, best, id = best, x, j
+ } else if x > next {
+ next = x
+ }
+ }
+ gap := best - next
+ wrong := id != truth
+ visits = append(visits, ReviewVisit{-gap, wrong})
+ if gap <= .1 {
+ if wrong {
+ fixed++
+ } else {
+ withheld++
+ }
+ } else if wrong {
+ remaining++
+ }
+ }
+ a, e := AnalyzeReview(visits, 0, 0, 1, 3)
+ if e != nil {
+ t.Fatal(e)
+ }
+ before := a.Curve[0].RemainingWrong
+ if before != fixed+remaining {
+ t.Fatal("replay mismatch")
+ }
+ t.Logf("fixture top1 replay queries=15 enrolled=10 held_out=5 wrong_before=%d wrong_removed=%d correct_withheld=%d wrong_remaining=%d gap_cutoff=0.1", before, fixed, withheld, remaining)
+}
+
+func TestDecisionInvalidAndExtreme(t *testing.T) {
+ if _, e := InferAssignments([][]float64{{math.NaN()}}); e == nil {
+ t.Fatal("invalid weight")
+ }
+ x, e := InferAssignments([][]float64{{math.Inf(-1), 100}, {math.Inf(-1), -100}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, v := range x.Marginals {
+ near25(t, v[0], 0)
+ near25(t, v[0]+v[1]+v[2], 1)
+ }
+ if _, e = SolveTrackPath([][]int{{0}, {}}, 1); e == nil {
+ t.Fatal("jagged track")
+ }
+ if _, e = SegmentDirections([][]float32{make([]float32, OutputSize)}, 1, 0, 0); e == nil {
+ t.Fatal("zero vector")
+ }
+ if _, e = AnalyzeReview([]ReviewVisit{{math.NaN(), false}}, 0, 0, 1, 1); e == nil {
+ t.Fatal("invalid priority")
+ }
+ if _, e = AuditPairedVisits(4, 3, 2, .05); e == nil {
+ t.Fatal("invalid counts")
+ }
+}
diff --git a/go/facex/track_path.go b/go/facex/track_path.go
new file mode 100644
index 0000000..27c9289
--- /dev/null
+++ b/go/facex/track_path.go
@@ -0,0 +1,159 @@
+package facex
+
+import (
+ "errors"
+ "math"
+)
+
+// TrackPath treats each column as a state (which may include unknown).
+// Scores and switchPenalty are integer utilities in the same units.
+type TrackPath struct {
+ States []int
+ Utility int64
+ AlternativeLoss, BestBySwitchCount []int64
+ ConstantPenalty float64
+ PenaltyIntervals []PenaltyInterval
+}
+
+// PenaltyInterval is the closed nonnegative penalty interval on which a switch count is optimal.
+type PenaltyInterval struct {
+ Low, High float64
+ Possible bool
+}
+
+const pathAbsent int64 = math.MinInt64 / 4
+
+// SolveTrackPath solves the offline sequence for up to 256 frames and 64 states.
+// Every state at every frame has an explicit finite utility in [-1e6,1e6].
+func SolveTrackPath(scores [][]int, switchPenalty int) (TrackPath, error) {
+ t := len(scores)
+ if t == 0 || t > 256 || len(scores[0]) == 0 || len(scores[0]) > 64 || switchPenalty < 0 || switchPenalty > 1000000000 {
+ return TrackPath{}, errors.New("facex: invalid track shape or penalty")
+ }
+ k := len(scores[0])
+ for _, row := range scores {
+ if len(row) != k {
+ return TrackPath{}, errors.New("facex: jagged track")
+ }
+ for _, x := range row {
+ if x < -1000000 || x > 1000000 {
+ return TrackPath{}, errors.New("facex: invalid track utility")
+ }
+ }
+ }
+ penalty := int64(switchPenalty)
+ forward := make([]int64, t*k)
+ pred := make([]int, t*k)
+ for j, v := range scores[0] {
+ forward[j] = int64(v)
+ }
+ for i := 1; i < t; i++ {
+ for j, v := range scores[i] {
+ best := forward[(i-1)*k+j]
+ origin := j
+ for prev := 0; prev < k; prev++ {
+ x := forward[(i-1)*k+prev] - penalty
+ if x > best {
+ best, origin = x, prev
+ }
+ }
+ forward[i*k+j] = best + int64(v)
+ pred[i*k+j] = origin
+ }
+ }
+ out := TrackPath{States: make([]int, t), AlternativeLoss: make([]int64, t)}
+ end := 0
+ for j := 1; j < k; j++ {
+ if forward[(t-1)*k+j] > forward[(t-1)*k+end] {
+ end = j
+ }
+ }
+ out.Utility = forward[(t-1)*k+end]
+ for i := t - 1; i >= 0; i-- {
+ out.States[i] = end
+ end = pred[i*k+end]
+ }
+ tail, next := make([]int64, k), make([]int64, k)
+ for i := t - 1; i >= 0; i-- {
+ alt := pathAbsent
+ for j := 0; j < k; j++ {
+ if j != out.States[i] {
+ alt = max(alt, forward[i*k+j]+tail[j])
+ }
+ }
+ out.AlternativeLoss[i] = -1
+ if alt != pathAbsent {
+ out.AlternativeLoss[i] = out.Utility - alt
+ }
+ for j := 0; j < k; j++ {
+ best := int64(scores[i][j]) + tail[j]
+ for h := 0; h < k; h++ {
+ best = max(best, int64(scores[i][h])+tail[h]-penalty)
+ }
+ next[j] = best
+ }
+ tail, next = next, tail
+ }
+ // For exactly c changes, keep the two best predecessor states so the
+ // best one different from j is available in O(1).
+ prev, curr := make([]int64, t*k), make([]int64, t*k)
+ for a := range prev {
+ prev[a] = pathAbsent
+ }
+ copy(prev, forward[:k])
+ for i := 1; i < t; i++ {
+ for c := 0; c <= i; c++ {
+ first, second, idx := pathAbsent, pathAbsent, -1
+ if c > 0 {
+ for h, x := range prev[(c-1)*k : c*k] {
+ if x > first {
+ first, second, idx = x, first, h
+ } else {
+ second = max(second, x)
+ }
+ }
+ }
+ for j, v := range scores[i] {
+ change := first
+ if idx == j {
+ change = second
+ }
+ stay := pathAbsent
+ if c < i {
+ stay = prev[c*k+j]
+ }
+ best := max(change, stay)
+ curr[c*k+j] = best
+ if best != pathAbsent {
+ curr[c*k+j] += int64(v)
+ }
+ }
+ }
+ prev, curr = curr, prev
+ }
+ counts := t
+ if k == 1 {
+ counts = 1
+ }
+ out.BestBySwitchCount = make([]int64, counts)
+ for c := 0; c < counts; c++ {
+ best := pathAbsent
+ for _, v := range prev[c*k : (c+1)*k] {
+ best = max(best, v)
+ }
+ out.BestBySwitchCount[c] = best
+ }
+ for c, v := range out.BestBySwitchCount {
+ lo, hi := 0., math.Inf(1)
+ for h, w := range out.BestBySwitchCount {
+ if h > c {
+ lo = max(lo, float64(w-v)/float64(h-c))
+ } else if h < c {
+ hi = min(hi, float64(v-w)/float64(c-h))
+ }
+ }
+ out.PenaltyIntervals = append(out.PenaltyIntervals, PenaltyInterval{lo, hi, lo <= hi})
+ }
+ out.ConstantPenalty = out.PenaltyIntervals[0].Low
+ return out, nil
+}
diff --git a/go/facex/track_segments.go b/go/facex/track_segments.go
new file mode 100644
index 0000000..1a404ff
--- /dev/null
+++ b/go/facex/track_segments.go
@@ -0,0 +1,89 @@
+package facex
+
+import (
+ "errors"
+ "math"
+)
+
+// SegmentFit summarizes a partition of a track into K contiguous nonempty segments.
+// Ends are exclusive. SecondLoss is the cost of the best distinct partition
+// with this K, including an equal-cost alternative. Losses sum squared chords
+// to unit representatives. WorstLoss is minimized separately over partitions.
+type SegmentFit struct {
+ Ends []int
+ Loss, SecondLoss, WorstLoss float64
+}
+type SegmentFrontier struct {
+ ByCount []SegmentFit
+ PenalizedCount, CountForBound int
+}
+
+// SegmentDirections fits from one through maxSegments segments (up to 256 frames).
+// CountForBound is zero when no partition respects maxSegmentLoss for every segment.
+func SegmentDirections(rows [][]float32, maxSegments int, penalty, maxSegmentLoss float64) (SegmentFrontier, error) {
+ n := len(rows)
+ if n > 256 || maxSegments < 1 || maxSegments > n || !(penalty >= 0 && maxSegmentLoss >= 0) || math.IsInf(penalty, 0) {
+ return SegmentFrontier{}, errors.New("facex: invalid segmentation settings")
+ }
+ u, e := unitViews(rows)
+ if e != nil {
+ return SegmentFrontier{}, e
+ }
+ width := n + 1
+ cost := make([]float64, width*width)
+ for start := 0; start < n; start++ {
+ var sum [OutputSize]float64
+ for end := start + 1; end <= n; end++ {
+ for j, v := range u[end-1] {
+ sum[j] += v
+ }
+ if end-start > 1 {
+ cost[start*width+end] = 2 * max(0., float64(end-start)-math.Sqrt(directionDot(sum[:], sum[:])))
+ }
+ }
+ }
+ type cell struct {
+ best, second, worst float64
+ start int
+ }
+ table := make([]cell, (maxSegments+1)*width)
+ for i := range table {
+ table[i] = cell{math.Inf(1), math.Inf(1), math.Inf(1), -1}
+ }
+ table[0] = cell{0, math.Inf(1), 0, -1}
+ out := SegmentFrontier{}
+ opt := math.Inf(1)
+ for k := 1; k <= maxSegments; k++ {
+ for end := k; end <= n; end++ {
+ c := &table[k*width+end]
+ for start := k - 1; start < end; start++ {
+ p := table[(k-1)*width+start]
+ x := cost[start*width+end]
+ cand := p.best + x
+ if cand < c.best {
+ c.second, c.best, c.start = c.best, cand, start
+ } else {
+ c.second = min(c.second, cand)
+ }
+ c.second = min(c.second, p.second+x)
+ c.worst = min(c.worst, max(p.worst, x))
+ }
+ }
+ c := table[k*width+n]
+ ends := make([]int, k)
+ end := n
+ for j := k; j > 0; j-- {
+ ends[j-1] = end
+ end = table[j*width+end].start
+ }
+ out.ByCount = append(out.ByCount, SegmentFit{ends, c.best, c.second, c.worst})
+ if val := c.best + float64(k-1)*penalty; val < opt {
+ opt = val
+ out.PenalizedCount = k
+ }
+ if out.CountForBound == 0 && c.worst <= maxSegmentLoss {
+ out.CountForBound = k
+ }
+ }
+ return out, nil
+}
diff --git a/go/facex/visit_review.go b/go/facex/visit_review.go
new file mode 100644
index 0000000..d904382
--- /dev/null
+++ b/go/facex/visit_review.go
@@ -0,0 +1,89 @@
+package facex
+
+import (
+ "errors"
+ "math"
+ "sort"
+)
+
+// ReviewVisit is one accepted ID decision for a labeled visit. Higher priority
+// is reviewed first. Wrong includes a false grant or an incorrect identity.
+type ReviewVisit struct {
+ Priority float64
+ Wrong bool
+}
+type ReviewPoint struct {
+ Threshold float64
+ Reviewed, WrongRemoved, CorrectWithheld, RemainingWrong int
+}
+type ReviewAnalysis struct {
+ Curve []ReviewPoint
+ BestWithinCorrectBudget, LeastForErrorTarget, MinimumCost ReviewPoint
+ TargetFeasible bool
+ RiskCoverageArea float64
+}
+
+// AnalyzeReview sweeps all inclusive priority thresholds with equal scores kept
+// together. RiskCoverageArea averages the expected retained error fraction at
+// every nonzero integer coverage, with random order within equal priorities.
+func AnalyzeReview(visits []ReviewVisit, maxCorrectWithheld, maxResidualErrors int, reviewCost, wrongCost float64) (ReviewAnalysis, error) {
+ if len(visits) == 0 || maxCorrectWithheld < 0 || maxResidualErrors < 0 || !(reviewCost >= 0 && wrongCost >= 0) || math.IsInf(reviewCost, 0) || math.IsInf(wrongCost, 0) {
+ return ReviewAnalysis{}, errors.New("facex: invalid review settings")
+ }
+ rows := append([]ReviewVisit(nil), visits...)
+ total := 0
+ for _, v := range rows {
+ if math.IsNaN(v.Priority) || math.IsInf(v.Priority, 0) {
+ return ReviewAnalysis{}, errors.New("facex: nonfinite priority")
+ }
+ if v.Wrong {
+ total++
+ }
+ }
+ sort.Slice(rows, func(i, j int) bool { return rows[i].Priority > rows[j].Priority })
+ p := ReviewPoint{Threshold: math.Inf(1), RemainingWrong: total}
+ out := ReviewAnalysis{Curve: []ReviewPoint{p}, BestWithinCorrectBudget: p, LeastForErrorTarget: p, MinimumCost: p, TargetFeasible: total <= maxResidualErrors}
+ // Normalize the costs to keep finite counts from overflowing an extreme price.
+ scale := max(reviewCost, wrongCost)
+ if scale > 0 {
+ reviewCost /= scale
+ wrongCost /= scale
+ }
+ bestCost := float64(total) * wrongCost
+ for i := 0; i < len(rows); {
+ start := i
+ wrong := 0
+ level := rows[i].Priority
+ for i < len(rows) && rows[i].Priority == level {
+ if rows[i].Wrong {
+ wrong++
+ }
+ i++
+ }
+ group := i - start
+ p.Threshold = level
+ p.Reviewed = i
+ p.WrongRemoved += wrong
+ p.RemainingWrong -= wrong
+ p.CorrectWithheld = i - p.WrongRemoved
+ out.Curve = append(out.Curve, p)
+ if p.CorrectWithheld <= maxCorrectWithheld && p.WrongRemoved > out.BestWithinCorrectBudget.WrongRemoved {
+ out.BestWithinCorrectBudget = p
+ }
+ if !out.TargetFeasible && p.RemainingWrong <= maxResidualErrors {
+ out.TargetFeasible = true
+ out.LeastForErrorTarget = p
+ }
+ cost := float64(i)*reviewCost + float64(p.RemainingWrong)*wrongCost
+ if cost < bestCost {
+ bestCost = cost
+ out.MinimumCost = p
+ }
+ kept := len(rows) - i
+ for j := 1; j <= group; j++ {
+ out.RiskCoverageArea += (float64(p.RemainingWrong) + float64(j)*float64(wrong)/float64(group)) / float64(kept+j)
+ }
+ }
+ out.RiskCoverageArea /= float64(len(rows))
+ return out, nil
+}
diff --git a/go/facex/visit_uncertainty.go b/go/facex/visit_uncertainty.go
new file mode 100644
index 0000000..2962eb0
--- /dev/null
+++ b/go/facex/visit_uncertainty.go
@@ -0,0 +1,114 @@
+package facex
+
+import (
+ "errors"
+ "math"
+)
+
+type ProbabilityInterval struct{ Low, High float64 }
+
+// Binomial CDF via the smaller-side recurrence around the binomial mode.
+func binomialBelow(n, k int, p float64) float64 {
+ if k < 0 {
+ return 0
+ }
+ if k >= n || p <= 0 {
+ return 1
+ }
+ if p >= 1 {
+ return 0
+ }
+ if float64(k) >= float64(n)*p {
+ return 1 - binomialLeft(n, n-k-1, 1-p)
+ }
+ return binomialLeft(n, k, p)
+}
+func binomialLeft(n, k int, p float64) float64 {
+ if p == 0 {
+ return 1
+ }
+ if p == 1 {
+ return 0
+ }
+ a, _ := math.Lgamma(float64(n + 1))
+ b, _ := math.Lgamma(float64(k + 1))
+ c, _ := math.Lgamma(float64(n - k + 1))
+ term := math.Exp(a - b - c + float64(k)*math.Log(p) + float64(n-k)*math.Log1p(-p))
+ sum := term
+ for j := k; j > 0; j-- {
+ term *= float64(j) / float64(n-j+1) * ((1 - p) / p)
+ old := sum
+ sum += term
+ if sum == old {
+ break
+ }
+ }
+ return min(1., sum)
+}
+func upperBinomial(n, k int, tail float64) float64 {
+ if k == n {
+ return 1
+ }
+ if k == 0 {
+ return -math.Expm1(math.Log(tail) / float64(n))
+ }
+ lo, hi := 0., 1.
+ for i := 0; i < 64; i++ {
+ mid := (lo + hi) / 2
+ if binomialBelow(n, k, mid) > tail {
+ lo = mid
+ } else {
+ hi = mid
+ }
+ }
+ return hi
+}
+func centralInterval(n, k int, alpha float64) ProbabilityInterval {
+ return ProbabilityInterval{1 - upperBinomial(n, n-k, alpha/2), upperBinomial(n, k, alpha/2)}
+}
+
+// VisitErrorInterval gives the central Clopper-Pearson interval for a fixed
+// binary error definition and independent identically distributed visits.
+func VisitErrorInterval(n, k int, alpha float64) (ProbabilityInterval, error) {
+ if n < 1 || n > 1000000 || k < 0 || k > n || !(alpha >= 1e-12 && alpha < 1) {
+ return ProbabilityInterval{}, errors.New("facex: invalid binomial audit")
+ }
+ return centralInterval(n, k, alpha), nil
+}
+
+// ZeroErrorVisits gives the least number of independent error-free visits for
+// a one-sided upper bound at most target, at confidence 1-alpha.
+func ZeroErrorVisits(target, alpha float64) (int, error) {
+ if !(target > 0 && target < 1 && alpha >= 1e-12 && alpha < 1) {
+ return 0, errors.New("facex: invalid zero-error target")
+ }
+ v := math.Ceil(math.Log(alpha) / math.Log1p(-target))
+ if v > 1e9 {
+ return 0, errors.New("facex: required sample exceeds one billion")
+ }
+ return int(v), nil
+}
+
+// Fixed counts visits where only the old policy erred; introduced counts
+// visits where only the new policy erred. Both policies see the same visits.
+type PairedAudit struct {
+ McNemarP float64
+ ErrorReduction, DiscordantOdds ProbabilityInterval
+}
+
+func AuditPairedVisits(n, fixed, introduced int, alpha float64) (PairedAudit, error) {
+ if n < 1 || n > 1000000 || fixed < 0 || introduced < 0 || fixed > n || introduced > n-fixed || !(alpha >= 1e-12 && alpha < 1) {
+ return PairedAudit{}, errors.New("facex: invalid paired audit")
+ }
+ d := fixed + introduced
+ out := PairedAudit{McNemarP: 1, DiscordantOdds: ProbabilityInterval{0, math.Inf(1)}}
+ if d > 0 {
+ out.McNemarP = min(1., 2*binomialBelow(d, min(fixed, introduced), .5))
+ x := centralInterval(d, fixed, alpha)
+ out.DiscordantOdds = ProbabilityInterval{x.Low / (1 - x.Low), x.High / (1 - x.High)}
+ }
+ // Simultaneous marginal intervals via a union bound, then subtract.
+ a, b := centralInterval(n, fixed, alpha/2), centralInterval(n, introduced, alpha/2)
+ out.ErrorReduction = ProbabilityInterval{a.Low - b.High, a.High - b.Low}
+ return out, nil
+}