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
Publish enrollment changes while searches are running
Baurzhan Atynovff566b51e7b6
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.ymlindex 20f74b3..f1704c9 100644--- a/.github/workflows/go-gallery.yml+++ b/.github/workflows/go-gallery.yml@@ -58,7 +58,14 @@ jobs:np.vstack((near_and_boundary, random)).astype("<f4").tofile(output / "queries")PYcd go/facex- go test -v -run '^TestIdentityGalleryScale$' -count=1 ./...+ go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale)+ - name: Verify concurrent engine replies against serial inference+ working-directory: go/facex+ env:+ FACEX_POOL_TEST_EXE: ${{ github.workspace }}/facex-cli+ FACEX_POOL_TEST_WEIGHTS: ${{ runner.temp }}/edgeface_xs_fp32.bin+ run: go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...+ -count=1 ./...- name: Verify concurrent engine replies against serial inferenceworking-directory: go/facexenv:diff --git a/go/facex/identity.go b/go/facex/identity.goindex e442e03..afb3f3c 100644--- a/go/facex/identity.go+++ b/go/facex/identity.go@@ -98,6 +98,27 @@ func (p *identityGroup) buildCaps() {}}+func newIdentityGroup(id int64, count int) identityGroup {+ return identityGroup{+ id: id,+ rows: make([]float32, 0, count*OutputSize),+ norms: make([]float64, 0, count),+ }+}++func (p *identityGroup) addView(row []float32) error {+ norm, err := vectorNorm(row)+ if err != nil {+ return err+ }+ if norm == 0 {+ return errors.New("facex: zero enrollment vector")+ }+ p.rows = append(p.rows, row...)+ p.norms = append(p.norms, norm)+ return nil+}+// NewIdentityGallery copies the enrollment vectors. Repeat an ID for additional// photos of the same person. IDs must be nonnegative and vectors finite and nonzero.func NewIdentityGallery(embeddings [][]float32, ids []int64) (*IdentityGallery, error) {@@ -121,20 +142,12 @@ func NewIdentityGallery(embeddings [][]float32, ids []int64) (*IdentityGallery,counts[i]++}for i, count := range counts {- g.people[i].rows = make([]float32, 0, count*OutputSize)- g.people[i].norms = make([]float64, 0, count)+ g.people[i] = newIdentityGroup(g.people[i].id, count)}for i, row := range embeddings {- norm, err := vectorNorm(row)- if err != nil {+ if err := g.people[index[ids[i]]].addView(row); err != nil {return nil, fmt.Errorf("enrollment row %d: %w", i, err)}- if norm == 0 {- return nil, fmt.Errorf("facex: zero enrollment row %d", i)- }- p := &g.people[index[ids[i]]]- p.rows = append(p.rows, row...)- p.norms = append(p.norms, norm)}for i := range g.people {g.people[i].buildCaps()@@ -153,7 +166,7 @@ func (p *identityGroup) capBounds(c *identityCap, query []float32, norm float64)}func (g *IdentityGallery) validate(score, margin float64) error {- if g == nil || len(g.people) == 0 {+ if g == nil || g.people == nil {return errors.New("facex: empty identity gallery")}if !(score >= -1 && score <= 1 && margin >= 0 && margin <= 2) {@@ -163,7 +176,7 @@ func (g *IdentityGallery) validate(score, margin float64) error {}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) {+ if len(g.people) == 0 || norm == 0 || (len(g.people) == 1 && margin > 0) {return rejectedID, true, 0}bestLower, first, second := math.Inf(-1), math.Inf(-1), math.Inf(-1)diff --git a/go/facex/live_gallery.go b/go/facex/live_gallery.gonew file mode 100644index 0000000..5f58fde--- /dev/null+++ b/go/facex/live_gallery.go@@ -0,0 +1,114 @@+package facex++import (+ "errors"+ "fmt"+ "math"+ "sync"+ "sync/atomic"+)++// ErrGalleryConflict means the enrollment revision changed before publication.+var ErrGalleryConflict = errors.New("facex: enrollment revision conflict")++// EnrollmentChange replaces the complete view list for ID. Set Remove with no+// views to remove the identity. Changes for one ID must occur once per update.+type EnrollmentChange struct {+ ID int64+ Views [][]float32+ Remove bool+}++type enrollmentVersion struct {+ gallery IdentityGallery+ revision uint64+}++// LiveGallery publishes immutable enrollment snapshots. Its zero value is an+// empty gallery at revision zero. Do not copy a LiveGallery after first use.+type LiveGallery struct {+ writers sync.Mutex+ current atomic.Pointer[enrollmentVersion]+}++// Snapshot pins both the enrollment data and its revision with one atomic load.+// Use the same returned gallery for all stages of a request or an entire batch.+// Older snapshots keep their view of enrollment, including subsequently removed+// identities, until callers release them.+func (g *LiveGallery) Snapshot() (IdentityGallery, uint64) {+ if current := g.current.Load(); current != nil {+ return current.gallery, current.revision+ }+ return IdentityGallery{people: []identityGroup{}}, 0+}++// Apply commits all changes together if expected is the current revision.+// On any error it publishes nothing and returns the current revision. Removing+// a missing ID is a no-op. The caller owns the input and may reuse it on return.+func (g *LiveGallery) Apply(expected uint64, changes []EnrollmentChange) (uint64, error) {+ g.writers.Lock()+ defer g.writers.Unlock()++ old, revision := g.Snapshot()+ if expected != revision {+ return revision, ErrGalleryConflict+ }+ if len(changes) == 0 {+ return revision, nil+ }++ byID := make(map[int64]int, len(changes))+ replacements := make([]identityGroup, len(changes))+ for i, edit := range changes {+ if edit.ID < 0 || (edit.Remove && len(edit.Views) > 0) || (!edit.Remove && len(edit.Views) == 0) {+ return revision, fmt.Errorf("facex: invalid enrollment change %d", i)+ }+ if _, duplicate := byID[edit.ID]; duplicate {+ return revision, fmt.Errorf("facex: repeated enrollment ID %d", edit.ID)+ }+ byID[edit.ID] = i+ if edit.Remove {+ continue+ }+ p := newIdentityGroup(edit.ID, len(edit.Views))+ for j, row := range edit.Views {+ if err := p.addView(row); err != nil {+ return revision, fmt.Errorf("identity %d view %d: %w", edit.ID, j, err)+ }+ }+ p.buildCaps()+ replacements[i] = p+ }++ // The directory is private to this version. Unchanged group descriptors+ // point to immutable view, norm and cap arrays shared with older versions.+ next := make([]identityGroup, 0, len(old.people))+ changed := false+ for _, p := range old.people {+ i, edited := byID[p.id]+ if !edited {+ next = append(next, p)+ continue+ }+ changed = true+ if !changes[i].Remove {+ next = append(next, replacements[i])+ }+ delete(byID, p.id)+ }+ for i, edit := range changes {+ if _, added := byID[edit.ID]; added && !edit.Remove {+ next = append(next, replacements[i])+ changed = true+ }+ }+ if !changed {+ return revision, nil+ }+ if revision == math.MaxUint64 {+ return revision, errors.New("facex: enrollment revision exhausted")+ }+ revision+++ g.current.Store(&enrollmentVersion{gallery: IdentityGallery{people: next}, revision: revision})+ return revision, nil+}diff --git a/go/facex/live_gallery_test.go b/go/facex/live_gallery_test.gonew file mode 100644index 0000000..112f972--- /dev/null+++ b/go/facex/live_gallery_test.go@@ -0,0 +1,246 @@+package facex++import (+ "bufio"+ "context"+ "encoding/binary"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "sort"+ "sync"+ "testing"+ "time"+)++func ExampleLiveGallery() {+ var live LiveGallery+ front := make([]float32, OutputSize)+ front[0] = 1 // In the application use the output of FaceX.Embed.+ _, err := live.Apply(0, []EnrollmentChange{{ID: 42, Views: [][]float32{front}}})+ if err != nil {+ panic(err)+ }+ gallery, revision := live.Snapshot()+ id, err := gallery.Identify(front, .85, 0)+ fmt.Println(revision, id, err)+ // Output: 1 42 <nil>+}++func identifyView(t *testing.T, g IdentityGallery, row []float32, want int64) {+ t.Helper()+ got, err := g.Identify(row, .8, 0)+ if err != nil || got != want {+ t.Fatalf("got %d want %d: %v", got, want, err)+ }+}++func TestLiveGalleryTransaction(t *testing.T) {+ var live LiveGallery+ first, revision := live.Snapshot()+ if revision != 0 {+ t.Fatal(revision)+ }+ identifyView(t, first, basis(0), -1)+ a, b := basis(0), basis(1)+ initial := []EnrollmentChange{{ID: 7, Views: [][]float32{a}}, {ID: 8, Views: [][]float32{b}}}+ if rev, err := live.Apply(0, initial); err != nil || rev != 1 {+ t.Fatal(rev, err)+ }+ initial[0].Views[0][0] = 0+ pinned, _ := live.Snapshot()+ identifyView(t, pinned, basis(0), 7)+ for _, invalid := range [][]EnrollmentChange{+ {{ID: 7, Remove: true}, {ID: 9, Views: [][]float32{{1}}}},+ {{ID: 7, Remove: true}, {ID: 7, Views: [][]float32{basis(0)}}},+ {{ID: -1, Remove: true}}, {{ID: 8}}, {{ID: 8, Views: [][]float32{b}, Remove: true}},+ } {+ rev, err := live.Apply(1, invalid)+ if err == nil || rev != 1 {+ t.Fatal(rev, err)+ }+ g, r := live.Snapshot()+ if r != 1 {+ t.Fatal(r)+ }+ identifyView(t, g, basis(0), 7)+ }+ if rev, err := live.Apply(1, []EnrollmentChange{{ID: 90, Remove: true}}); err != nil || rev != 1 {+ t.Fatal(rev, err)+ }+ if _, err := live.Apply(1, []EnrollmentChange{{ID: 7, Remove: true}, {ID: 9, Views: [][]float32{basis(0)}}}); err != nil {+ t.Fatal(err)+ }+ next, rev := live.Snapshot()+ if rev != 2 || &next.people[0].rows[0] != &pinned.people[1].rows[0] {+ t.Fatal("unchanged enrollment was rebuilt")+ }+ identifyView(t, next, basis(0), 9)+ identifyView(t, pinned, basis(0), 7)+ if _, err := live.Apply(rev, []EnrollmentChange{{ID: 8, Remove: true}, {ID: 9, Remove: true}}); err != nil {+ t.Fatal(err)+ }+ empty, _ := live.Snapshot()+ out, err := empty.IdentifyBatch(context.Background(), [][]float32{b}, .8, 0, 1)+ if err != nil || !slices.Equal(out, []int64{-1}) {+ t.Fatal(out, err)+ }+}++func TestLiveConcurrentWriters(t *testing.T) {+ var live LiveGallery+ start := make(chan struct{})+ results := make(chan error, 16)+ for i := 0; i < cap(results); i++ {+ go func(id int64) {+ <-start+ _, err := live.Apply(0, []EnrollmentChange{{ID: id, Views: [][]float32{basis(0)}}})+ results <- err+ }(int64(i))+ }+ close(start)+ wins := 0+ for i := 0; i < cap(results); i++ {+ if err := <-results; err == nil {+ wins+++ } else if !errors.Is(err, ErrGalleryConflict) {+ t.Fatal(err)+ }+ }+ if wins != 1 {+ t.Fatal("unexpected successful writers", wins)+ }+}++func TestLiveConcurrentReaders(t *testing.T) {+ var live LiveGallery+ a, b := basis(0), basis(1)+ apply := func(expected uint64) {+ x, y := a, b+ if expected%2 == 1 {+ x, y = b, a+ }+ _, err := live.Apply(expected, []EnrollmentChange{+ {ID: 1, Views: [][]float32{x}}, {ID: 2, Views: [][]float32{y}},+ })+ if err != nil {+ t.Fatal(err)+ }+ }+ apply(0)+ var readers, pinned sync.WaitGroup+ release := make(chan struct{})+ for i := 0; i < 8; i++ {+ readers.Add(1)+ pinned.Add(1)+ go func() {+ defer readers.Done()+ for n := 0; n < 60; n++ {+ g, rev := live.Snapshot()+ if n == 0 {+ pinned.Done()+ <-release+ }+ want := []int64{1, 2}+ if rev%2 == 0 {+ want = []int64{2, 1}+ }+ got, err := g.IdentifyBatch(context.Background(), [][]float32{a, b}, .9, .05, 2)+ if err != nil || !slices.Equal(got, want) {+ t.Errorf("mixed revision %d: %v want %v: %v", rev, got, want, err)+ return+ }+ }+ }()+ }+ pinned.Wait()+ apply(1)+ close(release)+ for rev := uint64(2); rev < 60; rev++ {+ apply(rev)+ }+ readers.Wait()+}++func TestLiveGalleryScale(t *testing.T) {+ dir := os.Getenv("FACEX_GALLERY_FIXTURE")+ if dir == "" {+ t.Skip("requires the model fixture gallery")+ }+ const people, per = 15, 4369+ rows, ids := make([][]float32, people*per), make([]int64, people*per)+ f, err := os.Open(filepath.Join(dir, "rows"))+ if err != nil {+ t.Fatal(err)+ }+ defer f.Close()+ input := bufio.NewReaderSize(f, 1<<20)+ for i := range rows {+ rows[i] = make([]float32, OutputSize)+ if err := binary.Read(input, binary.LittleEndian, rows[i]); err != nil {+ t.Fatal(err)+ }+ ids[i] = int64(i/per)+ }+ var live LiveGallery+ initial := make([]EnrollmentChange, people)+ for i := range initial {+ initial[i] = EnrollmentChange{ID: int64(i), Views: rows[i*per:(i+1)*per]}+ }+ rev, err := live.Apply(0, initial)+ if err != nil {+ t.Fatal(err)+ }+ var times [2][]time.Duration+ var allocated [2][]uint64+ for trial := 0; trial < 5; trial++ {+ owner := trial+ // Replace one photo, keeping the other 4368 views for this person.+ rows[owner*per] = basis(400+trial)+ change := []EnrollmentChange{{ID: int64(owner), Views: rows[owner*per:(owner+1)*per]}}+ var rebuilt *IdentityGallery+ for k := 0; k < 2; k++ {+ m := (trial+k)%2+ runtime.GC()+ var before, after runtime.MemStats+ runtime.ReadMemStats(&before)+ start := time.Now()+ if m == 0 {+ rebuilt, err = NewIdentityGallery(rows, ids)+ } else {+ rev, err = live.Apply(rev, change)+ }+ elapsed := time.Since(start)+ runtime.ReadMemStats(&after)+ if err != nil {+ t.Fatal(err)+ }+ times[m] = append(times[m], elapsed)+ allocated[m] = append(allocated[m], after.TotalAlloc-before.TotalAlloc)+ }+ current, _ := live.Snapshot()+ samples := [][]float32{rows[owner*per], rows[len(rows)-1], basis(300)}+ for i := 0; i < people; i++ {+ samples = append(samples, rows[i*per+1])+ }+ for _, q := range samples {+ want, err := rebuilt.Identify(q, .85, .05)+ if err != nil {+ t.Fatal(err)+ }+ got, err := current.Identify(q, .85, .05)+ if err != nil || got != want {+ t.Fatalf("trial %d got %d want %d: %v", trial, got, want, err)+ }+ }+ identifyView(t, current, rows[owner*per], int64(owner))+ }+ for m, name := range []string{"rebuild", "live"} {+ sort.Slice(times[m], func(i, j int) bool { return times[m][i] < times[m][j] })+ slices.Sort(allocated[m])+ t.Logf("%s rows=%d trials=5 median=%v median_allocated_bytes=%d", name, len(rows), times[m][2], allocated[m][2])+ }+}