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.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Solve enrollment verification and association objectives in Go
Baurzhan Atynovc2dbf8b6726d
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.ymlindex f940822..970e0c1 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")PYcd go/facex- go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale)$' -count=1 ./...+ go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale|MathModelFixture|MathWorkloads)$' -count=1 ./...- name: Verify concurrent engine replies against serial inferenceworking-directory: go/facexenv:diff --git a/docs/research/15_go_math_ru.md b/docs/research/15_go_math_ru.mdnew file mode 100644index 0000000..7e0aafd--- /dev/null+++ b/docs/research/15_go_math_ru.md@@ -0,0 +1,27 @@+# 15 задач для Go SDK FaceX++Все функции находятся в пакете go/facex. Вычисления регистрации и верификации используют float64. Сопоставление принимает целочисленную матрицу полезностей в миллионных долях. Пропуск имеет нулевую полезность. Запрещённое ребро отмечают значением ForbiddenAssociation. Перед сопоставлением по косинусу вызывающая сторона выбирает порог допустимости и переводит оценки в эти единицы.++| № | Задача | Решение и результат |+|---:|---|---|+| 1 | Построить единичный шаблон, минимизирующий взвешенную сумму квадратов хордовых расстояний | FitDirections нормирует взвешенную сумму единичных векторов. При почти полном сокращении направлений Template равен nil. |+| 2 | Найти реальное наблюдение, минимизирующее суммарное взвешенное косинусное расстояние | Максимизируем скалярное произведение наблюдения со взвешенной суммой. Поле Medoid вычисляется за O(nd) для n снимков размерности d. |+| 3 | Найти максимальный поворот шаблона после удаления одного снимка | Префиксные и суффиксные суммы дают все n направлений за O(nd). Угол берётся через atan2. При неопределённом направлении хотя бы в одном исключении LeaveOneOutDefined равен false. |+| 4 | Выбрать один снимок, лучше всего покрывающий худший ракурс | CoverViews(rows, 1) максимизирует наименьший косинус до выбранного наблюдения. Достаточно одного минимума на ракурс. |+| 5 | Найти оптимальную пару эталонных ракурсов | Для порога косинуса строим битовые множества покрытых снимков. Проверяем, покрывает ли их объединение двух множеств, и ищем наибольший достижимый порог среди наблюдаемых значений. |+| 6 | Оценить ROC AUC с одинаковыми оценками | EvaluateVerification обрабатывает группу равных оценок за один переход. Равенство подлинной и посторонней пары получает половинный вес. |+| 7 | Измерить качество только до заданной частоты ложных совпадений | Точно отсекаем последний отрезок ломаной ROC в точке maxFAR и считаем ненормированную площадь PartialAUC. |+| 8 | Найти частоту ошибок при равенстве FAR и FRR | Ищем пересечение на интерполированной ROC. EER может лежать между двумя достижимыми целочисленными режимами. |+| 9 | Найти рабочий порог с минимальной ценой ошибок | Перебираем все достижимые пороги и минимизируем prior-weighted costMiss × FRR + costFalse × FAR. Включён вариант отклонения всех пар. |+| 10 | Принять максимум подлинных пар при жёстком бюджете ложных совпадений | Выбираем детерминированную рабочую точку BudgetPoint. Группа равных оценок принимается целиком. |+| 11 | Сопоставить лица и кандидатов с максимальной суммарной полезностью, разрешая пропуски | AnalyzeAssociations возвращает Best. Каждый кандидат может принадлежать только одному лицу. |+| 12 | Найти максимум допустимых соответствий и лучшую полезность при этом количестве | MostMatches использует лексикографический приоритет числа совпадений, затем полезности. |+| 13 | Измерить, насколько неоднозначно каждое отдельное назначение с учётом перестановок остальных лиц | AssociationRegrets вычисляет минимальную потерю при принудительной смене решения каждой строки. Для равносильной альтернативы потеря нулевая, при отсутствии альтернативы возвращается -1. |+| 14 | Обеспечить наилучшую оценку самого слабого совпадения для заданного числа лиц | AssociationBottleneck ищет максимальный порог, при котором существуют k независимых рёбер. Проверка выполнимости использует увеличивающие пути. |+| 15 | Получить точный оптимум для каждого достижимого числа соответствий | ByCount хранит полную кривую «число назначений → максимальная полезность» и сами назначения. Каждый следующий поток может пересматривать уже выбранные рёбра. |++Для задач 11, 12 и 15 путь минимальной стоимости в остаточной сети переводит оптимальное k-сопоставление в оптимальное (k+1)-сопоставление. Для задачи 13 добавляем каждому лицу личный столбец пропуска. Вершины графа соответствуют столбцам. Ребро из занятого столбца в другой стоит разницу между прежней и новой полезностью его владельца. Вспомогательная вершина замыкает пути, меняющие набор занятых столбцов. Принудительная смена назначения требует цикла через другое первое ребро. Стоимость ребра плюс кратчайший обратный путь даёт искомую потерю. Отрицательный цикл противоречил бы оптимальности исходного назначения.++Верификация выполняет одну сортировку за O(n log n) и линейный проход. Точное покрытие двумя эталонами хранит квадратичную матрицу оценок. Вычисление всех потерь альтернативных назначений использует кубическое по числу столбцов и лиц замыкание кратчайших путей. Эти операции предназначены соответственно для набора ракурсов одного человека и ограниченного списка кандидатов кадра.++Проверки включают прямой перебор эталонов, попарную формулу AUC, независимый численный поиск EER и полный перебор допустимых назначений в малых прямоугольных матрицах. Команда из go/facex: `go test -race -run '^TestMath' ./...`. Нагрузочный тест: `FACEX_GALLERY_SCALE=1 go test -v -run '^TestMathWorkloads$'`. CI также собирает матрицу из 15 удержанных векторов модели и проверяет совместную работу трёх частей. Снимки происходят из фикстуры с одной исходной фотографией на человека.diff --git a/go/facex/association_math.go b/go/facex/association_math.gonew file mode 100644index 0000000..cc3fe40--- /dev/null+++ b/go/facex/association_math.go@@ -0,0 +1,260 @@+package facex++import (+ "errors"+ "math"+ "sort"+)++// Association utilities use integer millionths in [-1000000,1000000].+// ForbiddenAssociation removes an edge. An unmatched face earns zero.+const ForbiddenAssociation = -1000001+const associationInfinity int64 = math.MaxInt64 / 4++// Association maps each input face to a different column or -1.+type Association struct {+ Columns []int+ Utility int64+}++// AssociationAnalysis reports the best assignment for every attainable match+// count, the best optional assignment, and the maximum-cardinality optimum.+type AssociationAnalysis struct {+ ByCount []Association+ Best, MostMatches Association+}++func associationShape(scores [][]int) (int, error) {+ m := 0+ if len(scores) > 0 {+ m = len(scores[0])+ }+ for _, row := range scores {+ if len(row) != m {+ return 0, errors.New("facex: jagged association matrix")+ }+ for _, v := range row {+ if v < ForbiddenAssociation || v > 1000000 {+ return 0, errors.New("facex: invalid association score")+ }+ }+ }+ return m, nil+}++func unmatched(n int) []int {+ out := make([]int, n)+ for i := range out {+ out[i] = -1+ }+ return out+}++// AnalyzeAssociations augments a minimum-cost flow by one unit at a time.+// The residual graph can reassign earlier matches. Each augmentation gives+// the optimum at its new cardinality, including when the next gain is negative.+func AnalyzeAssociations(scores [][]int) (AssociationAnalysis, error) {+ m, e := associationShape(scores)+ if e != nil {+ return AssociationAnalysis{}, e+ }+ n := len(scores)+ cols, owners := unmatched(n), unmatched(m)+ zero := Association{append([]int(nil), cols...), 0}+ out := AssociationAnalysis{ByCount: []Association{zero}, Best: zero, MostMatches: zero}+ for k := 0; k < min(n, m); k++ {+ dRow, dCol := make([]int64, n), make([]int64, m)+ pred := unmatched(m)+ for i, c := range cols {+ if c >= 0 {+ dRow[i] = associationInfinity+ }+ }+ for j := range dCol {+ dCol[j] = associationInfinity+ }+ for pass := 0; pass <= k; pass++ {+ changed := false+ for i, row := range scores {+ if dRow[i] == associationInfinity {+ continue+ }+ for j, v := range row {+ if v == ForbiddenAssociation || cols[i] == j {+ continue+ }+ next := dRow[i] - int64(v)+ if next < dCol[j] {+ dCol[j], pred[j] = next, i+ changed = true+ }+ }+ }+ for j, i := range owners {+ if i >= 0 && dCol[j] != associationInfinity {+ dRow[i] = min(dRow[i], dCol[j]+int64(scores[i][j]))+ }+ }+ if !changed {+ break+ }+ }+ end := -1+ for j, i := range owners {+ if i < 0 && pred[j] >= 0 && (end < 0 || dCol[j] < dCol[end]) {+ end = j+ }+ }+ if end < 0 {+ break+ }+ total := out.MostMatches.Utility - dCol[end]+ for end >= 0 {+ i := pred[end]+ prev := cols[i]+ cols[i], owners[end] = end, i+ end = prev+ }+ match := Association{append([]int(nil), cols...), total}+ out.ByCount = append(out.ByCount, match)+ out.MostMatches = match+ if total > out.Best.Utility {+ out.Best = match+ }+ }+ return out, nil+}++// AssociationRegrets returns the minimum total utility lost when each face is+// forced to receive a different decision from the optional global optimum.+// A zero loss means there is an equally good alternative. A -1 result means+// no alternative exists. The returned optimum fixes the reference tie choice.+func AssociationRegrets(scores [][]int) (Association, []int64, error) {+ a, e := AnalyzeAssociations(scores)+ if e != nil {+ return Association{}, nil, e+ }+ best := a.Best+ n := len(scores)+ if n == 0 {+ return best, nil, nil+ }+ m := len(scores[0])+ hub := m + n+ d := make([][]int64, hub+1)+ used := make([]bool, hub)+ for i := range d {+ d[i] = make([]int64, hub+1)+ for j := range d[i] {+ if i != j {+ d[i][j] = associationInfinity+ }+ }+ }+ old := make([]int, n)+ value := make([]int64, n)+ for i, j := range best.Columns {+ if j < 0 {+ j = m + i+ } else {+ value[i] = int64(scores[i][j])+ }+ old[i] = j+ used[j] = true+ for c, v := range scores[i] {+ if v != ForbiddenAssociation && c != j {+ d[j][c] = value[i] - int64(v)+ }+ }+ if j != m+i {+ d[j][m+i] = value[i]+ }+ }+ // Closing an alternating path through the hub accounts for swaps that+ // both release an occupied column and consume a previously unused one.+ for j, occupied := range used {+ if occupied {+ d[hub][j] = 0+ } else {+ d[j][hub] = 0+ }+ }+ for k := range d {+ for i := range d {+ if d[i][k] == associationInfinity {+ continue+ }+ for j, right := range d[k] {+ if right != associationInfinity {+ d[i][j] = min(d[i][j], d[i][k]+right)+ }+ }+ }+ }+ loss := make([]int64, n)+ for i, j := range old {+ v := associationInfinity+ for c, s := range scores[i] {+ if s != ForbiddenAssociation && c != j && d[c][j] != associationInfinity {+ v = min(v, value[i]-int64(s)+d[c][j])+ }+ }+ if c := m + i; c != j && d[c][j] != associationInfinity {+ v = min(v, value[i]+d[c][j])+ }+ if v == associationInfinity {+ v = -1+ }+ loss[i] = v+ }+ return best, loss, nil+}++// AssociationBottleneck finds the highest weakest edge among all matchings of+// the requested positive cardinality. ok=false means the count is infeasible.+func AssociationBottleneck(scores [][]int, count int) (level int, ok bool, err error) {+ m, e := associationShape(scores)+ if e != nil {+ return 0, false, e+ }+ if count <= 0 {+ return 0, false, errors.New("facex: expected positive match count")+ }+ if count > min(len(scores), m) {+ return 0, false, nil+ }+ feasible := func(level int) bool {+ owner := unmatched(m)+ seen := make([]int, m)+ var augment func(int, int) bool+ augment = func(i, stamp int) bool {+ for j, s := range scores[i] {+ if s < level || seen[j] == stamp {+ continue+ }+ seen[j] = stamp+ if owner[j] < 0 || augment(owner[j], stamp) {+ owner[j] = i+ return true+ }+ }+ return false+ }+ hits := 0+ for i := range scores {+ if augment(i, i+1) {+ hits+++ if hits == count {+ return true+ }+ }+ }+ return false+ }+ // Search the fixed-point utility range. Index zero is the lowest legal score.+ pos := sort.Search(2000001, func(i int) bool { return !feasible(i - 1000000) })+ if pos == 0 {+ return 0, false, nil+ }+ return pos - 1 - 1000000, true, nil+}diff --git a/go/facex/enrollment_math.go b/go/facex/enrollment_math.gonew file mode 100644index 0000000..9352ec7--- /dev/null+++ b/go/facex/enrollment_math.go@@ -0,0 +1,206 @@+package facex++import (+ "errors"+ "math"+ "slices"+ "sort"+)++func unitViews(rows [][]float32) ([][]float64, error) {+ if len(rows) == 0 {+ return nil, errors.New("facex: empty views")+ }+ u := make([][]float64, len(rows))+ for i, row := range rows {+ n, e := vectorNorm(row)+ if e != nil {+ return nil, e+ }+ if n == 0 {+ return nil, errors.New("facex: zero enrollment view")+ }+ u[i] = make([]float64, OutputSize)+ for j, x := range row {+ u[i][j] = float64(x) / n+ }+ }+ return u, nil+}++func directionDot(a, b []float64) float64 {+ var sum float64+ for j, x := range a {+ sum += x * b[j]+ }+ return sum+}++// DirectionFit summarizes a weighted chordal least-squares template and the+// enrolled view minimizing weighted summed cosine distance. A nil template+// denotes cancellation within the numerical tolerance. Angles are radians.+type DirectionFit struct {+ Template []float64+ Medoid int+ WorstLeaveOneOutAngle float64+ LeaveOneOutDefined bool+}++// FitDirections uses strictly positive weights (nil means equal). The template,+// medoid and all leave-one-out comparisons take O(n*d) time.+func FitDirections(rows [][]float32, weights []float64) (DirectionFit, error) {+ u, e := unitViews(rows)+ if e != nil {+ return DirectionFit{}, e+ }+ if weights != nil && len(weights) != len(u) {+ return DirectionFit{}, errors.New("facex: expected one weight per view")+ }+ maxW := 1.+ if weights != nil {+ maxW = 0+ for _, w := range weights {+ if !(w > 0) || math.IsInf(w, 0) {+ return DirectionFit{}, errors.New("facex: invalid view weight")+ }+ maxW = max(maxW, w)+ }+ }+ w := make([]float64, len(u))+ suffix := make([][OutputSize]float64, len(u)+1)+ mass := make([]float64, len(u)+1)+ for i := len(u) - 1; i >= 0; i-- {+ w[i] = 1+ if weights != nil {+ w[i] = weights[i] / maxW+ }+ mass[i] = mass[i+1] + w[i]+ for j, x := range u[i] {+ suffix[i][j] = suffix[i+1][j] + w[i]*x+ }+ }+ sum := suffix[0][:]+ out := DirectionFit{}+ best := math.Inf(-1)+ for i, v := range u {+ s := directionDot(v, sum)+ if s > best {+ best = s+ out.Medoid = i+ }+ }+ length := math.Sqrt(directionDot(sum, sum))+ if length <= 1e-14*mass[0] {+ return out, nil+ }+ out.Template = make([]float64, OutputSize)+ for j, x := range sum {+ out.Template[j] = x / length+ }+ out.LeaveOneOutDefined = true+ var prefix, remaining [OutputSize]float64+ var prefixMass float64+ for i, v := range u {+ for j, x := range v {+ remaining[j] = prefix[j] + suffix[i+1][j]+ prefix[j] += w[i] * x+ }+ n := math.Sqrt(directionDot(remaining[:], remaining[:]))+ if n <= 1e-14*(prefixMass+mass[i+1]) {+ out.LeaveOneOutDefined = false+ } else {+ // atan2 of transverse and axial components remains useful at tiny angles.+ proj := directionDot(remaining[:], out.Template)+ var transverse float64+ for j, x := range remaining {+ delta := x - proj*out.Template[j]+ transverse += delta * delta+ }+ out.WorstLeaveOneOutAngle = max(out.WorstLeaveOneOutAngle, math.Atan2(math.Sqrt(transverse), proj))+ }+ prefixMass += w[i]+ }+ return out, nil+}++// ViewCover maximizes the worst cosine to the nearest selected enrollment view.+type ViewCover struct {+ Indices []int+ MinCosine float64+}++// CoverViews selects one or two distinct exemplars. Ties prefer earlier+// indices. The two-center solver stores O(n*n) scores for offline enrollment.+func CoverViews(rows [][]float32, k int) (ViewCover, error) {+ if (k != 1 && k != 2) || len(rows) < k {+ return ViewCover{}, errors.New("facex: expected one or two exemplars")+ }+ u, e := unitViews(rows)+ if e != nil {+ return ViewCover{}, e+ }+ n := len(u)+ if k == 1 {+ worst := make([]float64, n)+ for i := range worst {+ worst[i] = 1+ for j := 0; j < i; j++ {+ v := max(-1., min(1., directionDot(u[i], u[j])))+ worst[i], worst[j] = min(worst[i], v), min(worst[j], v)+ }+ }+ best := slices.Max(worst)+ return ViewCover{[]int{slices.Index(worst, best)}, best}, nil+ }+ sim := make([][]float64, n)+ levels := []float64{1}+ for i := range u {+ sim[i] = make([]float64, n)+ sim[i][i] = 1+ for j := 0; j < i; j++ {+ v := max(-1., min(1., directionDot(u[i], u[j])))+ sim[i][j], sim[j][i] = v, v+ levels = append(levels, v)+ }+ }+ slices.Sort(levels)+ levels = slices.Compact(levels)+ words := (n + 63) / 64+ covers := make([]uint64, n*words)+ pair := func(level float64) (int, int) {+ clear(covers)+ for i, row := range sim {+ for j, v := range row {+ if v >= level {+ covers[i*words+j/64] |= uint64(1) << uint(j%64)+ }+ }+ }+ last := ^uint64(0)+ if n%64 != 0 {+ last = (uint64(1) << uint(n%64)) - 1+ }+ for i := 0; i < n; i++ {+ for j := i + 1; j < n; j++ {+ ok := true+ for t := 0; t < words; t++ {+ mask := ^uint64(0)+ if t == words-1 {+ mask = last+ }+ if covers[i*words+t]|covers[j*words+t] != mask {+ ok = false+ break+ }+ }+ if ok {+ return i, j+ }+ }+ }+ return -1, -1+ }+ pos := sort.Search(len(levels), func(i int) bool { a, _ := pair(levels[i]); return a < 0 }) - 1+ a, b := pair(levels[pos])+ return ViewCover{[]int{a, b}, levels[pos]}, nil+}diff --git a/go/facex/math_solutions_test.go b/go/facex/math_solutions_test.gonew file mode 100644index 0000000..bfdc2c8--- /dev/null+++ b/go/facex/math_solutions_test.go@@ -0,0 +1,476 @@+package facex++import (+ "encoding/binary"+ "math"+ "math/rand"+ "os"+ "path/filepath"+ "slices"+ "testing"+ "time"+)++func closeMath(t *testing.T, got, want float64) {+ t.Helper()+ if math.IsNaN(got) || math.Abs(got-want) > 1e-10 {+ t.Fatalf("got %.16g want %.16g", got, want)+ }+}++func TestMathEnrollment(t *testing.T) {+ r := rand.New(rand.NewSource(2069))+ for trial := 0; trial < 50; trial++ {+ n := 2 + r.Intn(11)+ if trial == 0 {+ n = 65+ }+ rows := make([][]float32, n)+ weights := make([]float64, n)+ for i := range rows {+ rows[i] = make([]float32, OutputSize)+ for j := 0; j < 9; j++ {+ rows[i][j] = float32(r.NormFloat64())+ }+ weights[i] = .1 + r.Float64()+ }+ u, _ := unitViews(rows)+ fit, e := FitDirections(rows, weights)+ if e != nil || !fit.LeaveOneOutDefined {+ t.Fatal(fit, e)+ }+ sum := make([]float64, OutputSize)+ for i, v := range u {+ for j, x := range v {+ sum[j] += weights[i] * x+ }+ }+ length := math.Sqrt(directionDot(sum, sum))+ for j, x := range sum {+ closeMath(t, fit.Template[j], x/length)+ }+ medoid := 0+ medCost := math.Inf(1)+ angle := 0.+ for i, v := range u {+ cost := 0.+ without := make([]float64, OutputSize)+ for k, other := range u {+ cost += weights[k] * (1 - directionDot(v, other))+ if k != i {+ for j, x := range other {+ without[j] += weights[k] * x+ }+ }+ }+ if cost < medCost {+ medCost, medoid = cost, i+ }+ c := directionDot(fit.Template, without) / math.Sqrt(directionDot(without, without))+ angle = max(angle, math.Acos(max(-1., min(1., c))))+ }+ if fit.Medoid != medoid {+ t.Fatal(fit.Medoid, medoid)+ }+ closeMath(t, fit.WorstLeaveOneOutAngle, angle)+ for k := 1; k <= 2; k++ {+ got, e := CoverViews(rows, k)+ if e != nil {+ t.Fatal(e)+ }+ best := math.Inf(-1)+ var want []int+ dist := make([][]float64, n)+ for i := range u {+ dist[i] = make([]float64, n)+ for j := range u {+ dist[i][j] = directionDot(u[i], u[j])+ if i == j {+ dist[i][j] = 1+ }+ }+ }+ for i := range u {+ for j := i; j < n; j++ {+ if (k == 1) != (i == j) {+ continue+ }+ worst := 1.+ for a := range u {+ worst = min(worst, max(dist[i][a], dist[j][a]))+ }+ if worst > best {+ best = worst+ want = []int{i}+ if k == 2 {+ want = append(want, j)+ }+ }+ }+ }+ closeMath(t, got.MinCosine, best)+ if !slices.Equal(got.Indices, want) {+ t.Fatalf("cover got %v want %v", got, want)+ }+ }+ }+ a := basis(0)+ b := basis(0)+ b[0] = -1+ fit, e := FitDirections([][]float32{a, b}, nil)+ if e != nil || fit.Template != nil || fit.LeaveOneOutDefined {+ t.Fatal(fit, e)+ }+ fit, e = FitDirections([][]float32{a, b, b}, nil)+ if e != nil || fit.LeaveOneOutDefined {+ t.Fatal(fit, e)+ }+ if _, e = FitDirections([][]float32{a}, []float64{math.NaN()}); e == nil {+ t.Fatal("bad weight")+ }+}++func TestMathVerification(t *testing.T) {+ tied := []VerificationTrial{{1, true}, {1, false}}+ v, e := EvaluateVerification(tied, .2, 1, 1, 0)+ if e != nil {+ t.Fatal(e)+ }+ closeMath(t, v.AUC, .5)+ closeMath(t, v.EER, .5)+ closeMath(t, v.PartialAUC, .02)+ for i, high := range []bool{true, false} {+ v, e := EvaluateVerification([]VerificationTrial{{1, high}, {0, !high}}, .3, 1, 1, 0)+ if e != nil {+ t.Fatal(e)+ }+ closeMath(t, v.AUC, float64(1-i))+ closeMath(t, v.EER, float64(i))+ closeMath(t, v.PartialAUC, .3*float64(1-i))+ }+ r := rand.New(rand.NewSource(271))+ for trial := 0; trial < 300; trial++ {+ rows := append([]VerificationTrial(nil), tied...)+ for i := 0; i < 23; i++ {+ rows = append(rows, VerificationTrial{float64(r.Intn(7)), r.Intn(2) == 0})+ }+ limit := r.Intn(5)+ cost := .3 + r.Float64()+ far := .03 + .95*r.Float64()+ got, e := EvaluateVerification(rows, far, 1, cost, limit)+ if e != nil {+ t.Fatal(e)+ }+ var pos, neg []float64+ for _, x := range rows {+ if x.Genuine {+ pos = append(pos, x.Score)+ } else {+ neg = append(neg, x.Score)+ }+ }+ area, partial := 0., 0.+ for _, s := range neg {+ above, ties, ng, eq := 0, 0, 0, 0+ for _, q := range pos {+ if q > s {+ above+++ }+ if q == s {+ ties+++ }+ }+ for _, q := range neg {+ if q > s {+ ng+++ }+ if q == s {+ eq+++ }+ }+ cut := max(0., min(1., (far*float64(len(neg))-float64(ng))/float64(eq)))+ area += float64(above) + float64(ties)*.5+ partial += cut*float64(above) + .5*cut*cut*float64(ties)+ }+ closeMath(t, got.AUC, area/float64(len(pos)*len(neg)))+ closeMath(t, got.PartialAUC, partial/float64(len(pos)*len(neg)))+ minCost, bestTA := 1., 0+ for _, cut := range rows {+ tp, fp := 0, 0+ for _, x := range rows {+ if x.Score >= cut.Score {+ if x.Genuine {+ tp+++ } else {+ fp+++ }+ }+ }+ minCost = min(minCost, 1-float64(tp)/float64(len(pos))+cost*float64(fp)/float64(len(neg)))+ if fp <= limit {+ bestTA = max(bestTA, tp)+ }+ }+ // Solve FAR = FRR by bisecting the common rate. At the candidate+ // FAR, allocate the available impostor mass to descending score ties.+ lo, hi := 0., 1.+ for it := 0; it < 55; it++ {+ target := (lo + hi) / 2+ tpr := 0.+ for _, sp := range pos {+ higher, tied := 0, 0+ for _, sn := range neg {+ if sn > sp {+ higher+++ }+ if sn == sp {+ tied+++ }+ }+ available := target*float64(len(neg)) - float64(higher)+ if tied == 0 {+ if available >= 0 {+ tpr+++ }+ } else {+ tpr += min(1., max(0., available/float64(tied)))+ }+ }+ if 1-tpr/float64(len(pos)) > target {+ lo = target+ } else {+ hi = target+ }+ }+ closeMath(t, got.EER, (lo+hi)/2)+ closeMath(t, got.MinCost, minCost)+ if got.BudgetPoint.TrueAccept != bestTA || got.BudgetPoint.FalseAccept > limit {+ t.Fatal(got)+ }+ }+}++func TestMathAssociationExhaustive(t *testing.T) {+ r := rand.New(rand.NewSource(639))+ for trial := 0; trial < 600; trial++ {+ n, m := 1+r.Intn(5), r.Intn(6)+ scores := make([][]int, n)+ for i := range scores {+ scores[i] = make([]int, m)+ for j := range scores[i] {+ v := r.Intn(8) - 3+ if v == 4 {+ v = ForbiddenAssociation+ }+ scores[i][j] = v+ }+ }+ got, e := AnalyzeAssociations(scores)+ if e != nil {+ t.Fatal(e)+ }+ base, loss, e := AssociationRegrets(scores)+ if e != nil {+ t.Fatal(e)+ }+ if !slices.Equal(base.Columns, got.Best.Columns) {+ t.Fatal("unstable optimum")+ }+ by, weak := make([]int64, min(n, m)+1), make([]int, min(n, m)+1)+ for k := range by {+ by[k] = math.MinInt64+ weak[k] = ForbiddenAssociation+ }+ alt := make([]int64, n)+ for i := range alt {+ alt[i] = math.MinInt64+ }+ assign := unmatched(n)+ var visit func(int, int, int, int, int64)+ visit = func(i, used, k, bottleneck int, sum int64) {+ if i == n {+ by[k] = max(by[k], sum)+ weak[k] = max(weak[k], bottleneck)+ for row, x := range assign {+ if x != base.Columns[row] {+ alt[row] = max(alt[row], sum)+ }+ }+ return+ }+ assign[i] = -1+ visit(i+1, used, k, bottleneck, sum)+ for j, v := range scores[i] {+ if v != ForbiddenAssociation && used&(1<<j) == 0 {+ assign[i] = j+ visit(i+1, used|(1<<j), k+1, min(bottleneck, v), sum+int64(v))+ }+ }+ }+ visit(0, 0, 0, 1000000, 0)+ if base.Utility != slices.Max(by) {+ t.Fatalf("trial %d best %v scores %v", trial, base, scores)+ }+ for k, v := range by {+ if k < len(got.ByCount) {+ item := got.ByCount[k]+ seen := 0+ count := 0+ var sum int64+ for i, j := range item.Columns {+ if j < 0 {+ continue+ }+ if seen&(1<<j) != 0 || scores[i][j] == ForbiddenAssociation {+ t.Fatal(item)+ }+ seen |= 1 << j+ count+++ sum += int64(scores[i][j])+ }+ if item.Utility != v || sum != v || count != k {+ t.Fatal("frontier", trial, k, item, v)+ }+ } else if v != math.MinInt64 {+ t.Fatal("missing matching", k)+ }+ if k > 0 {+ b, ok, e := AssociationBottleneck(scores, k)+ if e != nil || ok != (v != math.MinInt64) || ok && b != weak[k] {+ t.Fatal("bottleneck", k, b, weak[k], e)+ }+ }+ }+ if got.MostMatches.Utility != by[len(got.ByCount)-1] {+ t.Fatal("cardinality")+ }+ for i, v := range alt {+ want := int64(-1)+ if v != math.MinInt64 {+ want = base.Utility - v+ }+ if loss[i] != want {+ t.Fatal("regret", trial, i, loss[i], want, scores, base)+ }+ }+ }+}++func TestMathWorkloads(t *testing.T) {+ if os.Getenv("FACEX_GALLERY_SCALE") != "1" {+ t.Skip("requires scale run")+ }+ r := rand.New(rand.NewSource(15))+ rows := make([][]float32, 128)+ for i := range rows {+ rows[i] = make([]float32, OutputSize)+ for j := range rows[i] {+ rows[i][j] = float32(r.NormFloat64())+ }+ }+ start := time.Now()+ if _, e := CoverViews(rows, 2); e != nil {+ t.Fatal(e)+ }+ t.Log("exact two exemplars, 128 views", time.Since(start))+ trials := make([]VerificationTrial, 1000000)+ for i := range trials {+ trials[i] = VerificationTrial{float64(r.Intn(10000)), i%2 == 0}+ }+ start = time.Now()+ if _, e := EvaluateVerification(trials, .001, 1, 1, 50); e != nil {+ t.Fatal(e)+ }+ t.Log("verification, 1000000 pairs", time.Since(start))+ s := make([][]int, 32)+ for i := range s {+ s[i] = make([]int, 48)+ for j := range s[i] {+ s[i][j] = r.Intn(2000001) - 1000000+ }+ }+ start = time.Now()+ if _, _, e := AssociationRegrets(s); e != nil {+ t.Fatal(e)+ }+ t.Log("assignment and all regrets, 32 by 48", time.Since(start))+}++// Assemble a fixed batch of 15 held-out crop embeddings; rows here do not+// represent a camera frame or independent visits.+func TestMathModelFixture(t *testing.T) {+ dir := os.Getenv("FACEX_GALLERY_FIXTURE")+ if dir == "" {+ t.Skip("requires gallery fixture")+ }+ f, e := os.Open(filepath.Join(dir, "rows"))+ if e != nil {+ t.Fatal(e)+ }+ defer f.Close()+ qf, e := os.Open(filepath.Join(dir, "queries"))+ if e != nil {+ t.Fatal(e)+ }+ defer qf.Close()+ const persons = 15+ templates := make([][]float64, persons)+ for i := range templates {+ if _, e = f.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(f, binary.LittleEndian, views[j]); e != nil {+ t.Fatal(e)+ }+ }+ fit, e := FitDirections(views, nil)+ if e != nil || fit.Template == nil {+ t.Fatal(e)+ }+ templates[i] = fit.Template+ one, e := CoverViews(views, 1)+ if e != nil {+ t.Fatal(e)+ }+ two, e := CoverViews(views, 2)+ if e != nil || two.MinCosine < one.MinCosine {+ t.Fatal(i, e)+ }+ }+ matrix := make([][]int, persons)+ var pairs []VerificationTrial+ for i := range matrix {+ q := make([]float32, OutputSize)+ if e = binary.Read(qf, binary.LittleEndian, q); e != nil {+ t.Fatal(e)+ }+ unit, e := unitViews([][]float32{q})+ if e != nil {+ t.Fatal(e)+ }+ matrix[i] = make([]int, persons)+ for j, template := range templates {+ s := max(-1., min(1., directionDot(unit[0], template)))+ pairs = append(pairs, VerificationTrial{s, i == j})+ matrix[i][j] = int(math.Round(s * 1e6))+ }+ }+ match, regrets, e := AssociationRegrets(matrix)+ if e != nil {+ t.Fatal(e)+ }+ right := 0+ for i, j := range match.Columns {+ if i == j {+ right+++ }+ }+ curve, e := EvaluateVerification(pairs, .01, 1, 1, 0)+ if e != nil {+ t.Fatal(e)+ }+ t.Logf("fixture assigned_correct=%d/%d min_regret=%d auc=%.6f eer=%.6f budget0_true=%d/%d", right, persons, slices.Min(regrets), curve.AUC, curve.EER, curve.BudgetPoint.TrueAccept, persons)+}diff --git a/go/facex/verification_math.go b/go/facex/verification_math.gonew file mode 100644index 0000000..2c4d57a--- /dev/null+++ b/go/facex/verification_math.go@@ -0,0 +1,81 @@+package facex++import (+ "errors"+ "math"+ "sort"+)++// VerificationTrial is a scored pair of face embeddings with a genuine/impostor label.+type VerificationTrial struct {+ Score float64+ Genuine bool+}+type OperatingPoint struct {+ Threshold float64+ TrueAccept, FalseAccept int+}+type VerificationCurve struct {+ AUC, PartialAUC, EER float64+ MinCost float64+ CostPoint, BudgetPoint OperatingPoint+}++// EvaluateVerification integrates the tie-grouped ROC with linear interpolation.+// PartialAUC is the raw area over [0, maxFAR]. EER uses randomized interpolation;+// both returned operating points are deterministic inclusive thresholds.+// costMiss and costFalse are prior-weighted costs per class error rate.+func EvaluateVerification(trials []VerificationTrial, maxFAR, costMiss, costFalse float64, falseBudget int) (VerificationCurve, error) {+ if !(maxFAR > 0 && maxFAR <= 1 && costMiss >= 0 && costFalse >= 0) || math.IsInf(costMiss, 0) || math.IsInf(costFalse, 0) || falseBudget < 0 {+ return VerificationCurve{}, errors.New("facex: invalid verification limits")+ }+ rows := append([]VerificationTrial(nil), trials...)+ p := 0+ for _, r := range rows {+ if math.IsNaN(r.Score) || math.IsInf(r.Score, 0) {+ return VerificationCurve{}, errors.New("facex: nonfinite verification score")+ }+ if r.Genuine {+ p+++ }+ }+ n := len(rows) - p+ if p == 0 || n == 0 {+ return VerificationCurve{}, errors.New("facex: both verification classes required")+ }+ sort.Slice(rows, func(i, j int) bool { return rows[i].Score > rows[j].Score })+ point := OperatingPoint{Threshold: math.Inf(1)}+ out := VerificationCurve{CostPoint: point, BudgetPoint: point, MinCost: costMiss}+ for i := 0; i < len(rows); {+ prev := point+ point.Threshold = rows[i].Score+ for i < len(rows) && rows[i].Score == point.Threshold {+ if rows[i].Genuine {+ point.TrueAccept+++ } else {+ point.FalseAccept+++ }+ i+++ }+ x0, y0 := float64(prev.FalseAccept)/float64(n), float64(prev.TrueAccept)/float64(p)+ x1, y1 := float64(point.FalseAccept)/float64(n), float64(point.TrueAccept)/float64(p)+ out.AUC += (x1 - x0) * (y1 + y0) / 2+ if x1 > x0 && x0 < maxFAR {+ dx := min(x1, maxFAR) - x0+ out.PartialAUC += dx * (y0 + .5*(y1-y0)*dx/(x1-x0))+ }+ before, after := 1-y0-x0, 1-y1-x1+ if before > 0 && after <= 0 {+ out.EER = x0 + (x1-x0)*before/(before-after)+ }+ cost := costMiss*(1-y1) + costFalse*x1+ if cost < out.MinCost {+ out.MinCost = cost+ out.CostPoint = point+ }+ if point.FalseAccept <= falseBudget && point.TrueAccept > out.BudgetPoint.TrueAccept {+ out.BudgetPoint = point+ }+ }+ return out, nil+}