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.

Fit exact identification thresholds under separate error budgets

Baurzhan Atynov50ccea26b6a3
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.yml
index 3b560e3..f940822 100644
--- a/.github/workflows/go-gallery.yml
+++ b/.github/workflows/go-gallery.yml
@@ -28,6 +28,10 @@ jobs:
env:
FACEX_GALLERY_SCALE: '1'
run: go test -v -run '^TestIdentityGalleryScale$' -count=1 ./...
+ - name: Verify threshold calibration on one million labeled scores
+ env:
+ FACEX_GALLERY_SCALE: '1'
+ run: go test -v -run '^TestCalibrationMillion$' -count=1 ./...
- uses: actions/setup-python@v5
with:
python-version: '3.12'
diff --git a/docs/research/go_threshold_calibration.md b/docs/research/go_threshold_calibration.md
new file mode 100644
index 0000000..12823ee
--- /dev/null
+++ b/docs/research/go_threshold_calibration.md
@@ -0,0 +1,30 @@
+# Fit two identification thresholds with separate error budgets
+
+For a fixed Go identity gallery, the score of a person is the largest cosine similarity over their enrollment photos. The margin is the best person's score minus the best other person's score. ScoreProbes calculates both exactly. It also handles ties, empty galleries, single-person galleries and zero queries according to Identify.
+
+```go
+snapshot, revision := live.Snapshot()
+probes, err := snapshot.ScoreProbes(calibrationQueries, expectedIDs)
+if err != nil {
+ return err
+}
+fit, err := facex.FitThresholds(probes, maxUnknownAccepted, maxKnownWrong)
+if err != nil {
+ return err
+}
+ids, err := snapshot.IdentifyBatch(ctx, heldOutQueries, fit.MinScore, fit.MinMargin, workers)
+```
+
+Use a fixed snapshot and checkpoint for scoring, fitting and independent evaluation. Record the revision with the thresholds. An ID absent from enrollment is counted as unknown. The two budgets count accepted unknown queries and accepted known queries assigned to another person. Use a representative mix of both kinds, keep visits independent across calibration and evaluation, and report both error rates and denominators on held-out visits before deploying. A zero calibration count alone cannot establish a deployment error rate.
+
+## Why the sweep is exact
+
+An accepted query must have a unique candidate, score at least the score cutoff, and margin at least the margin cutoff. As the cutoffs vary, acceptance changes only at observed scores and margins. The maximum legal cutoffs (1 and 2) cover the empty-selection case when attainable. A false match at both maxima can make an error budget infeasible.
+
+Sweep distinct scores in descending order, inserting all tied scores together. Coordinate-compress the distinct margins in descending order and maintain three prefix counts with a Fenwick tree. At a fixed score, relaxing the margin extends one prefix; each count is monotone. Binary lifting finds the longest prefix satisfying both budgets and hence the maximum attainable number of correct matches. Among prefixes with that many correct matches, the shortest incurs the fewest errors and has the highest margin cutoff. Compare these choices across scores by correct matches, total errors, then stricter score and margin. This enumerates all distinct outcomes needed for the optimum including inclusive threshold boundaries.
+
+For n labeled probes, fitting takes O(n log n) time and O(n) extra space. Generating the exact top-two scores from raw embeddings is a separate offline operation. Reuse the scored probes to explore different budgets without repeating gallery lookup.
+
+## Reproduction
+
+From go/facex run `go test -race ./...` for exhaustive small-set checks and deployment parity, and `FACEX_GALLERY_SCALE=1 go test -v -run '^TestCalibrationMillion$' -count=1` for the seeded million-score benchmark. The benchmark times fitting on generated scores, replays both error budgets and compares with the best score-only cutoff on the same calibration records.
diff --git a/go/facex/calibration.go b/go/facex/calibration.go
new file mode 100644
index 0000000..af82e39
--- /dev/null
+++ b/go/facex/calibration.go
@@ -0,0 +1,196 @@
+package facex
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "math/bits"
+ "slices"
+ "sort"
+)
+
+// ScoredProbe describes one labeled query against a fixed enrollment snapshot.
+// ExpectedID is -1 for an unenrolled person. BestID is -1 for a tied best
+// identity, an empty gallery or a query with no direction. For a single
+// enrolled identity Margin is zero, matching IdentityGallery.Identify.
+type ScoredProbe struct {
+ ExpectedID, BestID int64
+ Score, Margin float64
+}
+
+// ScoreProbes computes exact per-person scores once for offline calibration.
+// Labels for people absent from this gallery are recorded as unknown.
+func (g *IdentityGallery) ScoreProbes(queries [][]float32, labels []int64) ([]ScoredProbe, error) {
+ if err := g.validate(0, 0); err != nil {
+ return nil, err
+ }
+ if len(queries) != len(labels) {
+ return nil, errors.New("facex: expected a label per query")
+ }
+ enrolled := make(map[int64]bool, len(g.people))
+ for _, p := range g.people {
+ enrolled[p.id] = true
+ }
+ out := make([]ScoredProbe, len(queries))
+ for i, q := range queries {
+ if labels[i] < -1 {
+ return nil, fmt.Errorf("facex: invalid label at query %d", i)
+ }
+ norm, err := vectorNorm(q)
+ if err != nil {
+ return nil, fmt.Errorf("query %d: %w", i, err)
+ }
+ v := ScoredProbe{ExpectedID: labels[i], BestID: -1}
+ if !enrolled[labels[i]] {
+ v.ExpectedID = -1
+ }
+ best, second := math.Inf(-1), math.Inf(-1)
+ if norm != 0 {
+ for j := range g.people {
+ p := &g.people[j]
+ value := math.Inf(-1)
+ for row := range p.norms {
+ value = max(value, p.cosine(row, q, norm))
+ }
+ if value > best {
+ best, second, v.BestID = value, best, p.id
+ } else {
+ second = max(second, value)
+ }
+ }
+ }
+ if best == second {
+ v.BestID = -1
+ } else {
+ v.Score = best
+ if len(g.people) > 1 {
+ v.Margin = best - second
+ }
+ }
+ out[i] = v
+ }
+ return out, nil
+}
+
+// CalibrationCounts counts accepted probes, distinguishing both error types.
+type CalibrationCounts struct {
+ Correct, UnknownAccepted, KnownWrong int
+}
+
+func (a CalibrationCounts) plus(b CalibrationCounts) CalibrationCounts {
+ return CalibrationCounts{a.Correct + b.Correct, a.UnknownAccepted + b.UnknownAccepted, a.KnownWrong + b.KnownWrong}
+}
+
+func (v ScoredProbe) count() CalibrationCounts {
+ switch {
+ case v.ExpectedID < 0:
+ return CalibrationCounts{UnknownAccepted: 1}
+ case v.ExpectedID != v.BestID:
+ return CalibrationCounts{KnownWrong: 1}
+ default:
+ return CalibrationCounts{Correct: 1}
+ }
+}
+
+// CalibrationResult contains inclusive thresholds and their calibration counts.
+type CalibrationResult struct {
+ MinScore, MinMargin float64
+ Counts CalibrationCounts
+}
+
+// A Fenwick tree over descending margin values. A prefix represents all rows
+// above an inclusive margin cutoff among the currently active scores.
+type marginCounts []CalibrationCounts
+
+func (t marginCounts) add(i int, v CalibrationCounts) {
+ for ; i < len(t); i += i & -i {
+ t[i] = t[i].plus(v)
+ }
+}
+
+func (t marginCounts) prefix(i int) (sum CalibrationCounts) {
+ for ; i > 0; i -= i & -i {
+ sum = sum.plus(t[i])
+ }
+ return sum
+}
+
+// Longest prefix satisfying three monotone upper limits, in logarithmic time.
+func (t marginCounts) longest(limit CalibrationCounts) (int, CalibrationCounts) {
+ var sum CalibrationCounts
+ i := 0
+ for step := 1 << (bits.Len(uint(len(t)-1)) - 1); step > 0; step >>= 1 {
+ next := i + step
+ if next >= len(t) {
+ continue
+ }
+ v := sum.plus(t[next])
+ if v.Correct <= limit.Correct && v.UnknownAccepted <= limit.UnknownAccepted && v.KnownWrong <= limit.KnownWrong {
+ i, sum = next, v
+ }
+ }
+ return i, sum
+}
+
+// ErrNoFeasibleThresholds means even score 1 and margin 2 exceed a budget.
+var ErrNoFeasibleThresholds = errors.New("facex: no feasible threshold pair")
+
+// FitThresholds maximizes correct identifications under two inclusive error
+// counts on the supplied labeled probes. Ties minimize total errors, then
+// prefer a higher score cutoff followed by a higher margin cutoff.
+// Search takes O(n log n) time and O(n) space after scoring.
+func FitThresholds(probes []ScoredProbe, maxUnknown, maxWrong int) (CalibrationResult, error) {
+ if len(probes) == 0 || maxUnknown < 0 || maxWrong < 0 {
+ return CalibrationResult{}, errors.New("facex: expected labeled probes and nonnegative budgets")
+ }
+ active := make([]ScoredProbe, 0, len(probes))
+ margins := []float64{2}
+ for i, v := range probes {
+ if v.ExpectedID < -1 || v.BestID < -1 || !(v.Score >= -1 && v.Score <= 1 && v.Margin >= 0 && v.Margin <= 2) {
+ return CalibrationResult{}, fmt.Errorf("facex: invalid scored probe %d", i)
+ }
+ if v.BestID >= 0 {
+ active = append(active, v)
+ margins = append(margins, v.Margin)
+ }
+ }
+ sort.Slice(active, func(i, j int) bool { return active[i].Score > active[j].Score })
+ sort.Slice(margins, func(i, j int) bool { return margins[i] > margins[j] })
+ margins = slices.Compact(margins)
+ tree := make(marginCounts, len(margins)+1)
+ best := CalibrationResult{}
+ found := false
+ score := 1.
+ for i := 0; ; {
+ for i < len(active) && active[i].Score == score {
+ v := active[i]
+ rank := sort.Search(len(margins), func(j int) bool { return margins[j] <= v.Margin })
+ tree.add(rank+1, v.count())
+ i++
+ }
+ last, counts := tree.longest(CalibrationCounts{len(probes), maxUnknown, maxWrong})
+ if last > 0 {
+ // The shortest prefix retaining all achievable correct matches
+ // also minimizes errors for this fixed score cutoff.
+ first := 1
+ if counts.Correct > 0 {
+ pos, _ := tree.longest(CalibrationCounts{counts.Correct - 1, maxUnknown, maxWrong})
+ first = pos + 1
+ }
+ counts = tree.prefix(first)
+ if !found || counts.Correct > best.Counts.Correct ||
+ (counts.Correct == best.Counts.Correct && counts.UnknownAccepted+counts.KnownWrong < best.Counts.UnknownAccepted+best.Counts.KnownWrong) {
+ best = CalibrationResult{score, margins[first-1], counts}
+ found = true
+ }
+ }
+ if i == len(active) {
+ break
+ }
+ score = active[i].Score
+ }
+ if !found {
+ return CalibrationResult{}, ErrNoFeasibleThresholds
+ }
+ return best, nil
+}
diff --git a/go/facex/calibration_test.go b/go/facex/calibration_test.go
new file mode 100644
index 0000000..6fc1434
--- /dev/null
+++ b/go/facex/calibration_test.go
@@ -0,0 +1,177 @@
+package facex
+
+import (
+ "errors"
+ "math"
+ "math/rand"
+ "os"
+ "sort"
+ "testing"
+ "time"
+)
+
+func replayThresholds(probes []ScoredProbe, score, margin float64) (c CalibrationCounts) {
+ for _, p := range probes {
+ if p.BestID < 0 || p.Score < score || p.Margin < margin {
+ continue
+ }
+ switch {
+ case p.ExpectedID == -1:
+ c.UnknownAccepted++
+ case p.ExpectedID != p.BestID:
+ c.KnownWrong++
+ default:
+ c.Correct++
+ }
+ }
+ return c
+}
+
+func bruteThresholds(probes []ScoredProbe, unknown, wrong int) (CalibrationResult, bool) {
+ scores, margins := []float64{1, -1}, []float64{2, 0}
+ for _, v := range probes {
+ scores = append(scores, v.Score)
+ margins = append(margins, v.Margin)
+ }
+ var best CalibrationResult
+ found := false
+ for _, s := range scores {
+ for _, m := range margins {
+ c := replayThresholds(probes, s, m)
+ if c.UnknownAccepted > unknown || c.KnownWrong > wrong {
+ continue
+ }
+ loss := c.UnknownAccepted + c.KnownWrong
+ prev := best.Counts.UnknownAccepted + best.Counts.KnownWrong
+ if !found || c.Correct > best.Counts.Correct ||
+ c.Correct == best.Counts.Correct && (loss < prev ||
+ loss == prev && (s > best.MinScore || s == best.MinScore && m > best.MinMargin)) {
+ found, best = true, CalibrationResult{s, m, c}
+ }
+ }
+ }
+ return best, found
+}
+
+func TestThresholdSweepAgainstExhaustive(t *testing.T) {
+ rng := rand.New(rand.NewSource(2069))
+ for trial := 0; trial < 800; trial++ {
+ probes := make([]ScoredProbe, 1+rng.Intn(18))
+ for i := range probes {
+ probes[i] = ScoredProbe{ExpectedID: int64(rng.Intn(4) - 1), BestID: int64(rng.Intn(4) - 1),
+ Score: float64(rng.Intn(9)-4) / 4, Margin: float64(rng.Intn(9)) / 4}
+ }
+ u, w := rng.Intn(4), rng.Intn(4)
+ want, ok := bruteThresholds(probes, u, w)
+ got, err := FitThresholds(probes, u, w)
+ if !ok {
+ if !errors.Is(err, ErrNoFeasibleThresholds) {
+ t.Fatal(trial, err)
+ }
+ } else if err != nil || got != want {
+ t.Fatalf("trial %d got %+v want %+v err %v", trial, got, want, err)
+ }
+ }
+}
+
+func TestThresholdLimits(t *testing.T) {
+ for _, p := range []ScoredProbe{{Score: math.NaN()}, {Margin: math.Inf(1)}, {BestID: -2}} {
+ if _, err := FitThresholds([]ScoredProbe{p}, 0, 0); err == nil {
+ t.Fatal("invalid probe accepted")
+ }
+ }
+ if _, err := FitThresholds([]ScoredProbe{{ExpectedID: -1, BestID: 4, Score: 1, Margin: 2}}, 0, 0); !errors.Is(err, ErrNoFeasibleThresholds) {
+ t.Fatal(err)
+ }
+ if _, err := FitThresholds(nil, 0, 0); err == nil {
+ t.Fatal("empty input accepted")
+ }
+}
+
+func TestCalibrationAgreesWithIdentify(t *testing.T) {
+ a, b, c := basis(0), basis(1), basis(2)
+ rows := [][]float32{a, b, c, a}
+ labels := []int64{91, 28, 35, 91}
+ for _, n := range []int{1, 3, 4} {
+ g, err := NewIdentityGallery(rows[:n], labels[:n])
+ if err != nil {
+ t.Fatal(err)
+ }
+ mid := basis(0)
+ mid[1] = 1
+ queries := [][]float32{a, b, c, mid, make([]float32, OutputSize), basis(3)}
+ truth := []int64{91, 28, 999, 35, -1, 17}
+ probes, err := g.ScoreProbes(queries, truth)
+ if err != nil || probes[2].ExpectedID != -1 {
+ t.Fatal(probes, err)
+ }
+ for _, s := range []float64{-1, 0, .65, 1} {
+ for _, m := range []float64{0, .05, 1, 2} {
+ for i, p := range probes {
+ got, err := g.Identify(queries[i], s, m)
+ want := int64(-1)
+ if p.Score >= s && p.Margin >= m {
+ want = p.BestID
+ }
+ if err != nil || got != want {
+ t.Fatal(n, i, s, m, got, want, err)
+ }
+ }
+ }
+ }
+ }
+}
+
+func TestCalibrationMillion(t *testing.T) {
+ if os.Getenv("FACEX_GALLERY_SCALE") != "1" {
+ t.Skip("requires scale run")
+ }
+ rng := rand.New(rand.NewSource(77))
+ probes := make([]ScoredProbe, 1_000_000)
+ for i := range probes {
+ s, m := rng.Float64(), rng.Float64()
+ p := ScoredProbe{ExpectedID: 1, BestID: 1, Score: .5 + .5*s, Margin: .1 + .8*m}
+ switch i % 5 {
+ case 0:
+ p.ExpectedID, p.Score, p.Margin = -1, .25+.65*s, .65*m
+ case 1:
+ p.BestID, p.Score, p.Margin = 2, .5+.48*s, .35*m
+ }
+ probes[i] = p
+ }
+ start := time.Now()
+ got, err := FitThresholds(probes, 100, 100)
+ elapsed := time.Since(start)
+ if err != nil || got.Counts != replayThresholds(probes, got.MinScore, got.MinMargin) ||
+ got.Counts.UnknownAccepted > 100 || got.Counts.KnownWrong > 100 {
+ t.Fatal(got, err)
+ }
+ // Independent one-dimensional optimization. With margin fixed at zero
+ // the first threshold violating either budget marks the end of the sweep.
+ sort.Slice(probes, func(i, j int) bool { return probes[i].Score > probes[j].Score })
+ var correct, u, w, best int
+ for i := 0; i < len(probes); {
+ score := probes[i].Score
+ for i < len(probes) && probes[i].Score == score {
+ p := probes[i]
+ switch {
+ case p.ExpectedID < 0:
+ u++
+ case p.ExpectedID != p.BestID:
+ w++
+ default:
+ correct++
+ }
+ i++
+ }
+ if u > 100 || w > 100 {
+ break
+ }
+ best = correct
+ }
+ if got.Counts.Correct < best {
+ t.Fatal("two thresholds lost feasible matches")
+ }
+ t.Logf("synthetic probes=%d fit=%v score=%.8f margin=%.8f correct=%d unknown_accepted=%d known_wrong=%d score_only_correct=%d",
+ len(probes), elapsed, got.MinScore, got.MinMargin, got.Counts.Correct, got.Counts.UnknownAccepted, got.Counts.KnownWrong, best)
+}