---
title: metric
---

<div class="python-reference">
<a id="fastvideo.eval.metrics.vbench.motion_smoothness.metric-classes"></a>
<a id="fastvideo.eval.metrics.vbench.motion_smoothness.metric-functions"></a>
<a id="fastvideo.eval.metrics.vbench.motion_smoothness.metric"></a>
<p>VBench Motion Smoothness — AMT-S frame interpolation quality.</p>
<p>Takes every-other frame, uses AMT-S to interpolate the missing middle
frames, then compares interpolated vs actual frames.
Score = (255 - mean_pixel_diff) / 255.  Higher = smoother motion.</p>
<h2 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric</code></h2>
<pre class="doc-signature"><code>BaseMetric()</code></pre>
<p>Abstract base class for all eval metrics.</p>
<p>Two execution shapes:</p>
<ul>
<li>
<p><strong>Per-sample</strong> (<code>is_set_metric=False</code>, default) — implement
  :meth:<code>compute</code>. The Evaluator calls it once per input sample and
  returns one :class:<code>MetricResult</code> per sample.</p>
</li>
<li>
<p><strong>Set-vs-set</strong> (<code>is_set_metric=True</code>) — implement
  :meth:<code>accumulate</code> (called once per sample to buffer features)
  and :meth:<code>finalize</code> (called once after all samples to compute
  the corpus-level result). Use :meth:<code>reset</code> to clear buffers and
  :meth:<code>merge_from</code> to fold multi-GPU per-worker state together.</p>
</li>
</ul>
<p>Optionally override :meth:<code>setup</code> to eagerly load models. Metrics
that chunk along the time dim for memory hardcode their own chunk
size in <code>__init__</code> (see <code>optical_flow</code> for the canonical
example). Eval always processes one video per
:meth:<code>Evaluator.evaluate</code> call; <code>compute</code> / <code>accumulate</code>
receive a single sample, not a batch.</p>

<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.to"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.to</code></h3>
<pre class="doc-signature"><code>to(device: str | torch.device) -&gt; BaseMetric</code></pre>
<p>Move metric (and its internal models) to <em>device</em>.</p>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.setup"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.setup</code></h3>
<pre class="doc-signature"><code>setup() -&gt; None</code></pre>
<p>Eagerly load models. Called once by :class:<code>EvalWorker</code>.</p>
<p>Default is a no-op; metrics with no eager state (pixel math,
closed-form ops) inherit this. Override only if your metric
needs to load weights.</p>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.compute"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.compute</code></h3>
<pre class="doc-signature"><code>compute(sample: dict) -&gt; MetricResult</code></pre>
<p>Per-sample metrics: compute the score for one sample.</p>
<p><code>sample["video"]</code> is <code>(T, C, H, W)</code> float in <code>[0, 1]</code>.
<code>sample["reference"]</code> (if used) has the same shape. Return
<code>self._skip(sample, reason)</code> for missing inputs.</p>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.reset"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.reset</code></h3>
<pre class="doc-signature"><code>reset() -&gt; None</code></pre>
<p>Clear accumulator state at the start of each evaluate() call.</p>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.accumulate"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.accumulate</code></h3>
<pre class="doc-signature"><code>accumulate(sample: dict) -&gt; None</code></pre>
<p>Buffer per-sample features for a corpus-level metric.</p>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.finalize"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.finalize</code></h3>
<pre class="doc-signature"><code>finalize() -&gt; MetricResult</code></pre>
<p>Compute the corpus-level result from buffered state.</p>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.merge_from"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.BaseMetric.merge_from</code></h3>
<pre class="doc-signature"><code>merge_from(other: BaseMetric) -&gt; None</code></pre>
<p>Multi-GPU: fold another worker's accumulator state into this one.</p>
<h2 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.register"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.register</code></h2>
<pre class="doc-signature"><code>register(name: str)</code></pre>
<p>Decorator to register a metric class.</p>
<p>Usage::</p>
<pre><code>@register("ssim")
class SSIMMetric(BaseMetric):
    ...
</code></pre>
<h2 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.MetricResult"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.MetricResult</code></h2>
<pre class="doc-signature"><code>MetricResult(name: str, score: float | None, details: dict&#91;str, Any&#93; = dict())</code></pre>
<p>Standard result container returned by all metrics.</p>
<p><code>score</code> is <code>None</code> when the metric was skipped (e.g. missing
required input).  Check <code>details["skipped"]</code> for the reason.</p>

<h2 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric</code></h2>
<pre class="doc-signature"><code>MotionSmoothnessMetric()</code></pre>


<details><summary>Source</summary><pre><code>@register(&quot;vbench.motion_smoothness&quot;)
class MotionSmoothnessMetric(BaseMetric):

    name = &quot;vbench.motion_smoothness&quot;
    requires_reference = False
    higher_is_better = True
    needs_gpu = True
    dependencies = &#91;&quot;omegaconf&quot;&#93;

    def __init__(self) -&gt; None:
        super().__init__()
        self._model: Any = None
        self._embt: Any = None
        self._chunk_size = 8

    def to(self, device):
        super().to(device)
        if self._model is not None:
            self._model = self._model.to(self.device)
        if self._embt is not None:
            self._embt = self._embt.to(self.device)
        return self

    def setup(self) -&gt; None:
        if self._model is not None:
            return
        from omegaconf import OmegaConf
        import vbench.third_party.amt as _amt_pkg
        from vbench.third_party.amt.utils.build_utils import build_from_cfg
        from fastvideo.eval.models import ensure_checkpoint

        amt_dir = os.path.dirname(_amt_pkg.__file__)
        cfg_path = os.path.join(amt_dir, &quot;cfgs&quot;, &quot;AMT-S.yaml&quot;)

        ckpt_path = ensure_checkpoint(
            &quot;amt-s.pth&quot;,
            source=&quot;https://huggingface.co/lalala125/AMT/resolve/main/amt-s.pth&quot;,
        )

        network_cfg = OmegaConf.load(cfg_path).network
        self._model = build_from_cfg(network_cfg)
        ckpt = torch.load(ckpt_path, map_location=&quot;cpu&quot;, weights_only=False)
        self._model.load_state_dict(ckpt&#91;&quot;state_dict&quot;&#93;)
        self._model.to(self.device)
        self._model.eval()

        self._embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(self.device)

    def _get_scale(self, h: int, w: int) -&gt; float:
        &quot;&quot;&quot;Pick a downscale factor that keeps AMT&#x27;s correlation volume
        within free GPU memory.

        Re-queries free memory on every call (rather than caching at setup
        time) so the scale adapts to whatever&#x27;s actually available — other
        metric replicas already loaded, residual generator allocations,
        another process sharing the GPU, etc. The upstream version cached
        ``total_memory`` at setup, which on a shared/loaded GPU lets AMT
        attempt a 30+ GB correlation volume reshape and OOM.
        &quot;&quot;&quot;
        if self.device.type != &quot;cuda&quot;:
            return 1.0
        # Free memory that won&#x27;t be claimed by other allocations during this
        # forward pass. min(free, total) is conservative against transient
        # spikes; mem_get_info returns (free, total) in bytes.
        free_bytes, _ = torch.cuda.mem_get_info(self.device)
        anchor_resolution = 1024 * 512
        anchor_memory = 1500 * 1024**2
        anchor_memory_bias = 2500 * 1024**2
        if free_bytes &lt;= anchor_memory_bias:
            # Less than the model + scratch overhead is free; force the
            # most aggressive downscale we support.
            return 1 / 16
        scale = anchor_resolution / (h * w) * np.sqrt((free_bytes - anchor_memory_bias) / anchor_memory)
        if scale &gt;= 1.0:
            return 1.0
        scale = 1 / np.floor(1 / np.sqrt(scale) * 16) * 16
        return float(scale)

    _MIN_AMT_SCALE = 1 / 16

    def _safe_amt_forward(self, in0: Any, in1: Any, embt: Any, scale: Any) -&gt; Any:
        &quot;&quot;&quot;Run one chunk through AMT with OOM-retry on two axes.

        Recovery strategy on ``CUDA out of memory``:

        1. **Halve the batch** until batch=1. AMT&#x27;s per-pair memory
           dominates; splitting helps until each pair is on its own.
        2. **Halve the scale_factor** passed to AMT (which controls its
           internal feature-map resolution and therefore the correlation
           volume size). Bottoms out at ``_MIN_AMT_SCALE`` — beyond that
           the feature maps are too coarse to produce meaningful
           interpolation and we re-raise.

        Self-tunes under memory pressure: the upstream autoscale formula
        in :meth:`_get_scale` mis-extrapolates at large resolutions
        (treats memory as linear in pixel count, but AMT&#x27;s correlation
        volume grows quadratically). This retry path makes the metric
        robust to that without rewriting the formula.
        &quot;&quot;&quot;
        try:
            return self._model(in0, in1, embt, scale_factor=scale, eval=True)&#91;&quot;imgt_pred&quot;&#93;
        except torch.cuda.OutOfMemoryError:
            torch.cuda.empty_cache()
            bs = in0.shape&#91;0&#93;
            if bs &gt; 1:
                half = bs // 2
                a = self._safe_amt_forward(in0&#91;:half&#93;, in1&#91;:half&#93;, embt&#91;:half&#93;, scale)
                b = self._safe_amt_forward(in0&#91;half:&#93;, in1&#91;half:&#93;, embt&#91;half:&#93;, scale)
                return torch.cat(&#91;a, b&#93;, dim=0)
            if scale &gt; self._MIN_AMT_SCALE:
                return self._safe_amt_forward(in0, in1, embt, scale / 2)
            raise

    @torch.no_grad()
    def compute(self, sample: dict) -&gt; MetricResult:
        from vbench.third_party.amt.utils.utils import (
            img2tensor,
            tensor2img,
            check_dim_and_resize,
            InputPadder,
        )

        video = sample&#91;&quot;video&quot;&#93;  # (T, C, H, W) &#91;0, 1&#93;
        chunk = self._chunk_size or 8

        frames_np = (video * 255).to(torch.uint8).cpu().numpy()
        frames_np = &#91;f.transpose(1, 2, 0) for f in frames_np&#93;  # list of (H,W,C)

        even_indices = list(range(0, len(frames_np), 2))
        if len(even_indices) &lt;= 1:
            return MetricResult(name=self.name, score=1.0, details=&#123;&#125;)

        even_frames = &#91;frames_np&#91;i&#93; for i in even_indices&#93;
        inputs = &#91;img2tensor(f).to(self.device) for f in even_frames&#93;
        inputs = check_dim_and_resize(inputs)

        h, w = inputs&#91;0&#93;.shape&#91;-2:&#93;
        scale = self._get_scale(h, w)
        padding = int(16 / scale)
        padder = InputPadder(inputs&#91;0&#93;.shape, padding)
        inputs = padder.pad(*inputs)

        n_pairs = len(inputs) - 1
        all_in0 = &#91;inputs&#91;i&#93; for i in range(n_pairs)&#93;
        all_in1 = &#91;inputs&#91;i + 1&#93; for i in range(n_pairs)&#93;
        all_gt = &#91;
            frames_np&#91;even_indices&#91;i&#93; + 1&#93; if even_indices&#91;i&#93; + 1 &lt; len(frames_np) else frames_np&#91;-1&#93;
            for i in range(n_pairs)
        &#93;

        all_preds = &#91;&#93;
        for start in range(0, len(all_in0), chunk):
            end = min(start + chunk, len(all_in0))
            in0_batch = torch.cat(all_in0&#91;start:end&#93;, dim=0).to(self.device)
            in1_batch = torch.cat(all_in1&#91;start:end&#93;, dim=0).to(self.device)
            embt = self._embt.expand(in0_batch.shape&#91;0&#93;, -1, -1, -1)
            pred = self._safe_amt_forward(in0_batch, in1_batch, embt, scale)
            all_preds.append(pred.cpu())
        all_preds = torch.cat(all_preds, dim=0)

        diffs: list&#91;float&#93; = &#91;&#93;
        for i in range(n_pairs):
            pred = all_preds&#91;i:i + 1&#93;
            pred_unpadded = padder.unpad(pred)&#91;0&#93;
            pred_np = tensor2img(pred_unpadded)
            gt_np = all_gt&#91;i&#93;
            # gt comes from frames_np; pred goes through check_dim_and_resize +
            # AMT pad/unpad, which can reshape. Match shapes before absdiff.
            if gt_np.shape&#91;:2&#93; != pred_np.shape&#91;:2&#93;:
                gt_np = cv2.resize(gt_np, (pred_np.shape&#91;1&#93;, pred_np.shape&#91;0&#93;), interpolation=cv2.INTER_AREA)
            diffs.append(float(np.mean(cv2.absdiff(gt_np, pred_np))))

        vfi_score = float(np.mean(diffs)) if diffs else 0.0
        return MetricResult(
            name=self.name,
            score=(255.0 - vfi_score) / 255.0,
            details=&#123;&quot;vfi_score&quot;: vfi_score&#125;,
        )</code></pre></details>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric.to"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric.to</code></h3>
<pre class="doc-signature"><code>to(device)</code></pre>

<details><summary>Source</summary><pre><code>def to(self, device):
    super().to(device)
    if self._model is not None:
        self._model = self._model.to(self.device)
    if self._embt is not None:
        self._embt = self._embt.to(self.device)
    return self</code></pre></details>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric.setup"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric.setup</code></h3>
<pre class="doc-signature"><code>setup() -&gt; None</code></pre>

<details><summary>Source</summary><pre><code>def setup(self) -&gt; None:
    if self._model is not None:
        return
    from omegaconf import OmegaConf
    import vbench.third_party.amt as _amt_pkg
    from vbench.third_party.amt.utils.build_utils import build_from_cfg
    from fastvideo.eval.models import ensure_checkpoint

    amt_dir = os.path.dirname(_amt_pkg.__file__)
    cfg_path = os.path.join(amt_dir, &quot;cfgs&quot;, &quot;AMT-S.yaml&quot;)

    ckpt_path = ensure_checkpoint(
        &quot;amt-s.pth&quot;,
        source=&quot;https://huggingface.co/lalala125/AMT/resolve/main/amt-s.pth&quot;,
    )

    network_cfg = OmegaConf.load(cfg_path).network
    self._model = build_from_cfg(network_cfg)
    ckpt = torch.load(ckpt_path, map_location=&quot;cpu&quot;, weights_only=False)
    self._model.load_state_dict(ckpt&#91;&quot;state_dict&quot;&#93;)
    self._model.to(self.device)
    self._model.eval()

    self._embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(self.device)</code></pre></details>
<h3 id="fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric.compute"><code>fastvideo.eval.metrics.vbench.motion_smoothness.metric.MotionSmoothnessMetric.compute</code></h3>
<pre class="doc-signature"><code>compute(sample: dict) -&gt; MetricResult</code></pre>

<details><summary>Source</summary><pre><code>@torch.no_grad()
def compute(self, sample: dict) -&gt; MetricResult:
    from vbench.third_party.amt.utils.utils import (
        img2tensor,
        tensor2img,
        check_dim_and_resize,
        InputPadder,
    )

    video = sample&#91;&quot;video&quot;&#93;  # (T, C, H, W) &#91;0, 1&#93;
    chunk = self._chunk_size or 8

    frames_np = (video * 255).to(torch.uint8).cpu().numpy()
    frames_np = &#91;f.transpose(1, 2, 0) for f in frames_np&#93;  # list of (H,W,C)

    even_indices = list(range(0, len(frames_np), 2))
    if len(even_indices) &lt;= 1:
        return MetricResult(name=self.name, score=1.0, details=&#123;&#125;)

    even_frames = &#91;frames_np&#91;i&#93; for i in even_indices&#93;
    inputs = &#91;img2tensor(f).to(self.device) for f in even_frames&#93;
    inputs = check_dim_and_resize(inputs)

    h, w = inputs&#91;0&#93;.shape&#91;-2:&#93;
    scale = self._get_scale(h, w)
    padding = int(16 / scale)
    padder = InputPadder(inputs&#91;0&#93;.shape, padding)
    inputs = padder.pad(*inputs)

    n_pairs = len(inputs) - 1
    all_in0 = &#91;inputs&#91;i&#93; for i in range(n_pairs)&#93;
    all_in1 = &#91;inputs&#91;i + 1&#93; for i in range(n_pairs)&#93;
    all_gt = &#91;
        frames_np&#91;even_indices&#91;i&#93; + 1&#93; if even_indices&#91;i&#93; + 1 &lt; len(frames_np) else frames_np&#91;-1&#93;
        for i in range(n_pairs)
    &#93;

    all_preds = &#91;&#93;
    for start in range(0, len(all_in0), chunk):
        end = min(start + chunk, len(all_in0))
        in0_batch = torch.cat(all_in0&#91;start:end&#93;, dim=0).to(self.device)
        in1_batch = torch.cat(all_in1&#91;start:end&#93;, dim=0).to(self.device)
        embt = self._embt.expand(in0_batch.shape&#91;0&#93;, -1, -1, -1)
        pred = self._safe_amt_forward(in0_batch, in1_batch, embt, scale)
        all_preds.append(pred.cpu())
    all_preds = torch.cat(all_preds, dim=0)

    diffs: list&#91;float&#93; = &#91;&#93;
    for i in range(n_pairs):
        pred = all_preds&#91;i:i + 1&#93;
        pred_unpadded = padder.unpad(pred)&#91;0&#93;
        pred_np = tensor2img(pred_unpadded)
        gt_np = all_gt&#91;i&#93;
        # gt comes from frames_np; pred goes through check_dim_and_resize +
        # AMT pad/unpad, which can reshape. Match shapes before absdiff.
        if gt_np.shape&#91;:2&#93; != pred_np.shape&#91;:2&#93;:
            gt_np = cv2.resize(gt_np, (pred_np.shape&#91;1&#93;, pred_np.shape&#91;0&#93;), interpolation=cv2.INTER_AREA)
        diffs.append(float(np.mean(cv2.absdiff(gt_np, pred_np))))

    vfi_score = float(np.mean(diffs)) if diffs else 0.0
    return MetricResult(
        name=self.name,
        score=(255.0 - vfi_score) / 255.0,
        details=&#123;&quot;vfi_score&quot;: vfi_score&#125;,
    )</code></pre></details>
</div>
