Ascend-SACT/TRIBEV2
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

TRIBE v2 Ascend NPU Adaptation

中文文档 | English

1. Model Overview

TRIBE v2 is a tri-modal brain encoding model developed by Meta AI, designed to predict fMRI brain activity when humans watch videos, listen to audio, and read text. The model uses three pretrained encoders (V-JEPA, Wav2Vec-BERT, LLaMA) to extract features, then fuses them through a Transformer and maps to 70,000 brain voxels via a Subject Layer.

MetricValue
Modalitiesvideo, audio, text
Output70,000 voxels (whole-brain fMRI)
Parameters~4.8B (including three encoders)

Internal Encoders

ModalityEncoderParameters
VideoV-JEPA2 ViT-G1.03B
AudioWav2Vec-BERT 2.0580M
TextLLaMA 3.2-3B3.21B

2. Requirements

Hardware

ModelStatus
Ascend 910CVerified
Ascend 910BExpected compatible

Software

SoftwareVersion
CANN8.5.1
Driver25.5.0 (C23)
Python3.10 (image tag says py3.11, actual is 3.10.12)
PyTorch2.5.1
torch_npu2.5.1
transformersLatest

Docker Image

docker pull swr.cn-south-1.myhuaweicloud.com/ascendhub/cann:8.5.1-a3-ubuntu22.04-py3.11

Note: --privileged is recommended for dev/test environments. For production, use --cap-add=SYS_PTRACE --cap-add=IPC_LOCK --cap-add=SYS_ADMIN instead.

3. Quick Start

3.1 Start Container

docker run -d \
  --privileged \
  --device /dev/davinci_manager \
  --device /dev/devmm_svm \
  --device /dev/hisi_hdc \
  --device /dev/davinci0 \
  --device /dev/davinci1 \
  -v /data:/data \
  -v /usr/local/Ascend:/usr/local/Ascend \
  --name tribev2_npu \
  swr.cn-south-1.myhuaweicloud.com/ascendhub/cann:8.5.1-a3-ubuntu22.04-py3.11

3.2 Configure Environment

# Enter container
docker exec -it tribev2_npu bash

# Set CANN environment variables
source /usr/local/Ascend/ascend-toolkit/set_env.sh

3.3 Get Code

# Clone TRIBE v2 repository
cd /data
git clone https://github.com/facebookresearch/tribev2.git

# Create exca patch file (fixes exca 0.5.17 compatibility with neuralset)
cat > /data/tribev2/exca_patch.py << 'EOF'
#!/usr/bin/env python3
"""
exca 0.5.17 Compatibility Patch for Python 3.10

Problem: neuralset 0.0.2 requires exca >= 0.5.20, but exca 0.5.20+
requires Python >= 3.11. This patch adds missing methods to exca 0.5.17.

Methods added:
1. _get_discriminated_subclasses() - Class dispatcher for DiscriminatedModel
2. __new__() - Subclass instantiation method
"""
from exca import helpers

@classmethod
def _get_discriminated_subclasses(cls) -> dict:
    """Get all subclasses with the same discriminator key."""
    key = cls._exca_discriminator_key
    val_classes = {}
    for s in helpers._get_subclasses(cls) + [cls]:
        if s._exca_discriminator_key != key:
            continue
        val = s.__name__
        past = val_classes.get(val, None)
        if past is not None and past.__module__ != s.__module__:
            raise RuntimeError(f"2 subclasses from different modules are named {val!r}")
        val_classes[val] = s
    return val_classes

def __new__(cls, /, **kwargs):
    """Instantiate the correct subclass based on discriminator."""
    key = cls._exca_discriminator_key
    type_name = kwargs.get(key)
    if type_name is not None and type_name != cls.__name__:
        target = cls._get_discriminated_subclasses().get(type_name)
        if target is not None:
            return super(helpers.DiscriminatedModel, target).__new__(target)
    return super(helpers.DiscriminatedModel, cls).__new__(cls)

# Apply patch
helpers.DiscriminatedModel._get_discriminated_subclasses = _get_discriminated_subclasses
helpers.DiscriminatedModel.__new__ = __new__

print("exca 0.5.17 patch applied successfully")
EOF

3.4 Install Dependencies

cd /data/tribev2

# Install base dependencies
pip3 install pydantic==2.10.6

# Install exca 0.5.17 (neuralset needs exca>=0.5.20, but 0.5.20+ requires Python 3.11)
pip3 install exca==0.5.17

# Install neuralset/neuraltrain (skip deps check, exca is patched)
pip3 install neuralset==0.0.2 neuraltrain==0.0.2 --no-deps

# Install transformers with compatible versions (latest for V-JEPA2)
pip3 install transformers --upgrade
pip3 install huggingface_hub==0.29.0 tokenizers==0.21.2

# Install CANN TBE required dependencies
pip3 install decorator scipy attrs psutil sympy cffi pyyaml

# Apply exca patch
python3 exca_patch.py

3.5 Download Models

Note: If models exist in /data/npu_adapter/tribev2/cache/, skip this step and set:

export TRIBE_CACHE=/data/npu_adapter/tribev2/cache

Option A: Use ModelScope (Recommended for China)

# Install ModelScope
pip install modelscope

# Download LLaMA 3.2-3B
modelscope download --model LLM-Research/Llama-3.2-3B-Instruct --local_dir /data/cache/modelscope/LLM-Research/Llama-3___2-3B-Instruct

# Create HuggingFace cache mapping
mkdir -p ~/.cache/huggingface/hub/models--meta-llama--Llama-3.2-3B/snapshots
ln -s /data/cache/modelscope/LLM-Research/Llama-3___2-3B-Instruct ~/.cache/huggingface/hub/models--meta-llama--Llama-3.2-3B/snapshots/main

Option B: Use HuggingFace (Requires Authorization)

  1. Visit https://huggingface.co/meta-llama/Llama-3.2-3B and request access
  2. Configure token:
    export HF_TOKEN=<your_token>
    huggingface-cli login

Download Audio and Video Encoders:

# Use China mirror for faster download
export HF_ENDPOINT=https://hf-mirror.com

# Wav2Vec-BERT 2.0
huggingface-cli download facebook/w2v-bert-2.0 --local-dir /data/cache/models--facebook--w2v-bert-2.0

# V-JEPA2
huggingface-cli download facebook/vjepa2-vitg-fpc64-256 --local-dir /data/cache/models--facebook--vjepa2-vitg-fpc64-256

3.6 Run Inference

cd /data/tribev2
python run_inference_npu.py

Expected Output:

TRIBE v2 NPU Inference Test
============================
Device: npu:0 (Ascend 910C)
Model loaded successfully!

Text Encoder (LLaMA 3.2-3B):
  Output shape: [1, 10, 3072]
  Latency: 24.88 ms

Audio Encoder (Wav2Vec-BERT 2.0):
  Output shape: [1, 100, 1024]
  Latency: 75.93 ms (seq=1000)

Video Encoder (V-JEPA2 ViT-G):
  Output shape: [1, 1024, 1408]
  Latency: 420.25 ms (frames=32)

All encoders verified on NPU!

4. Adaptation Notes

4.1 Python Version Selection

Current Solution: Use container's Python 3.10 + exca patch (image cann:8.5.1-a3-ubuntu22.04-py3.11 tag says py3.11, but actual Python is 3.10.12)

Alternative: Users can try installing Python 3.11 environment

Background:

  • neuralset 0.0.2 requires exca >= 0.5.20
  • exca 0.5.20+ requires Python >= 3.11
  • Current image has Python 3.10, can only install exca 0.5.17, requiring patch for missing methods

Comparison:

SolutionProsCons
Python 3.10 + patch (current)Uses existing image, verifiedRequires manual exca_patch.py
Python 3.11 (optional)No patch neededNeed to install separately

Recommendation: Current image with exca_patch.py is verified working. If users encounter patch-related issues, try:

  1. Install Python 3.11 in container: apt-get install python3.11
  2. Or use another Ascend image with Python 3.11

4.2 exca Patch Details

Current image has Python 3.10. Meta's internal library neuralset requires exca >= 0.5.20, but exca 0.5.20+ needs Python >= 3.11. Patch exca 0.5.17:

# exca_patch.py adds to helpers.DiscriminatedModel:
# 1. _get_discriminated_subclasses() - Class dispatcher method
# 2. __new__() - Subclass instantiation method

Apply Patch:

import sys
sys.path.insert(0, "/data/tribev2")
import exca_patch  # Must be executed before importing neuralset

4.3 ModelScope LLaMA Alternative

LLaMA 3.2-3B is a HuggingFace gated model requiring:

  1. Manual access request on the webpage
  2. HF_TOKEN environment variable configuration

Using ModelScope version bypasses authentication, suitable for China region.

4.4 NPU Operator Compatibility

OperatorStatusNotes
ArgSort⚠️ Auto fallbackAiCore doesn't support int32/int64, falls back to AiCpu
Others✅ NormalStandard Transformer/ViT operators supported

5. Performance

Note: The following performance data is unoptimized. Further improvements can be achieved through operator optimization, graph optimization, etc.

Ascend 910C NPU Performance

EncoderModelParamsLatencyThroughput
TextLLaMA 3.2-3B3.2B24.9ms40.2 inf/s
AudioWav2Vec-BERT 2.0580M75.9ms (seq=1000)13.2 inf/s
VideoV-JEPA2 ViT-G1.0B420.2ms (32f)2.4 inf/s

NPU vs CPU Accuracy

EncoderMSEMAEMax DiffCosine SimRelative Error
Text (LLaMA)0.0000040.0014130.080.9999980.13%
Audio (Wav2Vec-BERT)~00.0000120.0011.0000000.02%
Video (V-JEPA2)0.0420.08519.370.9982514.4%

Rating:

  • LLaMA: ⭐⭐⭐⭐⭐ Excellent, ready for production
  • Wav2Vec-BERT: ⭐⭐⭐⭐⭐ Excellent, best accuracy
  • V-JEPA2: ⭐⭐⭐⭐ Good, recommend end-to-end business validation

6. FAQ

Q1: drvErr=87 or EL0005: Resource_Busy

Cause: NPU driver initialization requires privileged permissions.

Solution: Use --privileged or add necessary capabilities:

docker run --cap-add=SYS_PTRACE --cap-add=IPC_LOCK --cap-add=SYS_ADMIN ...

Q2: _get_discriminated_subclasses method missing

Cause: exca 0.5.17 doesn't include this method.

Solution: Run python exca_patch.py to apply the patch.

Q3: LLaMA model loading fails with GatedRepoError

Cause: HuggingFace gated model requires authentication.

Solution: Use ModelScope alternative model or configure HF_TOKEN.

Q4: ArgSort kernel warning

Cause: NPU AiCore doesn't support int32/int64 ArgSort.

Solution: No action needed, automatically falls back to AiCpu, doesn't affect inference.

7. Key Files

FileDescription
exca_patch.pyexca 0.5.17 compatibility patch
run_inference_npu.pyTri-modal inference script
benchmark_npu.pyPerformance benchmark script
accuracy_test.pyNPU vs CPU accuracy comparison script

8. References

  • Meta Demo: https://aidemos.atmeta.com/tribev2
  • HuggingFace: https://huggingface.co/facebook/tribev2
  • GitHub: https://github.com/facebookresearch/tribev2
  • Paper: https://arxiv.org/abs/2507.22229
  • ModelScope: https://modelscope.cn/models/LLM-Research/Llama-3.2-3B-Instruct