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.

Narrow exact gallery searches and bound concurrent batches

Baurzhan Atynovd94001562353
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.yml
new file mode 100644
index 0000000..7db3412
--- /dev/null
+++ b/.github/workflows/go-gallery.yml
@@ -0,0 +1,30 @@
+name: Go gallery checks
+on:
+ push:
+ paths:
+ - 'go/facex/**'
+ - '.github/workflows/go-gallery.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ gallery:
+ runs-on: ubuntu-latest
+ timeout-minutes: 12
+ defaults:
+ run:
+ working-directory: go/facex
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.22.x'
+ cache: false
+ - name: Check concurrent access and decision boundaries
+ run: go test -race -count=1 ./...
+ - name: Compare 65535 rows against exhaustive search
+ env:
+ FACEX_GALLERY_SCALE: '1'
+ run: go test -v -run '^TestIdentityGalleryScale$' -count=1 ./...
diff --git a/go/facex/identity.go b/go/facex/identity.go
index f93fac5..e442e03 100644
--- a/go/facex/identity.go
+++ b/go/facex/identity.go
@@ -1,6 +1,7 @@
package facex
import (
+ "context"
"errors"
"fmt"
"math"
@@ -28,6 +29,7 @@ type identityGroup struct {
type identityCap struct {
row int
cosRadius, sinRadius float64
+ members []int
}
func vectorNorm(row []float32) (float64, error) {
@@ -87,6 +89,7 @@ func (p *identityGroup) buildCaps() {
for i, label := range owner {
c := &p.caps[label]
c.cosRadius = min(c.cosRadius, nearest[i])
+ c.members = append(c.members, i)
}
for i := range p.caps {
c := &p.caps[i]
@@ -139,41 +142,42 @@ func NewIdentityGallery(embeddings [][]float32, ids []int64) (*IdentityGallery,
return g, nil
}
-func (p *identityGroup) bounds(query []float32, norm float64) (float64, float64) {
- low, high := -2., -2.
- for _, c := range p.caps {
- dot := p.cosine(c.row, query, norm)
- low = max(low, dot-cosinePad)
- d := min(1., dot+cosinePad)
- upper := 1.
- if d < c.cosRadius {
- upper = d*c.cosRadius + math.Sqrt((1-d)*(1+d))*c.sinRadius
- }
- high = max(high, upper+cosinePad)
+func (p *identityGroup) capBounds(c *identityCap, query []float32, norm float64) (float64, float64) {
+ dot := p.cosine(c.row, query, norm)
+ d := min(1., dot+cosinePad)
+ upper := 1.
+ if d < c.cosRadius {
+ upper = d*c.cosRadius + math.Sqrt((1-d)*(1+d))*c.sinRadius
}
- return low, high
+ return dot-cosinePad, upper+cosinePad
}
-func (g *IdentityGallery) check(query []float32, score, margin float64) (float64, error) {
+func (g *IdentityGallery) validate(score, margin float64) error {
if g == nil || len(g.people) == 0 {
- return 0, errors.New("facex: empty identity gallery")
+ return errors.New("facex: empty identity gallery")
}
if !(score >= -1 && score <= 1 && margin >= 0 && margin <= 2) {
- return 0, errors.New("facex: invalid cosine or margin threshold")
+ return errors.New("facex: invalid cosine or margin threshold")
}
- return vectorNorm(query)
+ return nil
}
-func (g *IdentityGallery) screen(query []float32, norm, score, margin float64) (int64, bool) {
+func (g *IdentityGallery) screen(ctx context.Context, query []float32, norm, score, margin float64) (int64, bool, float64) {
if norm == 0 || (len(g.people) == 1 && margin > 0) {
- return rejectedID, true
+ return rejectedID, true, 0
}
- // Track the two largest upper bounds to exclude the winning identity
- // from its own margin comparison without allocating per-query buffers.
bestLower, first, second := math.Inf(-1), math.Inf(-1), math.Inf(-1)
winner, upperWinner := 0, 0
for i := range g.people {
- lo, hi := g.people[i].bounds(query, norm)
+ if i%64 == 0 && ctx.Err() != nil {
+ return rejectedID, false, 0
+ }
+ p := &g.people[i]
+ lo, hi := math.Inf(-1), math.Inf(-1)
+ for j := range p.caps {
+ lower, upper := p.capBounds(&p.caps[j], query, norm)
+ lo, hi = max(lo, lower), max(hi, upper)
+ }
if lo > bestLower {
bestLower, winner = lo, i
}
@@ -184,47 +188,74 @@ func (g *IdentityGallery) screen(query []float32, norm, score, margin float64) (
}
}
if first < score {
- return rejectedID, true
+ return rejectedID, true, bestLower
}
rival := first
if winner == upperWinner {
rival = second
}
if bestLower >= score && bestLower > rival && bestLower-rival >= margin {
- return g.people[winner].id, true
+ return g.people[winner].id, true, bestLower
}
- return rejectedID, false
+ return rejectedID, false, bestLower
}
// Screen uses enrolled witnesses to bound the decision. A resolved ID of -1
// means rejection. With resolved=false, Identify can complete the exact lookup.
func (g *IdentityGallery) Screen(query []float32, minScore, minMargin float64) (id int64, resolved bool, err error) {
- norm, err := g.check(query, minScore, minMargin)
+ if err = g.validate(minScore, minMargin); err != nil {
+ return rejectedID, false, err
+ }
+ norm, err := vectorNorm(query)
if err != nil {
return rejectedID, false, err
}
- id, resolved = g.screen(query, norm, minScore, minMargin)
+ id, resolved, _ = g.screen(context.Background(), query, norm, minScore, minMargin)
return id, resolved, nil
}
-// Identify returns the best person's ID or -1. A person's score is the maximum
-// float64 cosine over their views. Both thresholds are inclusive, but equal
-// best scores across people always reject. One person requires a zero margin.
+// Identify returns the best person's ID or -1. Both thresholds are inclusive.
+// A tied best score across different people always rejects.
func (g *IdentityGallery) Identify(query []float32, minScore, minMargin float64) (int64, error) {
- norm, err := g.check(query, minScore, minMargin)
+ if err := g.validate(minScore, minMargin); err != nil {
+ return rejectedID, err
+ }
+ norm, err := vectorNorm(query)
if err != nil {
return rejectedID, err
}
- if id, resolved := g.screen(query, norm, minScore, minMargin); resolved {
- return id, nil
+ return g.identify(context.Background(), query, norm, minScore, minMargin), nil
+}
+
+func (g *IdentityGallery) identify(ctx context.Context, query []float32, norm, minScore, minMargin float64) int64 {
+ id, resolved, lower := g.screen(ctx, query, norm, minScore, minMargin)
+ if resolved {
+ return id
}
best, second := math.Inf(-1), math.Inf(-1)
winner := rejectedID
for i := range g.people {
+ if ctx.Err() != nil {
+ return rejectedID
+ }
p := &g.people[i]
value := math.Inf(-1)
- for j := range p.norms {
- value = max(value, p.cosine(j, query, norm))
+ // Every acceptable winner reaches minScore and at least the best
+ // witness score. A cap below this floor minus the required margin
+ // cannot change any accepted decision, even as a runner-up.
+ floor := max(minScore, max(best, lower)) - minMargin - cosinePad
+ for j := range p.caps {
+ c := &p.caps[j]
+ _, upper := p.capBounds(c, query, norm)
+ if upper < floor || upper < value {
+ continue
+ }
+ for n, row := range c.members {
+ if n%256 == 0 && ctx.Err() != nil {
+ return rejectedID
+ }
+ value = max(value, p.cosine(row, query, norm))
+ }
}
if value > best {
best, second, winner = value, best, p.id
@@ -233,7 +264,7 @@ func (g *IdentityGallery) Identify(query []float32, minScore, minMargin float64)
}
}
if best >= minScore && best > second && best-second >= minMargin {
- return winner, nil
+ return winner
}
- return rejectedID, nil
+ return rejectedID
}
diff --git a/go/facex/identity_batch.go b/go/facex/identity_batch.go
new file mode 100644
index 0000000..396b753
--- /dev/null
+++ b/go/facex/identity_batch.go
@@ -0,0 +1,59 @@
+package facex
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "runtime"
+ "sync"
+ "sync/atomic"
+)
+
+// IdentifyBatch identifies ready embeddings in input order using at most workers
+// goroutines and GOMAXPROCS CPUs. Cancellation or invalid input returns no IDs.
+// Callers must keep queries unchanged until the call returns.
+func (g *IdentityGallery) IdentifyBatch(ctx context.Context, queries [][]float32, minScore, minMargin float64, workers int) ([]int64, error) {
+ if ctx == nil || workers < 1 {
+ return nil, errors.New("facex: expected a context and a positive worker limit")
+ }
+ if err := g.validate(minScore, minMargin); err != nil {
+ return nil, err
+ }
+ norms := make([]float64, len(queries))
+ for i, q := range queries {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ norm, err := vectorNorm(q)
+ if err != nil {
+ return nil, fmt.Errorf("query %d: %w", i, err)
+ }
+ norms[i] = norm
+ }
+ ids := make([]int64, len(queries))
+ var next atomic.Int64
+ work := func() {
+ for ctx.Err() == nil {
+ i := int(next.Add(1)-1)
+ if i >= len(queries) {
+ break
+ }
+ ids[i] = g.identify(ctx, queries[i], norms[i], minScore, minMargin)
+ }
+ }
+ count := min(workers, min(len(queries), runtime.GOMAXPROCS(0)))
+ var wg sync.WaitGroup
+ for i := 1; i < count; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ work()
+ }()
+ }
+ work()
+ wg.Wait()
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
diff --git a/go/facex/identity_batch_test.go b/go/facex/identity_batch_test.go
new file mode 100644
index 0000000..acdec05
--- /dev/null
+++ b/go/facex/identity_batch_test.go
@@ -0,0 +1,160 @@
+package facex
+
+import (
+ "context"
+ "errors"
+ "math"
+ "math/rand"
+ "os"
+ "sort"
+ "testing"
+ "time"
+)
+
+func TestIdentifyBatchContract(t *testing.T) {
+ rows := [][]float32{basis(0), basis(1), basis(2), basis(0)}
+ ids := []int64{100, 200, 300, 100}
+ g, err := NewIdentityGallery(rows, ids)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := [][]float32{rows[2], rows[0], rows[1], make([]float32, OutputSize)}
+ for _, n := range []int{1, 2, 1024} {
+ got, err := g.IdentifyBatch(context.Background(), q, 1, 1, n)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i, want := range []int64{300, 100, 200, -1} {
+ if got[i] != want {
+ t.Fatalf("query %d got %d want %d", i, got[i], want)
+ }
+ }
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ got, err := g.IdentifyBatch(ctx, q, .7, .05, 2)
+ if got != nil || !errors.Is(err, context.Canceled) {
+ t.Fatal(got, err)
+ }
+ if got, err = g.IdentifyBatch(context.Background(), [][]float32{q[0], {1}}, .7, .05, 2); err == nil || got != nil {
+ t.Fatal("expected atomic validation failure")
+ }
+ if got, err = g.IdentifyBatch(context.Background(), nil, .7, .05, 2); err != nil || len(got) != 0 {
+ t.Fatal(got, err)
+ }
+}
+
+// fullFallback mirrors the previous refinement using cached row norms.
+func fullFallback(g *IdentityGallery, q []float32, score, margin float64) int64 {
+ norm, _ := vectorNorm(q)
+ id, resolved, _ := g.screen(context.Background(), q, norm, score, margin)
+ if resolved {
+ return id
+ }
+ best, second := math.Inf(-1), math.Inf(-1)
+ for i := range g.people {
+ p := &g.people[i]
+ value := math.Inf(-1)
+ for j := range p.norms {
+ value = max(value, p.cosine(j, q, norm))
+ }
+ if value > best {
+ best, second, id = value, best, p.id
+ } else {
+ second = max(second, value)
+ }
+ }
+ if best >= score && best > second && best-second >= margin {
+ return id
+ }
+ return rejectedID
+}
+
+func TestIdentityGalleryScale(t *testing.T) {
+ if os.Getenv("FACEX_GALLERY_SCALE") != "1" {
+ t.Skip("set FACEX_GALLERY_SCALE=1 to run the large gallery")
+ }
+ const people, per = 15, 4369
+ rng := rand.New(rand.NewSource(2069))
+ rows := make([][]float32, people*per)
+ ids := make([]int64, len(rows))
+ queries := make([][]float32, people*3)
+ for i := range rows {
+ person, view := i/per, i%8
+ row := make([]float32, OutputSize)
+ for j := range row {
+ row[j] = float32(.004 * rng.NormFloat64())
+ }
+ row[person] += 1
+ row[people+person*8+view] += .14
+ rows[i], ids[i] = row, int64(person)
+ }
+ for i := 0; i < people; i++ {
+ queries[i] = basis(i)
+ queries[i+people] = basis(i)
+ queries[i+people][(i+1)%people] = 1
+ queries[i+2*people] = basis(200+i)
+ }
+ g, err := NewIdentityGallery(rows, ids)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ want := make([]int64, len(queries))
+ for i, q := range queries {
+ want[i] = referenceID(rows, ids, q, .65, .05)
+ }
+ rows, ids = nil, nil
+ var timings [2][]time.Duration
+ fallback := 0
+ for pass := 0; pass < 4; pass++ {
+ for i, q := range queries {
+ _, resolved, err := g.Screen(q, .65, .05)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !resolved && pass == 0 {
+ fallback++
+ }
+ for k := 0; k < 2; k++ {
+ var result int64
+ method := (pass+i+k)%2
+ start := time.Now()
+ if method == 0 {
+ result = fullFallback(g, q, .65, .05)
+ } else {
+ result, err = g.Identify(q, .65, .05)
+ }
+ elapsed := time.Since(start)
+ if err != nil || result != want[i] {
+ t.Fatalf("method %d query %d got %d want %d: %v", method, i, result, want[i], err)
+ }
+ if !resolved && pass > 0 {
+ timings[method] = append(timings[method], elapsed)
+ }
+ }
+ }
+ }
+ if fallback == 0 {
+ t.Fatal("workload did not exercise fallback")
+ }
+ for method, samples := range timings {
+ sort.Slice(samples, func(i, j int) bool { return samples[i] < samples[j] })
+ t.Logf("fallback method=%d samples=%d p50=%v p95=%v", method, len(samples), samples[(len(samples)-1)/2], samples[(95*len(samples)+99)/100-1])
+ }
+ for _, n := range []int{1, 4} {
+ start := time.Now()
+ result, err := g.IdentifyBatch(ctx, queries, .65, .05, n)
+ if err != nil {
+ t.Fatal(err)
+ }
+ elapsed := time.Since(start)
+ for i, id := range result {
+ if id != want[i] {
+ t.Fatalf("batch %d query %d got %d want %d", n, i, id, want[i])
+ }
+ }
+ t.Logf("batch workers=%d queries=%d wall=%v", n, len(result), elapsed)
+ }
+ t.Logf("enrollment=%d distinct_queries=%d fallback_queries=%d", people*per, len(queries), fallback)
+}