---
title: 'RGFiLM: Rarity-Aware Feature-wise Modulation'
url: https://www.emergentmind.com/topics/rarity-gated-feature-wise-linear-modulation-rgfilm
type: topic
---

# RGFiLM: Rarity-Aware Feature-wise Modulation

Searching arXiv for RGFiLM and closely related FiLM/gated modulation papers to ground the article.
Rarity-Gated Feature-wise Linear Modulation (RGFiLM) is a rarity-aware context-conditioning module for contextual anomaly detection in which context generates feature-wise affine modulation parameters, while a separate gate—controlled by a data-driven rarity score—regulates how strongly the context-modulated representation should replace the original hidden state. In its reported instantiation, RGFiLM is inserted into an offline imitation learning-based maritime anomaly detector operating on AIS motion sequences with ERA5 environmental context, and is motivated by the observation that standard context-conditioned models can become unstable under highly imbalanced context distributions, particularly in rare but operationally important regimes. The defining claim of the method is not merely that context should be incorporated, but that the *manner* of conditioning should depend on empirical context rarity [2606.13311].

## 1. Contextual anomaly detection under imbalanced contexts

RGFiLM is formulated for contextual anomaly detection, where anomalousness depends on the conditional distribution $p(\mathbf{b}\mid \mathbf{c})$, with $\mathbf{b}$ denoting behavior and $\mathbf{c}$ denoting context. The sequential setting is central. A trajectory is represented as
$$
\tau=\{(s_t, e_t, a_t)\}_{t=1}^T,
$$
where $s_t$ is state at time $t$, $e_t$ is exogenous environmental context, and $a_t$ is an action or discretized decision. In the maritime case study, route deviations may be abnormal in calm conditions yet acceptable under severe weather, so anomaly scoring cannot be divorced from context [2606.13311].

The paper frames the core difficulty as **frequency bias** induced by imbalanced context distributions. Frequent contexts dominate training and are well fitted; rare contexts are underrepresented and can yield unstable or poorly calibrated context-conditioned responses. The reported consequence is excessive false alarms or overreaction to context in rare regimes. RGFiLM is therefore designed against a specific failure mode of ordinary context integration: standard FiLM or concatenation-based conditioning implicitly assumes sufficient support over the context distribution, whereas RGFiLM treats rarity itself as a control variable [2606.13311].

A recurrent misconception addressed by the formulation is that rare context should simply induce stronger context usage. The method does not adopt that rule. Instead, it sharpens the decision over whether the model should trust the context-modulated representation or fall back toward the original latent state. The distinction is operationally important: rarity modulates the *decisiveness* of interpolation, not a monotonic increase in contextual reliance [2606.13311].

## 2. Formal definition and gating mechanism

RGFiLM begins with a state encoder that produces a hidden representation
$$
\mathbf{h}_t = f_{\text{state}}(s_{1:t}),
$$
and an environment encoder that maps context to FiLM parameters
$$
(\boldsymbol{\gamma}_t, \boldsymbol{\beta}_t)=f_{\text{env}}(e_t).
$$
These parameters define the context-modulated hidden state
$$
\tilde{\mathbf{h}}_t=\boldsymbol{\gamma}_t\odot \mathbf{h}_t + \boldsymbol{\beta}_t,
$$
with $\odot$ denoting element-wise multiplication. This is the FiLM component proper: context-conditioned feature-wise scaling and shifting of latent features [2606.13311].

The distinctive addition is a rarity-controlled gate. Rarity is computed from a selected context subvector $e_t^r\in\mathbb{R}^{d_r}$; in the reported experiments,
$$
e_t^r=[\text{wave height, wind speed}].
$$
From normal training data, the method estimates a mean vector $\boldsymbol{\mu}$ and covariance matrix $\boldsymbol{\Sigma}$, then computes a Mahalanobis distance
$$
D_t^2 = (e_t^r - \boldsymbol{\mu})^{\top} \boldsymbol{\Sigma}^{-1} (e_t^r - \boldsymbol{\mu}).
$$
Assuming a multivariate Gaussian approximation, the rarity score is
$$
r_t = F_{\chi^2_{d_r}}(D_t^2),
$$
where $F_{\chi^2_{d_r}}$ is the chi-squared CDF with $d_r$ degrees of freedom. Thus $r_t\in[0,1]$, with small values denoting common contexts and large values denoting rare or extreme contexts [2606.13311].

The gate first computes
$$
s_t = g([e_t, r_t]),
$$
where $g$ is a small neural network operating on the concatenation of raw context and rarity. Rarity-dependent sharpening is then applied by
$$
\tilde{s}_t = \frac{s_t(1 + \kappa r_t)}{\tau},
$$
with base temperature $\tau>0$ and rarity sensitivity $\kappa\ge 0$. The scalar gate is
$$
w_t = \sigma(\tilde{s}_t),
$$
and the final RGFiLM output is
$$
\mathbf{h}_t^* = w_t\,\tilde{\mathbf{h}}_t + (1-w_t)\,\mathbf{h}_t.
$$
Equivalently, RGFiLM interpolates between the original representation and the FiLM-modulated representation using a rarity-aware mixing coefficient [2606.13311].

Two structural properties follow directly from this definition. First, FiLM is **feature-wise**, since $\boldsymbol{\gamma}_t,\boldsymbol{\beta}_t$ match the hidden dimension. Second, the rarity gate is **scalar per time step**, so interpolation is global across the latent vector at that step. A plausible implication is that RGFiLM separates *what* to modulate at feature level from *how much* to trust the modulated state at representation level.

## 3. Architectural insertion and anomaly-scoring pipeline

RGFiLM is integrated into the OIL-AD framework by replacing the original state representation with $\mathbf{h}_t^*$ wherever the state encoder output is used. The insertion point is therefore after sequence encoding and before the downstream OIL-AD heads. The sequence of computation is: encode AIS trajectory history into $\mathbf{h}_t$, encode environmental context into $(\boldsymbol{\gamma}_t,\boldsymbol{\beta}_t)$, form $\tilde{\mathbf{h}}_t$, compute rarity score $r_t$ and gate $w_t$, then pass $\mathbf{h}_t^*$ to the action and monotonicity heads [2606.13311].

The broader anomaly detector remains an offline imitation learning pipeline. AIS state is
$$
s_t=[LAT_t,LON_t,SPEED_t]\in\mathbb{R}^3,
$$
and actions are discretized into five categories: up, right, down, left, and stay. Environmental context is aligned from ERA5 as
$$
e_t=[\mathrm{SWH}_t,\mathrm{WindSpeed}_t,\mathrm{WindDir}_t].
$$
RGFiLM does not alter the original OIL-AD objective structure; the paper states that the action loss and monotonicity loss are retained unchanged, with $\mathbf{h}_t^*$ replacing $\mathbf{h}_t$ in the latent pathway [2606.13311].

At inference time, the model produces time-step anomaly evidence $z_t$, and the trajectory-level anomaly score is
$$
S(\tau)=\frac{1}{T}\sum_{t=1}^{T} z_t.
$$
A threshold is selected on the validation set and applied to the test set. Models are trained only on normal training trajectories; anomalies are synthetically injected only in validation and test data. The reported preprocessing follows OIL-AD: AIS messages are sorted by timestamp, cleaned, and temporally regularized; trajectories are split at stationary segments when vessel speed remains at $\text{SPEED}\le 1.2$ for more than a fixed number of consecutive steps; retained segments satisfy length $T\in[50,300]$ and are not dominated by near-stationary behavior [2606.13311].

The experimental dataset is an AIS–ERA5 corpus for the Bass Strait region in Australia covering July 2020 to December 2020. The principal benchmark is an environment-sensitive detour scenario in which anomalous validation and test trajectories are created by modifying a contiguous subsegment with an approximately $2^\circ$ eastward longitude shift before rejoining the original path, while leaving the environmental sequence unchanged. This design makes the anomaly injection environment-invariant and tests whether context-sensitive conditioning can reduce false alarms without legitimizing the injected detour [2606.13311].

## 4. Empirical behavior, ablations, and rare-context effects

The evaluation protocol uses 20 random seeds, a 10:1 normal-to-anomaly ratio in validation and test, and reports mean $\pm$ standard deviation over runs for Precision, Recall, F1 score, and False Positive Rate (FPR). The paper emphasizes the F1–FPR trade-off rather than accuracy-like summaries alone [2606.13311].

In the main comparison, RGFiLM achieves
$$
\text{F1}=0.595\pm0.067,\quad
\text{Precision}=0.474\pm0.080,\quad
\text{Recall}=0.826\pm0.118,\quad
\text{FPR}=0.097\pm0.037.
$$
Relative to OIL-AD without environmental context, F1 improves from $0.524$ to $0.595$ and FPR decreases from $0.120$ to $0.097$. Relative to standard FiLM, F1 improves from $0.577$ to $0.595$, Recall improves from $0.798$ to $0.826$, and FPR remains essentially unchanged at $0.098\rightarrow0.097$. Relative to **OIL-AD + Gated FiLM (no rarity)**, F1 improves from $0.582$ to $0.595$ and FPR decreases from $0.108$ to $0.097$ [2606.13311].

The gated-FiLM ablation is the most direct isolation of the rarity term. It shows that gating alone is beneficial, FiLM alone is beneficial, and rarity-aware sharpening contributes additional false-positive reduction beyond either component individually. Paired Wilcoxon signed-rank tests over matched seeds show significant improvements in F1 and FPR over OIL-AD and Concat at $p<0.05$, and a significant FPR reduction over OIL-AD + Gated FiLM with $p=0.028$. The paper explicitly notes that the strongest significant gains are concentrated in false-alarm reduction [2606.13311].

The rare-context analysis further clarifies the intended behavior. Trajectories are stratified by environmental rarity into frequent (bottom 80%) and rare (top 20%). All methods degrade in rare contexts, but RGFiLM attains the highest mean F1 in both regimes—$0.604$ in frequent and $0.547$ in rare—and the lowest mean FPR in both—$0.098$ in frequent and $0.092$ in rare. The reported gain over FiLM is larger in the rare regime, from $0.513$ to $0.547$, than in the frequent regime, from $0.587$ to $0.604$. This suggests that rarity-aware gating is most useful precisely where empirical context support is weakest [2606.13311].

The mechanism behind this pattern is the sharpening factor $(1+\kappa r_t)/\tau$. As $r_t$ increases, the magnitude of the sigmoid input grows for fixed $s_t$, pushing $w_t$ closer to $0$ or $1$. The intended effect is therefore a more confident decision between preserving $\mathbf{h}_t$ and trusting $\tilde{\mathbf{h}}_t$ in rare regimes, rather than a blanket amplification of context. The reported validation-selected hyperparameters are $\tau=1.2$ and $\kappa=0.1$ [2606.13311].

## 5. Relation to FiLM and adjacent gated-modulation architectures

RGFiLM belongs to the broader family of feature-wise affine modulation methods, but its novelty lies in coupling FiLM with a rarity-conditioned interpolation gate. In standard FiLM formulations, hidden features are modulated as $\gamma(c)\odot h+\beta(c)$, with conditioning supplied by some external variable. That paradigm appears across domains including graph message passing, where target-node representations generate feature-wise affine transformations over incoming messages in GNN-FiLM [1906.12192], and implicit ensembling, where member-specific FiLM parameters define low-overhead ensemble diversity in FiLM-Ensemble [2206.00050].

What distinguishes RGFiLM from those formulations is not the affine operator itself, but the explicit use of an empirical rarity score to regulate the influence of the FiLM-modulated state. In that respect it is closer to recent work in which FiLM is embedded inside higher-level routing or control structures. The deweathering MoFME architecture replaces full experts with feature-wise affine modulation branches routed by an uncertainty-aware router; routing calibrates how much each modulation expert contributes, while the downstream FFN weights are shared [2312.16610]. RGFiLM is structurally different—its gate interpolates between original and modulated representations rather than routing among multiple modulation experts—but both methods treat affine modulation as a substrate for conditional control rather than as a stand-alone conditioning primitive.

The contrast with FiLoRA is sharper. FiLoRA performs instruction-conditioned gating over grouped LoRA adaptation pathways,
$$
W' = W + \sum_{g \in \mathcal{G}} g_g(I_i)\,\Delta W_g,
$$
so natural-language instructions modulate reliance on predefined computation paths while keeping the task objective fixed [2602.02060]. This is group-wise/module-wise soft routing over low-rank adaptation branches, not feature-wise affine modulation. RGFiLM instead modulates hidden features directly via FiLM and then gates the resulting representation using a rarity signal. The two methods therefore share the goal of controllable internal reliance but operate at different levels of the model.

RGFiLM also differs from finer-grained modulation schemes that extend FiLM beyond feature-wise conditioning. SongEcho introduces Instance-Adaptive Element-wise Linear Modulation, where modulation parameters match the full hidden-state tensor and are refined using current hidden states before application [2602.19976]. Relative to such element-wise schemes, RGFiLM is architecturally simpler: the FiLM component is feature-wise, while the rarity gate is scalar per time step. A plausible implication is that RGFiLM prioritizes robustness and interpretability of context usage over maximal modulation granularity.

## 6. Limitations, scope, and prospective extensions

The reported evaluation is deliberately narrow. It uses synthetic detour injection with fixed magnitude, one geographic region, one time period, and one anomaly family. The rarity estimator relies on a Gaussian approximation over selected environmental variables and may be sensitive to limited coverage of environmental regimes or to context-domain shift. The paper also leaves several implementation details under-specified, including the exact architectures of the gate network $g$, the environment encoder $f_{\text{env}}$, and the sequence encoder $f_{\text{state}}$, beyond noting that OIL-AD-based variants share the same batch size, learning rate, and epochs to isolate the conditioning mechanism [2606.13311].

These constraints matter for interpretation. The method establishes that rarity-aware gating improves the F1–FPR trade-off in the reported maritime detour setting, but it does not demonstrate universality across contextual anomaly detection tasks. Likewise, the Mahalanobis-plus-chi-squared rarity score is presented as a simple and efficient choice rather than a definitive density estimator. The paper explicitly notes that other density-based scores could replace the chosen rarity metric [2606.13311].

From a broader FiLM perspective, several extension paths are suggested by adjacent literature, though they are not part of RGFiLM as reported. Fine-grained temporal or element-wise gating, as explored in SongEcho [2602.19976], could increase sensitivity to localized rare events. Routing among multiple modulation experts, as in MoFME [2312.16610], could separate distinct rare-context regimes. Instruction- or taxonomy-conditioned control over reliance, analogous to FiLoRA’s grouped gating [2602.02060], could provide a more explicit mechanism for distinguishing semantically central versus incidental contextual factors. These possibilities are extrapolations rather than claims of the RGFiLM paper.

In its reported form, RGFiLM is best understood as a modular representation-conditioning mechanism for imbalanced contextual regimes: FiLM supplies context-conditioned feature-wise affine transformation, rarity sharpens a scalar interpolation gate, and the resulting hybrid reduces false alarms without discarding context outright. Its principal contribution is therefore conceptual as much as empirical: rare context is treated neither as noise to ignore nor as signal to amplify indiscriminately, but as a cue for controlling the *confidence* of contextual modulation [2606.13311].

Source: https://www.emergentmind.com/topics/rarity-gated-feature-wise-linear-modulation-rgfilm