Metadata-Version: 2.5
Name: fujielab-fer
Version: 0.1.0
Summary: Fast facial expression recognition (emotion, valence/arousal, action units, gaze, head pose, face mesh, blendshapes) built on py-feat Detectorv2, with face-behavior features and a causal face tokenizer for spoken dialogue
Project-URL: Homepage, https://github.com/fujielab/fujielab-fer
Project-URL: Repository, https://github.com/fujielab/fujielab-fer
Project-URL: Issues, https://github.com/fujielab/fujielab-fer/issues
Project-URL: Models, https://huggingface.co/collections/fujielab/fujielab-fer-6ad832f4c51632df10cc6be3
Author-email: Shinya Fujie <shinya.fujie@chibatech.ac.jp>
Maintainer-email: Shinya Fujie <shinya.fujie@chibatech.ac.jp>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: action-units,blendshapes,face-mesh,facial-expression-recognition,gaze-estimation,head-pose,py-feat,spoken-dialogue,valence-arousal,voice-activity-projection
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Requires-Python: >=3.11
Requires-Dist: huggingface-hub>=0.25
Requires-Dist: numpy>=1.26
Requires-Dist: onnxruntime-gpu[cuda,cudnn]>=1.20; sys_platform == 'linux'
Requires-Dist: onnxruntime>=1.20; sys_platform != 'linux'
Requires-Dist: opencv-python>=4.9
Requires-Dist: safetensors>=0.4
Requires-Dist: timm>=1.0.11
Requires-Dist: torch>=2.4
Requires-Dist: torchvision>=0.19
Provides-Extra: tensorrt
Requires-Dist: tensorrt-cu13<11,>=10; (sys_platform == 'linux') and extra == 'tensorrt'
Provides-Extra: web
Requires-Dist: fastapi>=0.110; extra == 'web'
Requires-Dist: uvicorn[standard]>=0.29; extra == 'web'
Description-Content-Type: text/markdown

# fujielab-fer

English | [日本語](https://github.com/fujielab/fujielab-fer/blob/main/README_ja.md)

Fast facial expression recognition from Fujie Laboratory (Chiba Institute of Technology), as a library to embed in
larger systems and as live demos. It is built around **py-feat Detectorv2 (multitask v28)**, which ranked at the top
for both emotion and action units in our (internal) facial-expression / AU benchmark.
One forward pass gives

- probabilities of 7 emotions (neutral, happy, sad, surprise, fear, disgust, anger)
- valence and arousal (-1 to 1)
- presence probabilities of 20 action units (1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 14, 15, 17, 20, 23, 24, 25, 26, 28, 43)
- gaze (pitch, yaw) and head pose (pitch, roll, yaw)
- a 478-point face mesh (and the dlib 68 points) and the 52 MediaPipe blendshapes

The outputs match py-feat itself, while the time per face drops from **53-75 ms to a few ms** (see [Speed](#speed)).
We also provide students **distilled** from py-feat into light backbones (same accuracy as the teacher, 4-5 times
faster on the CPU; see [Distilled models](#distilled-models)), and **face-behavior features and a causal tokenizer for
spoken dialogue** (multimodal VAP etc.; see [Face features for spoken dialogue](#face-features-for-spoken-dialogue)).

## Licenses and model availability

- **Code**: Apache License 2.0 (see [LICENSE](https://github.com/fujielab/fujielab-fer/blob/main/LICENSE) and [NOTICE](https://github.com/fujielab/fujielab-fer/blob/main/NOTICE)). `src/fujielab_fer/_pyfeat_v2.py` is
  adapted from py-feat (MIT).
- **Pretrained models are not covered by the Apache License.** They are downloaded at run time and come with their own
  terms. All of them are for **non-commercial research use only**:

| Model | Used for | Terms |
|---|---|---|
| [`py-feat/face_multitask_v2`](https://huggingface.co/py-feat/face_multitask_v2) (`face_multitask_v28.safetensors`) | default expression model | designated by its authors for noncommercial research; see its [LICENSE](https://huggingface.co/py-feat/face_multitask_v2/blob/main/LICENSE) and [py-feat's licensing notes](https://github.com/cosanlab/py-feat/tree/main/LICENSES) |
| InsightFace SCRFD (`buffalo_l/det_10g.onnx`) | face detection | InsightFace pretrained models are for noncommercial research only |
| [`fujielab/fujielab-fer-*`](https://huggingface.co/collections/fujielab/fujielab-fer-6ad832f4c51632df10cc6be3) | distilled students, dialogue tokenizer | non-commercial research only; they inherit the terms of the py-feat teacher, the ConvNeXt-V2 ImageNet weights (CC BY-NC 4.0) and the training corpora (see each model card) |

The py-feat model is pinned to revision `66c65f28` of the HF repo (`FUJIELAB_FER_WEIGHTS` or `weights=` can point to a
local file instead). SCRFD is taken from `~/.insightface/models/buffalo_l/` or, if missing, downloaded from the
InsightFace GitHub release (md5 checked).

## Installation

```bash
pip install fujielab-fer               # library and the OpenCV demo (torch, timm, onnxruntime-gpu on Linux, opencv, ...)
pip install "fujielab-fer[web]"        # + the web UI demo (fastapi, uvicorn)
pip install "fujielab-fer[tensorrt]"   # + face detection with TensorRT fp16 (Linux; building the engine takes 10-20 min the first time)
```

Python 3.11 or later. On Linux the GPU build of onnxruntime is installed (it also runs on the CPU). From a clone of
this repository, `uv sync --extra web` creates `.venv` with everything, and `uv run <command>` runs the commands below.

## Usage

```python
from fujielab_fer import FaceExpressionRecognizer

fer = FaceExpressionRecognizer()              # GPU if available; the weights are fetched on first use (HF, insightface)
faces = fer(frame_bgr)                        # list[FaceResult] (an OpenCV BGR image)
for f in faces:
    f.emotion_label, f.emotion                # "happy", {"neutral": 0.02, "happy": 0.95, ...}
    f.valence, f.arousal
    f.au["AU12"]                              # AU presence probability
    f.gaze, f.head_pose                       # radians (same convention as py-feat's Fex)
    f.mesh, f.landmarks68                     # pixel coordinates in the frame
    f.to_dict()                               # JSON-serializable dict (for sending to other modules)

faces = fer(frame_bgr, boxes=[[x1, y1, x2, y2]])   # use your own face boxes (skips detection)
```

- `FaceExpressionRecognizer(det_size=320)`: a smaller detector input is faster and enough for large faces in front of a camera.
- `detect_interval=3`: run the detector every 3rd frame; in between, track the box from the mesh predicted on the previous frame.
- `box_smoothing=0.5, output_smoothing=0.5`: exponential moving averages of the boxes and outputs (less jitter in live use; the demo default).
- `with_gaze=False, with_blendshapes=False`: skip the gaze and blendshape heads (slightly faster).
- `compile=False`: do not use torch.compile (faster start-up, slower inference).
- `weights="fujielab/fujielab-fer-atto-192"`: use a distilled student (an HF repo id or a local safetensors file; the
  default is py-feat v28). The demos and the benchmark take the same `--weights`, and the environment variable
  `FUJIELAB_FER_WEIGHTS` works too.
- To use only the expression model, use `MultitaskEngine` (256x256 uint8 BGR face chips -> all outputs).

### Demo (OpenCV window)

```bash
fujielab-fer-demo --source 0                        # camera
fujielab-fer-demo --source in.mp4 --out out.mp4 --no-window --jsonl out.jsonl
fujielab-fer-demo --det-size 320 --detect-interval 3 # even faster
fujielab-fer-demo --no-compile                       # faster start-up (no torch.compile)
```

Keys: `q`/Esc quit, `m` mesh, `a` AU, `s` smoothing. The camera is read in a separate thread and the latest frame is
always processed, so latency does not build up when processing falls behind.

### Web UI demo (browser camera)

```bash
fujielab-fer-web                               # http://localhost:8000
```

- The UI is in English by default; switch to Japanese with the button in the header (or `?lang=ja`).
- Browsers allow the camera only on a secure origin (HTTPS or localhost). From another PC, forward the port
  (`ssh -L 8000:localhost:8000 <server>`) and open `http://localhost:8000`, or serve on the LAN with
  `fujielab-fer-web --host 0.0.0.0 --ssl` (creates a self-signed certificate in `~/.cache/fujielab_fer/web/`; accept the
  browser warning the first time).
- How it works: the browser shows the camera video itself and sends JPEGs (long side 640) over a WebSocket; the server
  returns only the JSON results (4 KB per face including the mesh), and the browser draws them over the video. The
  video stays smooth at the camera frame rate while the results update at the inference rate. The next frame is not
  sent until the result arrives, so latency does not build up. (Gradio or FastRTC send rendered images back, which costs
  latency and drawing flexibility.)
- Screen: box, mesh and gaze overlays (click a face to select it), emotion probabilities, a valence-arousal circumplex
  (trajectory of the last 3 s), the emotion history (last 20 s), AUs (parts of a face line drawing move with the
  probabilities; movements at 0.5 or above get an arrow and a name; numbers and probabilities are in a collapsible
  panel), head pose and gaze, and processing time. Detection interval, smoothing and mirroring can be switched, and the
  results can be recorded to JSONL.
- On a landscape screen the video height is limited so that everything fits on one screen. Text and figure sizes scale
  with the screen (the same proportions on a projector) and can be changed further with the text size buttons.
- Each connection has its own tracking state (`FaceExpressionRecognizer.session()`); the model is shared.
- With `--codec <tokenizer>`, the original dialogue features and the features decoded from the tokens are shown side
  by side (the number of codebooks can be switched). There is also a mode that takes video files as input.
- Speed (a Python client sending a DISFA video as 640x480 JPEGs, TensorRT 640, compile): 16.5 ms round trip (9.7 ms
  with detection every 3rd frame). In headless Chromium (fake camera), including JPEG encoding in the browser: 23 fps,
  35 ms round trip.

### Speed measurement

```bash
fujielab-fer-bench                          # expression model only (1, 2, 4, 8 faces)
fujielab-fer-bench --source face.jpg        # whole pipeline including detection
```

## Distilled models

With py-feat v28 (ConvNeXt-V2 tiny) as the teacher, all outputs (emotion, VA, AU, gaze, pose, mesh, blendshapes) were
distilled without labels into light ConvNeXt-V2 students. **Every student is about as accurate as the teacher**; the
speed difference is small on a GPU (the teacher also takes 2 ms) and **large on the CPU**.

| Use | Repository | Architecture | CPU (1 face) |
|---|---|---|---|
| with a GPU, accuracy first | [`fujielab/fujielab-fer-nano`](https://huggingface.co/fujielab/fujielab-fer-nano) | ConvNeXt-V2 nano, head 512, input 224 (28.5M) | 24.1 ms |
| without a GPU, speed first | [`fujielab/fujielab-fer-atto-192`](https://huggingface.co/fujielab/fujielab-fer-atto-192) | ConvNeXt-V2 atto, head 256, input 192 (11.2M) | 8.2 ms |

```python
fer = FaceExpressionRecognizer(weights="fujielab/fujielab-fer-atto-192")
```

```bash
fujielab-fer-demo --weights fujielab/fujielab-fer-nano
fujielab-fer-web --weights fujielab/fujielab-fer-atto-192
FUJIELAB_FER_WEIGHTS=fujielab/fujielab-fer-atto-192 python my_app.py
```

If a model on the Hub requires accepting its terms, accept them on the model page and log in with `hf auth login`
first. The safetensors metadata holds the architecture (backbone, head width, input size), and the library builds the
model to match. Append `@<revision>` (a full commit hash) to pin a version, e.g.
`fujielab/fujielab-fer-nano@6ee0a23607333396c690bc86ff75bbf8e7f7844e`.

### Students compared (all 400k x 12 epochs)

Evaluated with the same face boxes and definitions as our benchmark (UA over 7 emotions; AU = mean of 5 AUs (1, 2, 4, 6,
12); DISFA every 3rd frame). "Agree" is the argmax agreement of emotion with the teacher on 4,000 held-out faces. Speed
is the expression model only, one face; GPU = RTX 4060 Ti (no other jobs, torch.compile + CUDA Graph), CPU = i9-12900K
with 4 threads (`tools/speed_students.py`).

| Model | Head | Input | Params | Agree | RAF UA | AffectNet UA | CCC V / A | DISFA AU F1 / AUC | EmotioNet AU F1 / AUC | GPU B=1 | GPU 8 faces (per face) | CPU |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| teacher (py-feat v28, tiny) | 512 | 224 | 41.7M | — | 82.48 | 60.49 | 0.585 / 0.520 | 68.9 / 96.7 | 71.1 / 96.0 | 1.93 ms | 0.72 ms | 38.0 ms |
| **nano** (HF) | 512 | 224 | 28.5M | 95.2 | **82.83** | 60.43 | 0.584 / 0.520 | 70.7 / 96.1 | 71.8 / 96.0 | 1.39 ms | 0.45 ms | 24.1 ms |
| pico | 512 | 224 | 21.7M | 94.8 | 82.16 | 60.71 | 0.581 / 0.520 | 70.5 / 96.0 | 71.2 / 95.9 | 1.06 ms | 0.33 ms | 18.6 ms |
| femto | 512 | 224 | 17.7M | 94.3 | 81.58 | 60.66 | 0.581 / 0.517 | 71.1 / 96.1 | 71.9 / 96.0 | 0.95 ms | 0.28 ms | 14.5 ms |
| atto | 512 | 224 | 16.1M | 94.3 | 81.95 | 60.34 | 0.580 / 0.516 | 71.6 / 96.0 | 71.6 / 96.0 | 0.91 ms | 0.25 ms | 12.6 ms |
| atto | 256 | 224 | 11.2M | 94.5 | 81.40 | 60.60 | 0.580 / 0.517 | 70.3 / 96.0 | 71.5 / 95.9 | 0.81 ms | 0.22 ms | 9.2 ms |
| **atto** (HF, atto-192) | 256 | 192 | 11.2M | 93.4 | 82.09 | 60.60 | 0.581 / 0.516 | 70.5 / 95.9 | 71.6 / 96.0 | 0.75 ms | 0.19 ms | 8.2 ms |
| atto | 256 | 160 | 11.2M | 93.7 | 80.04 | 60.17 | 0.577 / 0.514 | 69.1 / 96.0 | 71.9 / 96.0 | 0.71 ms | 0.17 ms | 7.1 ms |

- Why these two: nano is closest to the teacher in emotion and VA and has the smallest mesh (0.46 px) and gaze (2.68°)
  differences. atto-192 is the fastest while keeping the accuracy. Input 160 is only about 1 ms faster than 192 but
  loses 2 points of RAF UA. pico, femto and atto (head 512) fall between the two in both accuracy and speed.
- "Head" is the width of the AU, mesh and other heads (py-feat's `afg_channels`). Width 512 starts from the teacher's
  head weights; 256 is trained from scratch. On the CPU the AU head (AFG) took a quarter of atto's time, so width 256
  made it 20% faster.
- Whole pipeline on the CPU (with detection, DISFA video, detector input 320): teacher 45 ms -> atto (head 512) 24 ms;
  with detection every 3rd frame, 33 -> 11 ms (89 fps).
- UA of atto (head 512) on other sets (student / teacher): JAFFE 55.7 / 57.0, CK+ 87.8 / 87.3, AIST 58.2 / 58.0, FER2013
  57.9 / 57.5, **ExpW 50.8 / 57.8**. Only ExpW drops, consistent with the teacher scoring 8 points higher on ExpW than
  other models (ExpW is in py-feat's training data).

### How the students were distilled

- **Data**: no labels. Faces were detected with SCRFD in corpus images and videos and stored as 256x256 JPEGs with the
  same crop as py-feat (668k faces, 8.6 GB): AffectNet train 287k, Hazumi 187k, CMU-MOSEI 78k, MELD 72k, CREMA-D 22k,
  RAF-DB train 11k, RAVDESS 10k. Long videos are decoded at key frames only (tens of times faster than decoding every
  frame). **The evaluation sets (AffectNet val, RAF-DB test, DISFA, EmotioNet, CK+, JAFFE, AIST, FER2013, ExpW) were not
  used.**
- **Training**: online distillation (teacher and student see the same augmented input; teacher in fp16). Augmentation:
  affine, horizontal flip, color, grayscale, blur, low resolution. Losses: KL for emotion, BCE for AU, KL over 180 bins
  for gaze, L1 for VA / mesh / pose / blendshapes (divided by the teacher's output standard deviation). The student
  backbone starts from ImageNet pretraining, and the heads from the teacher's weights when the shapes match. AdamW (lr
  1e-3, cosine, warmup 1,500), batch 128, 400k x 12 epochs, weight EMA, torch.compile. 2.5-3.5 hours on one RTX 2080 Ti
  (atto about 520 images/s, nano about 385 images/s). JPEG decoding (nvJPEG) and augmentation run on the GPU.
- Progress: every student reaches the teacher's AU accuracy in the first epoch, and the emotion UA catches up in about
  6 epochs.

### Procedure (`distill/`)

```bash
# 1. Collect face chips (7 processes, about 1.5 hours; resumes where it stopped)
python distill/extract_faces.py --out <data>/fer_distill --workers 7 --pidfile <logs>/extract.pid

# 2. Evaluation sets (in the environment of our internal benchmark; same face boxes as the benchmark)
<benchmark>/benchmark/facial_expression/.venv/bin/python distill/make_benchpack.py --out <...>/benchpack.pkl

# 3. Training (one run per GPU; stop with: kill -- -$(cat <runs>/<name>/pid))
C="--epochs 12 --epoch-size 400000 --bs 128 --lr 1e-3 --warmup 1500 --compile"
bash distill/run.sh nano_t512 0 --backbone convnextv2_nano.fcmae_ft_in22k_in1k $C
bash distill/run_queue.sh 1 atto_s256_i192 "--backbone convnextv2_atto.fcmae_ft_in1k --afg-channels 256 --input-size 192 $C" \
                            atto_s256_i160 "--backbone convnextv2_atto.fcmae_ft_in1k --afg-channels 256 --input-size 160 $C"

# 4. Result tables (per epoch, or only the last with --last)
python distill/summarize.py <runs>/nano_t512 <runs>/atto_s256_i192 --last

# 5. Check through the library and measure speed (the weights can be passed to --weights as they are)
python tools/validate_benchmark.py --corpora raf,affectnet --weights <run>/student_ep12.safetensors
python tools/speed_students.py --device cpu --threads 4
```

The scripts under `distill/`, `facefeat/` and `tools/` were written for our lab machines and contain paths to our
corpora; adapt them to your environment. `distill/profile_step.py` breaks down one training step (loading, decoding and
augmentation, teacher, student).

Notes on training:

- The RTX 2080 Ti (Turing) is slow in bf16, so we used fp16. In fp16 the mesh projection of the head occasionally
  overflowed to NaN, so the mesh fusion is computed in fp32, and the scale of the student's `proj` output is matched to
  the teacher before training. Faces where the teacher output is not finite are excluded from the loss
  (`teacher_nonfinite` in the log).
- With a head width different from the teacher (e.g. 256), the teacher weights cannot be copied. The AU head's
  `SCHead.s` must be initialized randomly as in py-feat (with zeros its gradient is zero and the AUs are not learned at
  all; we lost 12 epochs to this once).
- When extracting face chips in parallel, never run two workers with the same index (they append to the same file and
  corrupt the index; an exclusive lock now prevents it). `pkill -f` leaves the children spawned by
  `multiprocessing.spawn`, so stop the whole process group from `--pidfile`.

## Face features for spoken dialogue

Time-series features and a tokenizer for the **paralinguistic information of the face** (expression, head movement,
gaze), to feed spoken-dialogue models such as multimodal VAP (Voice Activity Projection). Identity (face shape, a
person's usual expression) is kept out as much as possible.

| Output | Rate | Content |
|---|---|---|
| (1) normalized features `z` | 25 Hz | **86 dims**: emotion log-probabilities 7, VA 2, AU logits 20, blendshape logits 52, head rotation 3, gaze 2, normalized by the mean and standard deviation over a large set of dialogue videos (below) (`features.py`; statistics in `assets/paraling_stats_{t,n}.json`) |
| baseline-subtracted features | 25 Hz | (1) minus a causal exponential moving average (τ seconds) (`RunningBaseline`). Removes "the person's usual face". **This is what removes identity most effectively** |
| (4b) tokens `codes` | 12.5 Hz | a Mimi-style causal codec (RVQ 8 x 256, 8 bits per codebook -> 800 bps with 8). Input: features with the baseline (τ = 60 s) subtracted. One frame of delay |
| (4b) latent `latent` | 12.5 Hz | the quantized 128 dims (sum over the codebooks used), for continuous input |

```python
from fujielab_fer import FaceExpressionRecognizer
from fujielab_fer.dialogue import FaceTokenizer, extract_video

fer = FaceExpressionRecognizer(weights="fujielab/fujielab-fer-nano")
tr = extract_video("talk.mp4", fer, model="n")         # 25 Hz: tr.z [T,86], tr.valid [T], tr.t [T] (largest face)
tok = FaceTokenizer.load("fujielab/fujielab-fer-facecodec-n")
enc = tok.encode(tr.z, tr.valid)                       # enc.codes [T/2, 8], enc.latent [T/2, 128], enc.z (baseline-subtracted input)
rec = tok.decode(enc.codes[:, :4])                     # decode from fewer codebooks -> [T, 86] (same space as enc.z)
```

```bash
fujielab-fer-dialogue talk.mp4 -o talk.npz --model n --codec fujielab/fujielab-fer-facecodec-n
fujielab-fer-dialogue pair.mp4 -o right.npz --crop 0.5,0,1,1    # the person on the right in a side-by-side video
```

- Real time (camera): `stream.FaceFeatureStream` (per-frame results at a varying frame rate -> a 25 Hz grid, baseline
  subtraction) and `tok.stream()` (tokens and decoded features every 2 frames). They give the same tokens as the offline
  `encode` (verified).
- Use the same base model (t = py-feat v28, n = nano) for the expression model and the tokenizer (the normalization
  statistics differ).
- For videos with non-square pixels (e.g. Seamless Interaction V01), `extract_video` reads the aspect ratio with
  ffprobe and corrects it.

### Model

| Name | Content |
|---|---|
| [`fujielab/fujielab-fer-facecodec-n`](https://huggingface.co/fujielab/fujielab-fer-facecodec-n) | base model nano, τ = 60 s, no speaker adversary |

`FaceTokenizer.load` reads an exported directory (`model.safetensors`, which also holds the normalization statistics
used in training; a warning is issued if they differ from the bundled ones), a run directory of
`facefeat/train_seq.py`, or an HF repo (`<owner>/<name>[@rev]`).

### Evaluation (speakers not seen in training)

Data: MHHS (our in-house dialogue corpus), NoXi, Hazumi and Seamless Interaction (Tabidachi and CEJC were left out for
turn-taking evaluation). Split by speaker: 2,760 sessions for training (205.7 hours), 233 for validation, 313 for test.

- **Information**: correlation of a linear reconstruction of (1) (the values without baseline subtraction) from the
  features (fit on validation, measured on test; mean over 86 dims). For the codec, also the correlation between its
  own decoder output and its input (baseline-subtracted).
- **Identity**: speaker identification from the mean and standard deviation over 2 s windows (logistic regression,
  tested on each speaker's last session). MHHS 12 speakers (chance 8.3%, noisy due to the small number), Seamless 97
  speakers (chance 1.0%).

| Features | Dims | Linear reconstruction r | Own decoding r | Speaker MHHS % | Speaker Seamless % |
|---|---|---|---|---|---|
| (1) as is (n) | 86 | 0.942 | – | 90.8 | 88.6 |
| (1) baseline subtracted, τ = 20 s | 86 | 0.638 | – | 11.8 | 12.4 |
| (1) baseline subtracted, τ = 60 s | 86 | 0.658 | – | 16.4 | 13.8 |
| backbone last stage (c5, 768 dims, t) | 768 | 0.842 | – | 99.8 | 96.1 |
| (3) TDNN (τ = 60, adversary 0.5) | 128 | 0.692 | – | 48.4 | 16.5 |
| **(4b) codec (τ = 60, no adversary)** | 128 | 0.569 | **0.899** | 42.2 | 12.7 |
| (4b) codec (τ = 60, 3 adversaries with resets) | 128 | 0.565 | 0.873 | 43.3 | 14.3 |
| (4b) codec (τ = 60, adversary 0.5, collapsed late) | 128 | 0.540 | 0.752 | 35.5 | 10.0 |
| (4b) codec (τ = 60, confusion 2.0) | 128 | 0.477 | 0.776 | 31.1 | 8.7 |
| (4b) codec (τ = 20, adversary 0.5) | 128 | 0.548 | 0.869 | 29.1 | 7.5 |
| (4b) codec (τ = 60, no adversary), 2 codebooks (200 bps) | 128 | 0.520 | 0.839 | 41.1 | 12.8 |
| (4a) HuBERT-style (t, no baseline, 2nd iteration, causal) | 256 | 0.797 | – | 82.4 | 79.1 |
| (4a) HuBERT-style (n, τ = 60, 1st iteration, causal) | 256 | 0.658 | – | 70.4 | 36.6 |

(The c5 and HuBERT-style rows were measured before a pixel-aspect-ratio fix of the data; the others after it. The
HuBERT-style models pick identity back up from the temporal context and leak a lot even with baseline-subtracted input.)

Findings:

- Most identity lies in "the person's usual face" (static offsets of blendshapes and AUs) and drops sharply with the
  **causal baseline subtraction** (Seamless 88.6 -> 13.8%). A shorter τ removes more, but also removes information about
  the expressive "state" (we tried τ = 10-300 s; 20-60 s is a good balance).
- Backbone features ((2): c5, gX, eyes) carry strong identity (96-100%) and are not suitable as input as they are.
- **A speaker adversary (gradient reversal) brings speaker identification on training speakers down to chance, but
  hardly helps on unseen speakers** (after baseline subtraction, leakage is the same with or without the adversary).
  Gradient reversal can also push the adversary loss up without bound and collapsed late in training once (adversary
  cross-entropy from chance 7.3 to 11.3, own-decoding correlation 0.84 -> 0.75). A confusion loss that pulls the
  adversary toward the uniform distribution (`--adv-mode confusion`, bounded below) is stable but costs a lot of
  reconstruction. The default is therefore no adversary.
- The teacher (t) and nano (n) differ little (own decoding of the τ = 60 codec: t 0.84, n 0.87-0.90; similar leakage).
  The lighter nano is the default.

### Training procedure (`facefeat/`)

```bash
# 1. Videos -> 25 Hz features (both teacher and nano, plus the head-input vectors). One process per machine / GPU (they share the job list)
python facefeat/extract.py manifest --sources mhhs,noxi,hazumi,seamless --seamless-max-sec 360 --out <data>/seqfeat
bash facefeat/run_extract.sh <GPU> <index>
# 2. Normalization statistics (equal weight per corpus) -> assets/, training caches (also baseline-subtracted versions)
python facefeat/stats.py
python facefeat/seqdata.py build --model n --baseline 60
# 3. Training and evaluation
bash facefeat/run_train.sh <GPU> codec_n_rb60 facefeat/train_seq.py --arch codec --model n --data paraling_n_rb60 --adv 0
python facefeat/eval_round.py --feats paraling_n_rb60,enc:<runs>/codec_n_rb60 --out <data>/eval/round2.jsonl
python facefeat/summarize_eval.py <data>/eval/round2.jsonl
```

Pitfalls:

- **Non-square pixels**: Seamless Interaction V01 has 2160x2160 pixels displayed at 9:16. Ignoring the aspect ratio
  feeds the model faces stretched horizontally by 1.78 (fixed in both extraction and the demo's conversion).
- **The inference fast path of PyTorch's `TransformerEncoderLayer`** mishandles per-head 3-D float masks (ALiBi) (results
  change only at evaluation). `seqmodels.CausalTransformer` disables it.
- **cuDNN TF32**: the trained codec amplifies TF32 rounding differences in convolutions, and the tokens change with
  how the input is chunked. It is disabled for inference (`FaceTokenizer`, `CodecStream`, evaluation).
- Pascal and Maxwell GPUs (1080 Ti, TITAN X) need torch 2.8 cu126 in a separate environment and train in fp32.

## Speed

Measured on an RTX 4060 Ti **shared with other jobs** (99-100% utilization, load average 15-20); a free GPU is faster.
The "53 ms/face" of the benchmark was measured on the same busy GPU; re-measuring py-feat under the same conditions gave
75 ms per face (median).

### Expression model (per face; `tools/tune_engine.py`, `tools/speed_engine.py`)

| Setting | Wall clock B=1 | GPU kernel time B=1 | 8 faces at once (per face) |
|---|---|---|---|
| py-feat itself (called as in the benchmark: 720p frame to GPU -> crop -> inference) | 75 ms | — | — |
| own definition (no syncs, fused AFG, crop with cv2, one output transfer) | 14.2 ms | 7.4 ms | 7.0 ms |
| + CUDA Graph + channels_last | 13.3 ms | 6.4 ms | 6.5 ms |
| + **torch.compile** (default) | **6.5 ms** | **2.0 ms** | **2.7 ms** |
| (reference) CUDA Graph + channels_last, no gaze / blendshapes | 6.8 ms | 3.8 ms | 3.0 ms |

What helped:

1. **At B=1, launching from the CPU costs more than the GPU compute (a few ms).** One inference consists of about 700
   kernels, and on a busy shared CPU/GPU, launch and sync waits dominate. py-feat also synchronized with the GPU twice per
   inference (it indexes the eye ROIs with Python lists) -> the indices became buffers, removing the syncs, and
   everything from preprocessing through the model to output packing runs in a **CUDA Graph**.
2. **torch.compile** (inductor) fuses the small ops of ConvNeXt (LayerNorm, GELU, ...), cutting GPU kernel time from 6.4
   to 2.0 ms. A comment in py-feat says "compile shifts AUs by 0.16", but this does not happen with v28 (see the table
   below; 1-1.5 min the first time, about 20 s afterwards with the inductor cache).
3. **Cropping only the 256x256 chip with cv2.warpAffine on the CPU** (0.05-0.15 ms/face). py-feat moved the whole frame to
   the GPU, converted it to float and cropped with grid_sample.
4. The outputs (AU, emotion, VA, pose, gaze, blendshapes, mesh) are packed into one tensor, reducing transfers to the CPU
   from 11 to 1.

### Whole pipeline (detection + crop + expression; DISFA video 1024x768, one face; `fujielab-fer-bench --source`)

| Configuration | Detection | Expression | Total |
|---|---|---|---|
| detector input 640 (as in the benchmark), onnxruntime CUDA | 22.4 ms | 6.1 ms | 29.1 ms (34 fps) |
| detector input 320 | 5.9 ms | 4.9 ms | 11.6 ms (86 fps) |
| detector input 320, every 3rd frame (mesh tracking in between) | 2 ms on average | 6.7 ms | 8.8 ms (113 fps) |
| detector input 640, **TensorRT fp16** | 8.4 ms | 6.2 ms | 15.0 ms (67 fps) |
| detector input 640, TensorRT fp16, every 3rd frame | 3 ms on average | 6.6 ms | 7.9 ms (126 fps) |

With the expression model this fast, **face detection (SCRFD, 10 GFLOPs in fp32) became the heaviest part**. Ways to
lighten it:

- **A smaller detector input** (`det_size=320`): enough when faces are large, as with a dialogue partner in front of the
  camera. Small faces are missed.
- **Detect less often and track** (`detect_interval=N`): on frames without detection, the box is made from the 478-point
  mesh that the expression model predicted on the previous frame (the same idea as MediaPipe). The mapping from the
  mesh's bounding rectangle to an SCRFD box was fit on 400 RAF-DB faces (`tools/fit_mesh_to_box.py`): median IoU with the
  SCRFD box 0.92, median difference of the emotion probabilities when re-inferred with that box 0.02. A newly appearing
  face shows up at the next detection.
- **TensorRT** (installed with the `tensorrt` extra and used by `det_backend="auto"`, fp16): SCRFD alone at 640 goes from
  20.4 to 6.5 ms, at 320 from 6.9 to 5.3 ms (box difference in fp16 at most 0.03 px). However, **building the engine the
  first time takes long** (on a busy GPU about 16 min for 640 and 20 min for 320). The engine is saved in
  `~/.cache/fujielab_fer/trt/det<size>/` and loads in seconds afterwards (onnxruntime does not put the input size in the
  engine file name and overwrites it when built with another size, so each size gets its own directory). At 320 the
  difference from the CUDA EP is small, so TensorRT mainly helps at 640.

Not tried yet:

- TensorRT for the expression model (export to ONNX; roi_align maps to ONNX RoiAlign). With compile the GPU time is
  already 2 ms, so the gain would mainly be the CPU-side overhead at B=1.
- Overlapping detection and expression inference on separate CUDA streams / threads (expression of frame t with
  detection of t+1).

## Agreement with py-feat

`tools/validate_benchmark.py` re-ran the benchmark sets through this library (cv2 crop + torch.compile + CUDA Graph)
with **the same face boxes as the benchmark** and compared with the py-feat predictions stored by the benchmark.

| Set | Faces | Emotion argmax agreement | Probability difference (mean) | VA difference | AU difference | UA (7 emotions): this library / benchmark | CCC V, A: this library / benchmark |
|---|---|---|---|---|---|---|---|
| RAF-DB test | 3,068 | 99.67% | 0.0008 | 0.0016 | 0.0019 | 82.46 / 82.48 | — |
| AffectNet val | 3,999 | 99.60% | 0.0010 | 0.0017 | 0.0017 | 60.46 / 60.49 | 0.584, 0.520 / 0.584, 0.520 |

The differences are bf16 rounding noise (the same size as py-feat's own bf16 vs fp32 difference;
`tools/tune_engine.py`, `tools/compare_pyfeat.py`). AU probabilities move by up to about 0.09 on some faces because edges
of the AU graph (kNN) swap with rounding; the same happens between py-feat's fp32 and bf16. Our SCRFD gives the same
boxes as the benchmark (insightface) (median difference 0 px on 100 RAF-DB images; `tools/check_detector.py`).

## Repository layout

```
src/fujielab_fer/
├── _pyfeat_v2.py   py-feat's multitask model, only the path used by v28 (same weight keys)
├── engine.py       chip -> all outputs (CUDA Graph, torch.compile, channels_last, one output transfer)
├── crop.py         py-feat's crop (box x1.2 -> square on the long side -> 256, reflect padding) with cv2.warpAffine
├── detector.py     SCRFD (insightface buffalo_l det_10g) on onnxruntime (also TensorRT fp16)
├── recognizer.py   high-level API (detect -> crop -> infer -> frame coordinates, tracking, smoothing)
├── features.py     the 86-dim dialogue features (1), normalization (assets/paraling_stats_{t,n}.json), causal baseline subtraction
├── stream.py       real-time alignment to the 25 Hz grid and incremental tokenization
├── seqmodels.py    sequence models (causal TDNN, Mimi-style codec, HuBERT-style, speaker adversary)
├── dialogue.py     video -> 25 Hz features -> tokens (extract_video, FaceTokenizer, fujielab-fer-dialogue)
├── demo.py         live demo (OpenCV window)
├── web/            web UI demo (server.py: FastAPI + WebSocket; static/: index.html, app.js, style.css)
└── bench.py        speed measurement
tests/test_equivalence.py   agreement with py-feat (crop, engine, CUDA Graph)
tools/                      comparison with py-feat, speed per setting, detector check, tracking fit, student speed
facefeat/                   extraction, training and evaluation of the dialogue features
distill/                    distillation (face extraction, training, evaluation, job queue, result tables)
```

## Notes

- The caveats of our benchmark apply: py-feat v28's training data includes DISFA, EmotioNet and ExpW (see py-feat's
  [dataset register](https://github.com/cosanlab/py-feat/blob/main/LICENSES/DATASETS.md)), so scores on those sets are
  not held-out for the teacher (nor, indirectly, for the students). VA is lower than on the py-feat model card
  in our setting (AffectNet val CCC 0.58 / 0.52).
- AU20 is effectively non-functional (F1 0.057 on the py-feat model card).
- Speed numbers were measured on a shared GPU (with other jobs running); a free GPU is faster.

## Acknowledgements

This library depends on the models and research of [py-feat](https://github.com/cosanlab/py-feat) and
[InsightFace](https://github.com/deepinsight/insightface). If you use it in research, please also cite py-feat.
