/ Модель

Характеристики

Лицензия
Apache 2.0
Базовая модель
vit_pe_core_large_patch14_336.fb
Опубликована
16 ноя 2026

mars-gend

Классификация видеоВидео → label3 профессии

Модель классифицирует видео для выявления дипфейков и других манипуляций с лицами.

34скачиваний за 30 дней0лайковвеса обновлены17 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

vector-institute/mars-gend — переобученная командой MARS базовая модель GenD для обнаружения подделанных и манипулированных видео. Это не исходные веса авторов GenD: модель повторно реализована и обучена по протоколу MARS. Для оценки кадров используется визуальный энкодер PE-Core-L на базе ViT; обучаются только нормализационные слои, а нормализованные признаки классифицируются одним линейным слоем. Оценка видео вычисляется как среднее вероятностей манипуляции по кадрам и клипам. Модель анализирует RGB-кадры: берётся каждый второй кадр, изображения приводятся к размеру 336×336, клипы содержат до 64 кадров.

Модель предназначена для классификации видео как подлинных или манипулированных, включая выявление дипфейков. В README приведены результаты на FaceForensics++, Celeb-DF v2 и DeepfakeTIMIT; показатели различаются между наборами данных. Репозиторий содержит веса safetensors и полный граф ONNX в float32; ONNX-граф включает энкодер, тогда как для варианта safetensors энкодер загружается отдельно. Лицензия — Apache-2.0. Оценки не калиброваны, поэтому порог принятия решения следует выбирать на валидационных данных целевого сценария.

Сценарии применения

  • выявление дипфейков в видео
  • проверка видео на подмену лица
  • классификация подлинных и манипулированных роликов
  • оценка видеоматериалов из FaceForensics++
  • анализ видео для выявления синтетических лиц

Ограничения

Оценки не калиброваны, поэтому порог решения нужно подбирать на валидационных данных целевого сценария. Результаты зависят от набора данных и протокола: модель обучена на FaceForensics++ и GTA-V, а показатели в статье GenD не совпадают с результатами этой пере реализации.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

GenD, re-implemented and trained under the MARS protocol

arXiv Code MARS Original GenD code

This is a GenD baseline from the MARS project: our re-implementation of GenD (Yermakov et al., WACV 2026), trained and evaluated under the same protocol as MARS. It is not the original authors' model or weights; training data, inputs, optimization and checkpoint selection follow the MARS protocol, so its numbers differ from those in the GenD paper.

GenD scores each frame with a Perception Encoder (PE-Core-L) in which only the normalization layers are trained. The pooled feature is L2-normalized and classified by one linear layer, and the clip score is the mean of the frame scores.

Training length. This checkpoint was trained for 10 epochs. The main comparison table in the MARS paper reports GenD under the shared 3-epoch recipe, where it reaches a 65.78 average AUROC; with 10 epochs it reaches 88.46 (below).

Files

filecontentssize
model.safetensorstrained normalization layers and head; the rest of PE-Core-L is not included and is downloaded from timm on first use0.4 MB
config.yamlmodel and data settings, read by the mars package1 KB
model.onnxcomplete graph, encoder included; runs with ONNX Runtime alone, float321.32 GB
model.fp16.onnxthe same graph in float16, inputs and outputs still float32; less GPU memory0.66 GB
usual_ranges.jsonpercentiles of the ONNX video score on the authentic and manipulated test videos, with model.onnx3 KB
usual_ranges.fp16.jsonthe same with model.fp16.onnx3 KB
serving.jsonmeasured GPU memory and time per clip with ONNX Runtime (both files, batch 1 and 2), opset, outputs, encoder chunk, ONNX Runtime version1 KB

Input

  1. Decode the video as RGB and keep every second frame (0, 2, 4, ...).
  2. Cut the kept frames into consecutive clips of 64. A short last clip (or a short video) is padded by repeating its last frame; n_valid is the number of real frames.
  3. Resize each frame to 336 x 336 (square, no crop, bicubic with antialiasing), scale to [0, 1], then to [-1, 1].
  4. The video score is the mean P(manipulated) over its clips.

Scores are not calibrated. If you need a decision, choose a threshold on validation data from your own setting.

Use with safetensors (PyTorch)

Requires the code repository:

git clone https://github.com/VectorInstitute/mars.git && cd mars && uv sync
import torch
from huggingface_hub import snapshot_download
from safetensors.torch import load_file

from mars.config import load_yaml
from mars.data.sampling import clips_for_video
from mars.data.transforms import preprocess
from mars.data.video import count_frames, read_frames
from mars.models.factory import build_detector

folder = snapshot_download("vector-institute/mars-gend", allow_patterns=["config.yaml", "model.safetensors"])
raw = load_yaml(f"{folder}/config.yaml")
detector = build_detector(raw["model"]["name"], raw)
model = detector.build_network()  # downloads PE-Core-L on first use
missing, unexpected = model.load_state_dict(load_file(f"{folder}/model.safetensors"), strict=False)
assert not unexpected and all(key.startswith("encoder.") for key in missing)  # only the frozen encoder weights are absent
model = model.cuda().eval()
data = detector.cfg.data


def score(path: str) -> float:
    """Mean P(manipulated) over the clips of one video."""
    probs = []
    for clip in clips_for_video(path, count_frames(path), data.n_frames, data.frame_stride):
        frames = preprocess(read_frames(path, list(clip.frame_indices)), data.image_size)[None].cuda()
        valid = (torch.arange(data.n_frames) < clip.n_valid)[None].cuda()
        with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
            logits = model(frames, valid).logits
        probs.append(logits.float().softmax(-1)[0, 1].item())
    return sum(probs) / len(probs)


print(score("video.mp4"))

Use with ONNX (no PyTorch, no code repository)

pip install onnxruntime-gpu av numpy pillow huggingface_hub   # or onnxruntime for CPU
nameshape, typemeaning
input frames(B, 64, 3, 336, 336), float32B clips in [-1, 1]
input n_valid(B,), int64number of real frames in each clip, 1 to 64
output fake_prob(B,), float32P(manipulated) for each clip
output logits(B, 2), float32authentic and manipulated logits
output frame_probs(B, 64), float32P(manipulated) of each frame on its own, 0 on padded frames

The batch size B is free. Clip length, frame stride and image size are also stored in the file's metadata.

Both files take the full 64-frame clip. Inside the graph the encoder processes 16 frames of each clip at a time; frames are encoded independently, so this lowers memory without changing the outputs. On an A100, one clip peaks at about 2.8 GiB of GPU memory with model.onnx and 2.3 GiB with model.fp16.onnx (details in serving.json). The float16 video scores are within 0.006 of float32 on UADFV and Celeb-DF. Use model.onnx on CPU, or as the source for a TensorRT engine.

The clip logits are the mean of the per-frame logits, so fake_prob is the sigmoid of the mean logit of frame_probs over the real frames, not the mean of frame_probs. For the clip score, use fake_prob; do not average frame_probs.

usual_ranges.json gives the percentiles (0 to 100) of the video score on the authentic and on the manipulated test videos listed under Results, computed with model.onnx; usual_ranges.fp16.json is the same for model.fp16.onnx. Use them to place a score in context, not as a threshold.

import av
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from PIL import Image

session = ort.InferenceSession(
    hf_hub_download("vector-institute/mars-gend", "model.onnx"),  # or "model.fp16.onnx" for less GPU memory
    providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
meta = session.get_modelmeta().custom_metadata_map
T, STRIDE, S = (int(meta[key]) for key in ("n_frames", "frame_stride", "image_size"))


def to_input(rgb: np.ndarray) -> np.ndarray:
    """(H, W, 3) uint8 RGB to (3, S, S) float32 in [-1, 1]."""
    x = rgb.astype(np.float32) / 255.0
    if x.shape[:2] != (S, S):
        channels = [Image.fromarray(np.ascontiguousarray(x[..., c])).resize((S, S), Image.BICUBIC) for c in range(3)]
        x = np.clip(np.stack([np.asarray(c) for c in channels], axis=-1), 0.0, 1.0)
    return ((x - 0.5) / 0.5).transpose(2, 0, 1)


def score(path: str) -> float:
    """Mean P(manipulated) over the clips of one video."""
    with av.open(path) as container:
        kept = [to_input(f.to_ndarray(format="rgb24")) for i, f in enumerate(container.decode(video=0)) if i % STRIDE == 0]
    probs = []
    for start in range(0, len(kept), T):
        clip = kept[start : start + T]
        n_valid = len(clip)
        clip = clip + [clip[-1]] * (T - n_valid)
        inputs = {"frames": np.stack(clip)[None].astype(np.float32), "n_valid": np.array([n_valid], dtype=np.int64)}
        probs.append(float(session.run(["fake_prob"], inputs)[0][0]))
    return float(np.mean(probs))


print(score("video.mp4"))

Neither ONNX file runs in bfloat16 like the evaluation behind Results, so scores differ slightly from that table. To use the GPU, ONNX Runtime needs CUDA and cuDNN; if PyTorch with CUDA is installed, import torch before creating the session also works.

Training

training dataFaceForensics++ (c23; original videos and Deepfakes, Face2Face, FaceSwap, NeuralTextures; official splits) and GTA-V (rendered sequences from SAIL-VOS 3D, all synthetic)
validationFaceForensics++ validation split; the checkpoint is the epoch with the best video AUROC (the last of 10)
clips64 frames, every second frame, full frames at 336 x 336
encodervit_pe_core_large_patch14_336.fb; every normalization layer is trained, the rest is frozen
losscross-entropy plus uniformity (weight 0.5) and alignment (weight 0.1) on the unit-norm features
optimizationAdamW, learning rate 1e-4, weight decay 1e-4, batch 32 clips, step decay x0.5 every 3,333 steps, 10 epochs, bfloat16, seed 0
hardware4 x NVIDIA A40

Results

Video-level AUROC and average precision (%), trained on FaceForensics++ and GTA-V. A video's score is the mean over its clips.

test setvideosAUROCAP
FaceForensics++ (test split)70096.6899.11
Celeb-DF v251884.0991.01
DeepfakeTIMIT96095.0897.81
UADFV9897.0097.53
HiFiFace (paired with FF++ targets)28076.4278.91
GenVideo (validation split, 10 generators)18,28680.4984.71
DF26 (10 generators)2,69189.4498.27
average88.46

License

The weights in this repository are released under Apache 2.0. The encoder is Meta's Perception Encoder (PE-Core-L), downloaded from timm under its own license (Apache 2.0).

Citation

Please cite the MARS paper for these weights and the protocol, and the GenD paper for the method.

@misc{radwan2026marsmultiscaleappearanceresidualstreams,
      title={MARS: Multiscale Appearance-Residual Streams for Video Forgery Detection},
      author={Ahmed Y. Radwan and Shaina Raza},
      year={2026},
      eprint={2611.12508},
      archivePrefix={arXiv},
      primaryClass={cs.CV},
      url={https://arxiv.org/abs/2611.12508},
}

@inproceedings{GenD,
    title     = {Deepfake detection that generalizes across benchmarks},
    author    = {Yermakov, Andrii and Cech, Jan and Matas, Jiri and Fritz, Mario},
    year      = 2026,
    booktitle = {Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision},
    pages     = {773--783}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Нельзя запустить

Не удалось определить, чем загружать веса модели (нет library_name и architectures).

Ревизия весов
3dd6619

0 моделей