---
title: activation_trace
---

<div class="python-reference">
<a id="fastvideo.hooks.activation_trace-classes"></a>
<a id="fastvideo.hooks.activation_trace-functions"></a>
<a id="fastvideo.hooks.activation_trace"></a>
<p>Zero-overhead-when-off activation trace mode for FastVideo pipelines.</p>
<p>Enable by setting FASTVIDEO_TRACE_ACTIVATIONS=1. When off, this module
adds zero overhead — no hooks are registered, no branches exist in the
production forward path. When on, registers forward hooks on modules
whose name matches FASTVIDEO_TRACE_LAYERS, computes the requested stats
(FASTVIDEO_TRACE_STATS) on each output tensor, and writes JSONL records
to FASTVIDEO_TRACE_OUTPUT.</p>
<p>Useful for parity debugging across model ports — log on both the
FastVideo path and the upstream reference, diff the two JSONL files
to find the first divergent layer.</p>
<p>Example:</p>
<pre><code>FASTVIDEO_TRACE_ACTIVATIONS=1     FASTVIDEO_TRACE_LAYERS="^block\.layers\.[0-9]+$"     FASTVIDEO_TRACE_STATS="abs_mean,max,shape"     FASTVIDEO_TRACE_OUTPUT="/tmp/fv_trace.jsonl"     python examples/inference/basic/basic_magi_human.py
</code></pre>
<h2 id="fastvideo.hooks.activation_trace.ForwardHook"><code>fastvideo.hooks.activation_trace.ForwardHook</code></h2>
<pre class="doc-signature"><code>ForwardHook()</code></pre>
<p>Base class for forward hooks.
Hooks are used in the way:
    modified_args, modified_kwargs = hook.pre_forward(module, <em>args, </em><em>kwargs)
    output = module.forward(</em>modified_args, **modified_kwargs)
    modified_output = hook.post_forward(module, output)</p>
<h3 id="fastvideo.hooks.activation_trace.ForwardHook.name"><code>fastvideo.hooks.activation_trace.ForwardHook.name</code></h3>
<pre class="doc-signature"><code>name() -&gt; str</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ForwardHook.on_attach"><code>fastvideo.hooks.activation_trace.ForwardHook.on_attach</code></h3>
<pre class="doc-signature"><code>on_attach(module: nn.Module)</code></pre>
<p>Called once when the hook is attached to the module.</p>
<h3 id="fastvideo.hooks.activation_trace.ForwardHook.on_detach"><code>fastvideo.hooks.activation_trace.ForwardHook.on_detach</code></h3>
<pre class="doc-signature"><code>on_detach(module: nn.Module)</code></pre>
<p>Called once when the hook is detached from the module.
Note: this function is not guaranteed to be called if the module is
      deleted before the hook is detached.</p>
<h3 id="fastvideo.hooks.activation_trace.ForwardHook.pre_forward"><code>fastvideo.hooks.activation_trace.ForwardHook.pre_forward</code></h3>
<pre class="doc-signature"><code>pre_forward(module: nn.Module, *args, **kwargs) -&gt; tuple&#91;tuple&#91;Any, ...&#93;, dict&#91;str, Any&#93;&#93;</code></pre>
<p>Called before the module's forward method is executed.</p>
<h3 id="fastvideo.hooks.activation_trace.ForwardHook.post_forward"><code>fastvideo.hooks.activation_trace.ForwardHook.post_forward</code></h3>
<pre class="doc-signature"><code>post_forward(module: nn.Module, output: Any) -&gt; Any</code></pre>
<p>Called after the module's forward method is executed.</p>
<h2 id="fastvideo.hooks.activation_trace.ModuleHookManager"><code>fastvideo.hooks.activation_trace.ModuleHookManager</code></h2>
<pre class="doc-signature"><code>ModuleHookManager(module: nn.Module)</code></pre>


<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.get_from"><code>fastvideo.hooks.activation_trace.ModuleHookManager.get_from</code></h3>
<pre class="doc-signature"><code>get_from(module: nn.Module) -&gt; ModuleHookManager | None</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.get_from_or_default"><code>fastvideo.hooks.activation_trace.ModuleHookManager.get_from_or_default</code></h3>
<pre class="doc-signature"><code>get_from_or_default(module: nn.Module) -&gt; ModuleHookManager</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.remove_from_manager"><code>fastvideo.hooks.activation_trace.ModuleHookManager.remove_from_manager</code></h3>
<pre class="doc-signature"><code>remove_from_manager(module: nn.Module) -&gt; None</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.append_forward_hook"><code>fastvideo.hooks.activation_trace.ModuleHookManager.append_forward_hook</code></h3>
<pre class="doc-signature"><code>append_forward_hook(hook: ForwardHook)</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.replace_forward_hook"><code>fastvideo.hooks.activation_trace.ModuleHookManager.replace_forward_hook</code></h3>
<pre class="doc-signature"><code>replace_forward_hook(hook_name: str, new_hook: ForwardHook, run_on_attach: bool = True)</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.remove_forward_hook"><code>fastvideo.hooks.activation_trace.ModuleHookManager.remove_forward_hook</code></h3>
<pre class="doc-signature"><code>remove_forward_hook(hook_name: str, run_detach: bool = True)</code></pre>

<h3 id="fastvideo.hooks.activation_trace.ModuleHookManager.get_forward_hook"><code>fastvideo.hooks.activation_trace.ModuleHookManager.get_forward_hook</code></h3>
<pre class="doc-signature"><code>get_forward_hook(hook_name: str) -&gt; ForwardHook | None</code></pre>

<h2 id="fastvideo.hooks.activation_trace.init_logger"><code>fastvideo.hooks.activation_trace.init_logger</code></h2>
<pre class="doc-signature"><code>init_logger(name: str) -&gt; _FastvideoLogger</code></pre>
<p>The main purpose of this function is to ensure that loggers are
retrieved in such a way that we can be sure the root fastvideo logger has
already been configured.</p>
<h2 id="fastvideo.hooks.activation_trace.current_step_idx"><code>fastvideo.hooks.activation_trace.current_step_idx</code></h2>
<pre class="doc-signature"><code>current_step_idx() -&gt; int | None</code></pre>

<details><summary>Source</summary><pre><code>def current_step_idx() -&gt; int | None:
    return getattr(_TRACE_STATE, &quot;step_idx&quot;, None)</code></pre></details>
<h2 id="fastvideo.hooks.activation_trace.trace_step"><code>fastvideo.hooks.activation_trace.trace_step</code></h2>
<pre class="doc-signature"><code>trace_step(step_idx: int) -&gt; Iterator&#91;None&#93;</code></pre>
<p>Context manager that sets the current denoise step for trace records.</p>
<details><summary>Source</summary><pre><code>@contextmanager
def trace_step(step_idx: int) -&gt; Iterator&#91;None&#93;:
    &quot;&quot;&quot;Context manager that sets the current denoise step for trace records.&quot;&quot;&quot;
    prev = getattr(_TRACE_STATE, &quot;step_idx&quot;, None)
    _TRACE_STATE.step_idx = step_idx
    try:
        yield
    finally:
        _TRACE_STATE.step_idx = prev</code></pre></details>
<h2 id="fastvideo.hooks.activation_trace.JsonlSink"><code>fastvideo.hooks.activation_trace.JsonlSink</code></h2>
<pre class="doc-signature"><code>JsonlSink(path: Path)</code></pre>
<p>Buffered JSONL writer with thread-safe append.</p>

<details><summary>Source</summary><pre><code>class JsonlSink:
    &quot;&quot;&quot;Buffered JSONL writer with thread-safe append.&quot;&quot;&quot;

    def __init__(self, path: Path) -&gt; None:
        self.path = path
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self._fh = open(self.path, &quot;a&quot;, buffering=1)  # noqa: SIM115
        self._lock = threading.Lock()
        logger.info(&quot;Activation trace JSONL sink: %s&quot;, self.path)

    def write(self, record: dict&#91;str, Any&#93;) -&gt; None:
        line = json.dumps(record, default=str) + &quot;\n&quot;
        with self._lock:
            self._fh.write(line)

    def close(self) -&gt; None:
        with self._lock:
            if not self._fh.closed:
                self._fh.close()</code></pre></details>
<h3 id="fastvideo.hooks.activation_trace.JsonlSink.write"><code>fastvideo.hooks.activation_trace.JsonlSink.write</code></h3>
<pre class="doc-signature"><code>write(record: dict&#91;str, Any&#93;) -&gt; None</code></pre>

<details><summary>Source</summary><pre><code>def write(self, record: dict&#91;str, Any&#93;) -&gt; None:
    line = json.dumps(record, default=str) + &quot;\n&quot;
    with self._lock:
        self._fh.write(line)</code></pre></details>
<h3 id="fastvideo.hooks.activation_trace.JsonlSink.close"><code>fastvideo.hooks.activation_trace.JsonlSink.close</code></h3>
<pre class="doc-signature"><code>close() -&gt; None</code></pre>

<details><summary>Source</summary><pre><code>def close(self) -&gt; None:
    with self._lock:
        if not self._fh.closed:
            self._fh.close()</code></pre></details>
<h2 id="fastvideo.hooks.activation_trace.ActivationStatHook"><code>fastvideo.hooks.activation_trace.ActivationStatHook</code></h2>
<pre class="doc-signature"><code>ActivationStatHook(module_name: str, stats: list&#91;tuple&#91;str, Callable&#91;&#91;torch.Tensor&#93;, Any&#93;&#93;&#93;, sink: JsonlSink, step_filter: set&#91;int&#93; | None)</code></pre>
<p>Forward hook that emits per-tensor stats to a JSONL sink.</p>

<details><summary>Source</summary><pre><code>class ActivationStatHook(ForwardHook):
    &quot;&quot;&quot;Forward hook that emits per-tensor stats to a JSONL sink.&quot;&quot;&quot;

    def __init__(
        self,
        module_name: str,
        stats: list&#91;tuple&#91;str, Callable&#91;&#91;torch.Tensor&#93;, Any&#93;&#93;&#93;,
        sink: JsonlSink,
        step_filter: set&#91;int&#93; | None,
    ) -&gt; None:
        self.module_name = module_name
        self.stats = stats
        self.sink = sink
        self.step_filter = step_filter

    def name(self) -&gt; str:
        return &quot;ActivationStatHook&quot;

    def post_forward(self, module: nn.Module, output: Any) -&gt; Any:
        step_idx = current_step_idx()
        if self.step_filter is not None and step_idx not in self.step_filter:
            return output
        for tensor_label, tensor in _flatten_tensors(output):
            record: dict&#91;str, Any&#93; = &#123;
                &quot;module&quot;: self.module_name,
                &quot;tensor&quot;: tensor_label,
                &quot;step&quot;: step_idx,
            &#125;
            for stat_name, stat_fn in self.stats:
                try:
                    record&#91;stat_name&#93; = stat_fn(tensor)
                except Exception as exc:  # pragma: no cover - defensive logging
                    record&#91;stat_name&#93; = f&quot;&lt;error: &#123;exc!r&#125;&gt;&quot;
            self.sink.write(record)
        return output</code></pre></details>
<h3 id="fastvideo.hooks.activation_trace.ActivationStatHook.name"><code>fastvideo.hooks.activation_trace.ActivationStatHook.name</code></h3>
<pre class="doc-signature"><code>name() -&gt; str</code></pre>

<details><summary>Source</summary><pre><code>def name(self) -&gt; str:
    return &quot;ActivationStatHook&quot;</code></pre></details>
<h3 id="fastvideo.hooks.activation_trace.ActivationStatHook.post_forward"><code>fastvideo.hooks.activation_trace.ActivationStatHook.post_forward</code></h3>
<pre class="doc-signature"><code>post_forward(module: nn.Module, output: Any) -&gt; Any</code></pre>

<details><summary>Source</summary><pre><code>def post_forward(self, module: nn.Module, output: Any) -&gt; Any:
    step_idx = current_step_idx()
    if self.step_filter is not None and step_idx not in self.step_filter:
        return output
    for tensor_label, tensor in _flatten_tensors(output):
        record: dict&#91;str, Any&#93; = &#123;
            &quot;module&quot;: self.module_name,
            &quot;tensor&quot;: tensor_label,
            &quot;step&quot;: step_idx,
        &#125;
        for stat_name, stat_fn in self.stats:
            try:
                record&#91;stat_name&#93; = stat_fn(tensor)
            except Exception as exc:  # pragma: no cover - defensive logging
                record&#91;stat_name&#93; = f&quot;&lt;error: &#123;exc!r&#125;&gt;&quot;
        self.sink.write(record)
    return output</code></pre></details>
<h2 id="fastvideo.hooks.activation_trace.ActivationTraceManager"><code>fastvideo.hooks.activation_trace.ActivationTraceManager</code></h2>
<pre class="doc-signature"><code>ActivationTraceManager(managers: list&#91;ModuleHookManager&#93;, sink: JsonlSink)</code></pre>


<details><summary>Source</summary><pre><code>class ActivationTraceManager:

    def __init__(self, managers: list&#91;ModuleHookManager&#93;, sink: JsonlSink) -&gt; None:
        self.managers = managers
        self.sink = sink

    def remove_from_manager(self) -&gt; None:
        for manager in self.managers:
            if manager.get_forward_hook(&quot;ActivationStatHook&quot;) is not None:
                manager.remove_forward_hook(&quot;ActivationStatHook&quot;)
            if not manager.forward_hooks:
                ModuleHookManager.remove_from_manager(manager.module)
        self.sink.close()</code></pre></details>
<h3 id="fastvideo.hooks.activation_trace.ActivationTraceManager.remove_from_manager"><code>fastvideo.hooks.activation_trace.ActivationTraceManager.remove_from_manager</code></h3>
<pre class="doc-signature"><code>remove_from_manager() -&gt; None</code></pre>

<details><summary>Source</summary><pre><code>def remove_from_manager(self) -&gt; None:
    for manager in self.managers:
        if manager.get_forward_hook(&quot;ActivationStatHook&quot;) is not None:
            manager.remove_forward_hook(&quot;ActivationStatHook&quot;)
        if not manager.forward_hooks:
            ModuleHookManager.remove_from_manager(manager.module)
    self.sink.close()</code></pre></details>
<h2 id="fastvideo.hooks.activation_trace.attach_activation_trace"><code>fastvideo.hooks.activation_trace.attach_activation_trace</code></h2>
<pre class="doc-signature"><code>attach_activation_trace(model: nn.Module | None) -&gt; ActivationTraceManager | None</code></pre>
<p>Attach activation-stat hooks to model. Returns None if trace is off.</p>
<details><summary>Source</summary><pre><code>def attach_activation_trace(model: nn.Module | None) -&gt; ActivationTraceManager | None:
    &quot;&quot;&quot;Attach activation-stat hooks to model. Returns None if trace is off.&quot;&quot;&quot;
    if not envs.FASTVIDEO_TRACE_ACTIVATIONS.get() or model is None:
        return None

    pattern_spec = envs.FASTVIDEO_TRACE_LAYERS.get()
    pattern = re.compile(pattern_spec) if pattern_spec else re.compile(&quot;.*&quot;)
    stats = _resolve_stats(envs.FASTVIDEO_TRACE_STATS.get())
    if not stats:
        logger.warning(&quot;FASTVIDEO_TRACE_STATS yielded no valid stats; trace disabled.&quot;)
        return None

    sink = JsonlSink(_resolve_output_path(envs.FASTVIDEO_TRACE_OUTPUT.get()))
    step_filter = _parse_step_filter(envs.FASTVIDEO_TRACE_STEPS.get())
    managers = &#91;&#93;
    for name, module in model.named_modules():
        if not name or not pattern.search(name):
            continue
        manager = ModuleHookManager.get_from_or_default(module)
        manager.append_forward_hook(ActivationStatHook(name, stats, sink, step_filter))
        managers.append(manager)

    logger.info(
        &quot;Activation trace attached to %d modules (pattern=%r, stats=%s)&quot;,
        len(managers),
        pattern_spec,
        &#91;stat_name for stat_name, _ in stats&#93;,
    )
    return ActivationTraceManager(managers, sink)</code></pre></details>
<h2 id="fastvideo.hooks.activation_trace.detach_activation_trace"><code>fastvideo.hooks.activation_trace.detach_activation_trace</code></h2>
<pre class="doc-signature"><code>detach_activation_trace(mgr: ActivationTraceManager | None) -&gt; None</code></pre>

<details><summary>Source</summary><pre><code>def detach_activation_trace(mgr: ActivationTraceManager | None) -&gt; None:
    if mgr is not None:
        mgr.remove_from_manager()</code></pre></details>
</div>
