Anomalous Decision Discovery using Inverse Reinforcement Learning Ashish Bastola 1, Mert D. Pesé 1, Long Cheng 1, Jonathon Smereka 2, and Abolfazl Razi 1 Abstract Anomaly detection plays a critical role in Autonomous Vehicles (AVs) by identifying unusual behaviors through perception systems that could compromise safety and lead to hazardous situations. Current approaches, which often rely on predefined thresholds or supervised learning paradigms, exhibit reduced efficacy when confronted with unseen scenarios, sensor noise, and occlusions, leading to potential safety-critical failures. Moreover, supervised methods require large annotated datasets, limiting their real-world feasibility. To address these gaps, we propose an anomaly detection framework based on Inverse Reinforcement Learning (IRL) to infer latent driving intentions from sequential perception data, thus enabling robust identification. Specifically, we present Trajectory-Reward Guided Adaptive Pretraining (TRAP), a novel IRL framework for anomaly detection, to address two critical limitations of existing methods: noise robustness and generalization to unseen scenarios. Our core innovation is implicitly learning temporal credit assignments via reward and worst-case supervision. We leverage pretraining with variable-horizon sampling to maximize time-to-consequence, resulting in early detection of behavior deviation. Experiments on 14,000+ simulated trajectories demonstrate state-of-the-art performance, achieving 0.90 AUC and 82.2% F1-score - outperforming similarly trained supervised and unsupervised baselines by 39% on Recall and 12% on F1-score, respectively. Similar performance is achieved while exhibiting robustness to various noise types and generalization to unseen anomaly types. Our code will be available at: https://github.com/abastola0/TRAP.git I Introduction Autonomous Vehicles (AVs) represent a significant advancement in transportation systems. However, their safe deployment greatly depends on robust anomaly detection mechanisms to address unpredictable real-world scenarios [ 1 , 2 ] . While AI-driven perception systems excel in controlled environments, their reliability diminishes when encountering novel edge cases—a critical gap given that 67% of AV incidents stem from undetected behavioral anomalies in safety-critical situations [ 1 , 3 ] . Traditional anomaly detection methods face three fundamental limitations: (i) Dependence on manually crafted rules that fail to generalize across driving contexts in case of rule-based methods [ 4 , 2 ] , (ii) Model-based supervised approaches that generally require exhaustive labeled datasets are impractical for rare events [ 5 , 6 ] , and (iii) inability of unsupervised methods to distinguish safety-critical deviations from benign outliers in sequential decision-making processes [ 7 ] . Recent advances in Deep Learning (DL) methods have enabled data-driven anomaly detection through architectures such as Long Short-Term Memory (LSTM), LSTM-based autoencoders [ 8 ] , and multi-modal sensor fusion [ 3 ] techniques. However, these methods face scalability issues with high-dimensional data, often requiring additional pre-processing steps like Principal Component Analysis (PCA) to reduce dimensionality, which adds to the risk of losing nuanced features. Moreover, threshold tuning remains dataset-specific and labor-intensive, which is worsened by their interpretability issues as they mostly perform full trajectory-wise classification (assign labels to entire trajectory) [ 2 ] . Inverse Reinforcement Learning (IRL) addresses this by inferring reward functions from expert demonstrations, providing a principled framework for understanding decision-making patterns, facilitating anomaly detection [ 9 , 4 ] . While prior IRL-based approaches [ 9 ] demonstrated promise in controlled simulations, they often suffer from three key shortcomings: • Threshold Dependency : Manual tuning of normality thresholds limits adaptability to diverse driving scenarios, • Temporal Myopia : Temporal Myopia refers to bias when the model prioritizes more on immediate reward and short-term gains over long-term consequences. Fixed-horizon optimization fails to account for the delayed consequences of anomalous actions, • Sensor Noise Vulnerability : Performance degradation under real-world noise conditions like rain and sensor dropout. Our framework introduces three contributions to overcome these limitations: • We introduce TRAP (Trajectory-Reward Guided Adaptive Pretraining), a novel IRL-based anomaly detection framework that implicitly learns temporal credit assignment via reward and worst-case supervision, eliminating the need for extensively labeled datasets. Given expert demonstrations and worst-case rollouts, our method leverages variable horizon (unequal episode length) pretraining to detect behavioral deviations by implicitly maximizing the time to consequence. • We formulate rule-based anomaly labeling criteria to clearly define the joint anomaly threshold. This labeling allows us to evaluate our model’s performance in identifiable real-world anomalous scenarios such as tailgating, sudden braking, etc. Note that this labeling is only for validation, and we do not use this labeled supervision during training. We assume our method is generalizable to broad anomaly groups, with our labeled groups being a small subset that can be used for deterministic validation. • We generate a closed-loop simulation eligible anomaly trajectory dataset that can be used for various RL-based and supervised applications. Since we perform anomaly labeling purely based on the vehicle’s behavior in that specific trajectory after simulation, we prevent any kind of bias in the dataset generation. The contributed anomaly dataset—14,000+ trajectories with six anomaly categories—provides a benchmark for evaluating safety-critical AV behaviors under 8 noise conditions, addressing the scarcity of realistic scenarios noted before. We validate our approach through large-scale simulations in the MetaDrive [ 10 ] simulator due to its lightweight and high-speed performance. Our method demonstrates 12.5% higher recall than unsupervised baselines and 39% over supervised methods that are benchmarked on our dataset. II Related Work Anomaly detection originates from the broader challenge of outlier detection. In many cases, the datasets used for outlier detection are static, i.e., the data does not represent a sequence that evolves over time, but rather a fixed collection of observations. Various methods exist for detecting outliers, including supervised techniques [ 11 , 12 ] , distance-based approaches [ 13 , 14 ] , feature selection-based methods [ 15 ] , density-based methods [ 16 , 17 , 18 ] , model-based strategies [ 19 ] , and isolation-based techniques [ 20 ] . However, few methods have evaluated their feasibility over vehicle trajectory data to detect [ 9 ] sequentially occurring anomalous behaviors. II-A Inverse Reinforcement Learning for Anomaly Detection IRL aims to identify the underlying intent or the goal the agent is trying to reach by calculating intermediate reward estimates for each agent’s transition. The reward estimates are commonly modeled as a distribution using neural networks, which are gradually optimized using expert demonstrations. Applying IRL for anomaly detection is one of the theoretically appropriate ways to detect anomalies [ 9 ] . The idea is simple: first, estimate the reward baseline and specify a threshold for some deviation measure of a test trajectory from the reward distribution. One such method leveraging this approach for sequential data using Guided Cost Learning (GCL) [ 21 ] for reward learning includes a sequential anomaly detection framework [ 9 ] which uses policy optimization in online Reinforcement Learning (RL) settings. Using online environment interaction as part of online RL is significantly time-consuming, sample inefficient, unstable, and poses major computational limitations when dealing with training and simulation of high-dimensional data simultaneously. Moreover, pure online learning methods operate in a strictly forward manner without access to past trajectories, which limits the ability to apply strategies that optimize for longer time to anomaly detection. An IRL-based approach has also been used in diverse scenarios, such as Unmanned Aerial Vehicles (UAV), by providing a correction mechanism for the flight anomalies [ 22 ] . Li et al. [ 4 ] developed an outlier-robust IRL for detecting anomalous driving behaviors. Their joint IRL framework enables learning a common reward function that captures the behavior of the majority while simultaneously identifying outliers. All of these methods are, however, threshold-based and require threshold tuning to fit each specific application. Most of the code is not publicly released, and thus, cross-comparison is challenging; however, we reproduced the work by Oh et al. [ 9 ] , which is the most popular one for the purpose of comparison with our method. II-B Benchmarking and Dataset Considerations Developing suitable benchmarks is essential for assessing anomaly detection methods. However, most existing sequential anomaly benchmarks focus on objects, often overlooking anomalies in vehicle behavior. Bogdoll et al. [ 23 ] introduced AnoVox, described as the largest benchmark for anomaly detection in autonomous driving up to date. Their benchmark incorporates large-scale multimodal sensor data and spatial voxel ground truth, allowing for comparing methods independent of the sensors used. However, this benchmark [ 23 ] focuses more on anomalous objects than anomalous behavior like sudden turns, lane crossing, etc. The next limitation is the use of the CARLA simulator, which operates at a significantly lower frame rate than the MetaDrive simulator [ 10 ] , thereby posing a substantial constraint on both training and evaluation when comparing different baselines. Moreover, CARLA faces severe compatibility issues with recent Linux distributions [ 24 ] , thus making it less feasible. In our case, since we need to generate Worst-Case Terminus (WCT), which is the terminating condition leading to hazards, we need a large number of simulations for both expert and test trajectories and thus opt for the significantly more lightweight MetaDrive simulator, which offers satisfactory simulation quality without sacrificing speed. Other similar approaches like Fontanel et al. [ 25 ] utilize semantic segmentation to detect anomalous events such as traffic light abnormalities, unusual obstacles, hazards, etc. However, these can be formulated as general image recognition problems and are different from behavioral anomaly detection compared to ours. II-C Rule-based and symbolic approaches Beyond purely data-driven methods, rule-based approaches offer complementary strengths in anomaly detection. For instance, Chen et al. [ 26 ] explored integrating a common-sense knowledge base and predefined rules on driving behavior to enhance anomaly detection in autonomous vehicles. By leveraging symbolic rules, this approach mitigates the limitations of incomplete training data while enabling dynamic rule updates in an active learning fashion. In automotive cybersecurity, numerous attacks have exploited vulnerabilities in Controller Area Networks (CAN), the communication backbone between Electronic Control Units (ECUs) [ 27 , 28 ] . To counter such threats, rule-based methods such as One-Class Anomaly Detection Systems (OCADS) and association rules have been proposed to detect unknown and adversarial attacks [ 29 , 30 ] . However, we focus on detecting anomalies as high-level consequences of these attacks, allowing us to capture behavioral deviations indicative of a broader range of security breaches. While rule-based thresholding can be useful in directly observable feature spaces, its broader application remains limited. Our TRAP framework primarily relies on Inverse Reinforcement Learning (IRL). Yet, it integrates rule-based components to define worst-case termination scenarios, aligning with the conceptual foundation of rule-driven anomaly detection. This hybrid approach can extend to various anomaly types. However, purely rule-based methods often struggle with unseen cases, making them more suited as heuristic guides for trend identification or as complementary safeguards alongside more robust detection mechanisms. Fig. 1: Anomalies classified using a rule-based approach. We classify common anomaly scenarios for evaluation, such as sudden braking, frequent lane change, etc., by analyzing vehicle kinematics and environment information from the simulator. Fig. 2: Hybrid IRL-based reward guidance in supervised fine-tuning of variable horizon sampled trajectories labeled for worst-case terminus. By making easy labeling of the worst-case trajectories, we can mostly avoid labeling for specific anomaly groups, which is costly. Our approach implicitly learns to classify even minor behavior deviations by maximizing the time to consequence. III Problem Formulation III-A Simulation environment A flexible and efficient simulation environment is fundamental for reinforcement learning research, particularly when rapid prototyping and robust scenario customization are desired. The MetaDrive simulator [ 10 ] offers extensive configurability of scenarios, observations, and action spaces. MetaDrive’s integration with ScenarioNet [ 31 ] enables recording and replaying trajectories while also being closed-loop simulation eligible. To improve training efficiency and resource utilization, we use vectorized environments, which enable parallel training across multiple instances—a capability that MetaDrive supports at scale. By processing actions, observations, rewards, and termination signals in batches across independent environments, the vectorized environment significantly accelerates RL training compared to the regular single-environment training paradigm. We modify MetaDrive for our custom settings, where each vehicle observes its surroundings using 240 LiDAR lasers (also referred to as LiDAR channels or pulses that measure distance to objects), as well as 12 lane detectors (detect broken/solid lines) and 12 side detectors (detect sidewalks/solid lines). We opt for LiDAR state observation over top-down or visual observation due to computational efficiency and storage constraints, as we can approximate our state with only a few lasers. However, our trajectories are also separately stored in Scenario Description Language (SDL) as in ScenarioNet [ 31 ] , which lets us replay and derive the visual counterpart if required. Another major benefit of this simulator is the scenario customizability, which generates an almost unlimited number of scenarios using random sampling. Some of the most common ones in regard to popular road structures can be easily implemented. We can modify attributes such as lane width, number of vehicles, the gap of IDM-driven vehicles from the ego vehicle, and many more, thus leading to a new scenario every time we reset the environment. In our setup, each trajectory represents a unique scenario, created by randomizing the environment with a different random seed at every reset. III-B Rule based anomaly labeling In this paper, we assume that the only given perception information is in the form of LiDAR, as well as lane and side detectors. We make this assumption to accommodate for the fact that these sensors are available to most Level-3+ autonomous vehicles. Since the simulator also provides access to vehicle dynamics data, such as heading, acceleration etc., we utilize this additional information to generate trajectory anomaly targets through a set of rule-based labeling criteria (explained below) for evaluation purposes. However, during inference, we depend solely on perception data to determine whether a trajectory is anomalous. Below are the specific types of anomalies our labeling system detects: III-B 1 Zigzag driving patterns Given the vehicle heading \theta_{x} and \theta_{y} , we detect the curvature of trajectory at any given time as follows: k=\frac{\left|\theta_{x}^{\prime}\theta_{y}^{\prime\prime}-\theta_{y}^{\prime}\theta_{x}^{\prime\prime}\right|}{\left(\theta_{x}^{\prime 2}+\theta_{y}^{\prime 2}\right)^{3/2}} (1) where \theta_{x}^{\prime}=\frac{d\theta_{x}}{dt},\theta_{y}^{\prime}=\frac{d\theta_{y}}{dt},\theta_{x}^{\prime\prime}=\frac{d^{2}\theta_{x}}{dt^{2}},\theta_{y}^{\prime\prime}=\frac{d^{2}\theta_{y}}{dt^{2}} . We compute these time derivatives based on the temporal window size (40 steps in our case) and threshold this value based on human observation to detect high-frequency zig-zag patterns. III-B 2 Sudden Braking We calculate the velocity magnitude V_{i}=\left\|\mathbf{v}_{i}\right\| for every time point i . Acceleration can thus be calculated using finite differences over a specified window size given by: A_{i}=\frac{S_{i+w/2}-S_{i-w/2}}{w} where w is the window size and A_{i} is the acceleration at point i . We then compute the smoothed acceleration using a moving average filter as SA_{i}=\frac{1}{w}\sum_{k=-\frac{w-1}{2}}^{\frac{\mathrm{m}-1}{2}}A_{i+k} . Here, the index k runs between the half-windows -\frac{w-1}{2} to \frac{w-1}{2} , which ensures that the window is centered at i and includes w terms. This formula assumes that w is odd; if w is even, you might need to adjust the limits accordingly or redefine the window slightly to maintain symmetry. Then we identify sudden acceleration changes when \text{Indices}=\left\{i\mid SA_{i}<\theta\right\} , where \theta represents the braking threshold (which is typically a negative value indicating deceleration). III-B 3 Sudden turns Similarly, measuring lateral acceleration is the best way to detect sudden turns. Given a sequence of heading vectors \mathbf{h}_{i} (where i indexes the frame), the angular change \Delta\theta_{i} between consecutive heading vectors can be calculated as: \Delta\theta_{i}=\arccos\left(\frac{\mathbf{h}_{i-1}\cdot\mathbf{h}_{i}}{\left\|\mathbf{h}_{i-1}\right\|\left\|\mathbf{h}_{i}\right\|}\right) , where \mathbf{h}_{i-1} and \mathbf{h}_{i} are normalized to unit vectors before computing the dot product. We clip values to ensure the argument of across remains within its valid domain of [-1,1] to prevent undefined values due to floating-point precision issues. The lateral acceleration a_{\text{lat },i} based on the angular change and velocities is computed using: a_{\mathrm{lat},i}=\Delta\theta_{i}\times v_{i+1} where v_{i+1} is the magnitude of the velocity vector at frame i+1 , and \Delta\theta_{i} is the angular change from the previous frame. To identify frames where the lateral force exceeds a certain threshold \tau (such as a critical lateral acceleration that might indicate a risk of skidding or rolling in vehicle dynamics), we use: \text{ Indices }=\left\{i||a_{\text{lat },i}\mid>\tau\right\} Here, \tau is set to 0.8~\mathrm{m}/\mathrm{s}^{2} , but this value can be adjusted based on empirical data or dynamic conditions as required. Our choice is informed by the findings of [ 32 ] , where a 20% discomfort reporting threshold corresponded to a maximum lateral acceleration of 0.8~\mathrm{m}/\mathrm{s}^{2} . III-B 4 Frequent lane switching/driving between two lanes We detect this specific lane anomaly using lane break points. We trigger a boolean whenever a vehicle crosses a lane line and evaluate the crossing frequency to detect an anomalous vehicle trajectory. The moving average M of the data array D is computed using a convolution operation. This operation involves sliding a window of size w across D , and for each position, computing the average of the elements within the window given by: M=D*\frac{1}{w}\mathbf{1}_{w} , where, \mathbf{1}_{w} is a vector of ones with length w , * denotes the convolution operation and \frac{1}{w}\mathbf{1}_{w} is the kernel used for the convolution, effectively averaging the elements in each window of size w . This is central to smoothing the data, reducing noise, and helping to identify sustained patterns indicative of lane changes. We then identify indices where M exceeds 0.5 : \text{ Indices }=\left\{i\mid M_{i}>0.5\right\} We derive contiguous index ranges as Intervals and then filter these by computing the length of each interval based on a threshold \tau . \mathrm{Anomalies}=\{\ell(\mathrm{Int.})\mid\mathrm{Int.}\in\mathrm{Intervals~}\wedge\ell(\mathrm{Int.})>\tau\} (2) Here, \ell(\mathrm{Int.}) is the length of a specific interval and \tau is the user-validated threshold indicating a significant duration indicative of an anomaly in lane change behavior. III-B 5 Tailgating/Driving very close We use the simulator-provided proximity detectors to detect if any vehicles exist close to a specific threshold to detect these behaviors. Thus, we directly label trajectories for these categories with pure vehicle proximity bounds. IV Algorithm Design IV-A Reward Learning IRL aims at identifying reward estimates that explain expert behaviors and reason about their specific actions within the seen trajectories. Maximum Entropy IRL [ 33 , 21 ] has been the most popular way of modeling reward estimates. With Maximum Entropy IRL, we aim to learn the underlying reward function that explains expert behavior by assuming experts are exponentially more likely to choose higher-reward actions, but not always perfectly. It does this by finding the reward function that makes the expert’s actions most probable while also maximizing randomness (entropy), so it doesn’t assume any more than what the data shows. In other words, this can be explained using a Boltzmann distribution as follows: p(\tau|\theta)=\frac{1}{Z}\exp(R(\tau|\theta)) (3) However, one major limitation of this approach is the assumption that the expert is optimal, which does not apply to most cases, even for well-trained policies or IDM (Intelligent Driver Model) policies. The notion of optimality indirectly biases the learned reward estimate, which results in even poor performance when a new policy is trained with this reward estimate, or simply detecting anomalies based on this reward, flaws the binary estimate. We thus implement the trajectory-ranked reward extrapolation approach [ 34 ] to derive the reward function. With this approach, we first position the expert policy with varying noise intensity and then rank the expert rollouts \tau_{1},\ldots,\tau_{m} , from worst to best. Thus with a reward estimate \hat{r}_{\theta}(s) parameterized by \theta , we have \sum_{s\in\tau_{i}}\hat{r}_{\theta}(s)<\sum_{s\in\tau_{j}}\hat{r}_{\theta}(s) when \tau_{i}\prec\tau_{j} . The reward function can then be trained in a supervised fashion with ranked demonstrations using the generalized loss function below: \mathcal{L}(\theta)=\mathbf{E}_{\tau_{i},\tau_{j}\Pi}\left[\xi\left(\mathbf{P}(\hat{J}_{\theta}(\tau_{i})<\hat{J}_{\theta}(\tau_{j})),\tau_{i}\prec\tau_{j}\right)\right] (4) where, \Pi is a distribution over demonstrations, \prec is the preference ordering between trajectories, \xi is the binary classification loss function and \hat{J} is a discounted return defined by a parameterized reward function \hat{r}_{\theta} , i.e. \hat{J}_{\theta}(\tau)=\sum_{s\in\tau}\hat{r}_{\theta}(s) The probability \mathbf{P} signifies this hierarchy between the trajectories and can be obtained using a softmax-normalized distribution. \mathbf{P}\left(\hat{J}_{\theta}(\tau_{i})<\hat{J}_{\theta}(\tau_{j})\right)\approx\frac{\exp\sum_{s\in\tau_{j}}\hat{r}_{\theta}(s)}{\exp\sum_{s\in\tau_{i}}\hat{r}_{\theta}(s)+\exp\sum_{s\in\tau_{j}}\hat{r}_{\theta}(s)}, (5) This objective is trained by predicting whether one trajectory is preferable to another, with the label being the hierarchical ordering that we already know based on the added noise to expert policy. The output of this training is the learned reward function \hat{r}_{\theta}(s) . IV-B Worst-Case-Terminus Defining an anomaly is a significant challenge, specifically in autonomous driving scenarios, due to dynamic factors such as environmental conditions, road user behavior, sensor limitations, etc. A more reasonable way to define an anomaly is the deviation that leads to potential hazards or system failures. Anomalous behaviors that do not lead to any hazard are of significantly low interest, especially in safety-critical scenarios such as autonomous driving. Thus, we define worst-case terminus as the utmost severe consequence that a vehicle might have to suffer if it behaves abnormally. In our case, we define vehicles crashing with objects (such as traffic cones, walls, other vehicles etc.) and driving off the road leading to simulation termination as worst-case terminus. One benefit of defining worst-case-terminus is that these are limited, unlike anomalies, which can appear in different forms every single time and are explicitly hard to dictate. This helps us generate binary labels if the worst-case terminus is reached for each expert trajectory, essentially turning into a supervised learning setting. In our implementation, we thus generate these crashes by different ways of traffic density variation and adding noise to the expert policy. Fig. 3: Trajectory-Reward fusion to generate DistilBERT compatible embedding for binary classification Fig. 4: t-SNE plot of anomalous segments of test trajectories labeled using the rule-based approach described in Section III-B . Figure shows distribution shift with added noise(type: Composite2 high) Fig. 5: Figure demonstrating the expert anomaly composition formation. We form four different composition groups by removing trajectories corresponding to the increasing majority and minority groups. IV-C End-Clipping & Variable Trajectory Sampling Defining the worst-case terminus simply does not allow us to detect anomalies, and training for crash and no-crash on its own is a trivial problem to solve, considering the early deviation detection objective. However, we take a different approach and intend to maximize the time for the worst-case-terminus. This induces the side effect of detecting the change from normal to abnormal behavior that leads to severe consequences. This is implicitly achieved with variable sub-trajectory sampling, where we break demonstrations into different trajectories of high variance in lengths. This strategy needs to be applied at the dataset level. Let D=\{\tau_{i}\}_{i=1}^{N} be the training trajectory datasets containing worst-case-terminus and let each trajectory have length L_{i} . The max-length and min-length of trajectories in the dataset are represented by L_{\max}=\max_{i\in D}L_{i} and L_{\min}=\min_{i\in D}L_{i} . The trajectory sampling steps are as follows: Step 1: Crop each trajectory from the end with a random length L_{rand}\sim\mathrm{Uniform}(\min(L_{min},L_{thres}),L_{i}) , where L_{thres} is the max length the cropped trajectories can have. Step 2: Expand each trajectory multiple times. Let each trajectory be defined by \tau=(o,a,r,l) where o is the observation, a is the action, r is the reward, and l is the binary label for the worst-case-terminus. Note r here is obtained using reward inference of the state observation o from the learned reward estimate \hat{r}_{\theta} . Let \mathcal{L} be the set of \eta integers sampled uniformly at random from the range [2,n) such that \mathcal{L}\subseteq\{2,3,\ldots,n-1\},\hskip 10.00002pt|\mathcal{L}|=\min(\eta,n-2) . Then for each k\in\mathcal{L} , we expand the trajectory as \tau_{k}^{\prime}=(o[:k],a[:k],r[:k],l). We do this for every trajectory with worst-case-terminus or with label = 1 as follows: D^{\prime}=\bigcup_{\tau\in D;l=1}\text{expand traj}(\tau) (6) IV-D Finetuning DistilBERT We use DistilBERT [ 35 ] , which is a compact and efficient version of BERT (Bidirectional Encoder Representations from Transformers) [ 36 ] language model, as our anomaly detection module for sequential classification. Given the specially configured trajectories from our new dataset D^{\prime} , we generate embeddings for each timestep corresponding to these trajectories. Note that these trajectories already have reward values estimated from our reward function \hat{r}_{\theta} , which is learned using IRL through the minimization of equation ( 4 ). We now define a projection feedforward network \Psi that takes state, action, and reward estimate and generates an embedding token h , i.e., is compatible with DistilBERT’s embedding dimension. We finally finetune DistilBERT to classify each trajectory of embedding token h for the corresponding label l . \textbf{h}=\Psi(o,a,r) (7) Thus the final training dataset D^{\prime} is given by D^{\prime}=D\cup D^{\prime} . Note that this trick directly contributes to optimization for time maximization and is not a part of dataset generation by itself. Note, during inference, the test trajectories may or may not include crash points. Naturally, our model is likely to flag these crash points as anomalies, which is expected behavior. However, since our training objective is to detect such worst-case endpoints, including them during evaluation can introduce bias. To ensure a fair assessment of the model’s performance, we trim the final steps of each trajectory, thereby removing this bias and allowing for a more balanced evaluation. Fig. 6: ROC curve demonstrating the performance comparison of some widely used anomaly detection methods trained with WCT. IV-E Implicit optimization strategy Our method is related to Receding Horizon Optimization (RHO) [ 37 ] , also known as Model Predictive Control (MPC), which is a feedback control strategy that repeatedly solves a finite-horizon optimization problem through online learning. An optimal control sequence is computed over a prediction horizon after the first control action is applied, which shifts the horizon step forward. One popular way to deal with piecewise continuous nominal control trajectory in such problems is using variable horizon length in each iteration [ 38 , 39 ] , which aligns with our strategy. Another analogy that includes RHO is the state estimation whereas our approach implements reward-guided embedding projection. However, the core optimization in our implementation occurs through temporal reward decomposition and variable-length trajectory embedding. TRAP learns temporal relationships through data-driven reward shaping rather than explicit trajectory optimization. This makes it more adaptable to unknown anomaly patterns while maintaining computational efficiency. Specifically, our approach implicitly solves three interconnected optimization processes: IV-E 1 Temporal Credit Assignment When cropping trajectories to random lengths, we essentially solve the following: \max_{\theta}\;\mathbb{E}_{L_{i},\tau\sim D^{\prime}}\bigg[\sum_{t=1}^{L_{i}}\gamma^{t}\hat{\tau}_{\theta}(s_{t})+\lambda\cdot\mathrm{KL}\left(p(\tau\mid\theta)\,\|\,p_{\text{expert}}(\tau)\right)\bigg] (8) where, L_{i} is a random trajectory length and L_{i}\sim\mathcal{U}[L_{\min},L_{\text{thres}}] with both L_{min} and L_{thres} being discrete valued. This forces the reward function \hat{r}_{\theta} to: • Prioritize early warning signs in short segments. Since L_{i} is randomly sampled and can be small, the model must extract information from early states and weight accordingly to incentivize early timesteps. • Maintain temporal consistency across partial observations. To generalize across random-length segments, r_{\theta} must be weighted to behave consistently in time, even with partial observations. This is further strengthen by the possibility of overlap between these segments and reward structure must match regardless. • Balance immediate rewards against long-term consequences. Much like the weighting effect of \gamma^{t} , our approach through whole sequence modeling learns to tradeoff short and long term behavior. The KL term penalizes divergence from the expert distribution which further anchors the trajectory level structure and prevents from overfitting to short-term patterns if those cause long-term divergence from expert thus maintaining balance among all three steps. This in our case is attained by the minimizing the cross-entropy loss. IV-E 2 Worst-case anticipation and implicit horizon coupling The trajectory clipping creates an adversarial optimization landscape: \min_{\phi}\mathbb{E}_{r\in D^{\prime}}\left[1_{\mathrm{WCT}}\cdot\exp\left(-\alpha\sum_{t=1}^{k}\hat{r}_{\theta}\left(s_{t}\right)\right)\right] (9) where \phi are the DistilBERT parameters. This penalizes the model exponentially when high-reward trajectories (reward scaled) lead to crashes (false negatives) or low-reward trajectories avoid crashes (false positives). Moreover, the variable lengths paired with clipping create an implicit relationship between detection time t_{d} and the remaining time to terminus T_{\text{WCT}} given by: \mathrm{P}\left(\mathrm{WCT}\mid\tau_{1:t_{d}}\right)\propto\exp\left(-\beta\frac{T_{\mathrm{WCT}}}{t_{d}}\sum_{k=1}^{t_{d}}\hat{r}_{\theta}\left(s_{k}\right)\right) (10) This automatically weights early detections more heavily when T_{\text{WCT}} is small. IV-E 3 Multi-scale feature learning Variable lengths essentially induce a curriculum learning effect by asking if the trajectory segment (ahead in time) anticipates the future worst case: \mathcal{L}_{\mathrm{emb}}=\sum_{k=1}^{K}w_{k}\cdot\operatorname{CE}\left(\Psi\left(o_{:k},a_{:k},r_{:k}\right),l_{\mathrm{WCT}}\right) (11) where weights w_{k} increase with segment length k and CE is the cross entropy. This makes the model focus on local patterns for early detection of deviations, integrates global context for final classification and learns length-invariant representations. V Experiments We compare both supervised and unsupervised methods in our evaluation. Our method is supervised for the worst-case terminus but remains unsupervised for anomaly detection. For the purpose of our evaluation, we consider three of the most popular yet powerful unsupervised anomaly detection models, i.e., One-Class SVM (OC-SVM) [ 40 ] , Isolation Forest (IForest) [ 20 ] , and Local Outlier Factor (LOF) [ 16 ] , and three powerful supervised classifiers, namely Long short-term memory (LSTM) [ 41 ] , Decision Tree [ 42 ] , Supervised Autoencoder (SPAE) [ 43 ] . We also consider the popular IRL based Sequential Anomaly Detection algorithm by Oh et al. [ 9 ] (Seq-AD). For a fair comparison, since worst-case terminus and reward modeling are trained on expert scenarios, we train supervised methods on expert trajectories for the worst-case terminus and evaluate them on the same test dataset. Similarly, we train unsupervised methods on expert trajectories, which, despite being imperfect and containing anomalies, provide sufficient data for learning the underlying anomaly structure. We utilized 5,000 expert trajectories to train our model. For non-sequential methods, including both supervised and unsupervised approaches such as Decision Trees and SPAE, we concatenated and flattened state-action data to generate compatible inputs. Given the intensive computational requirements of some unsupervised methods (e.g., OC-SVM), processing large datasets is challenging. However, we found that using more than 5,000 trajectories did not significantly improve results. For a more comprehensive assessment, we conducted an evaluation of 14,000+ trajectories. These trajectories have the following characteristics: • Can be replayed and simulated in closed form • Include anomaly labeling for each trajectory This expanded dataset allows for a more robust evaluation of our model’s performance across a diverse set of scenarios. Fig. 7: t-SNE plot of 14000+ full test trajectories labeled using the rule-based approach described in III-B for evaluation. Figure shows distribution shift with added noise (type: Composite2 high) TABLE I: Comparison of TRAP with various Anomaly Detection methods Models F1-Score AUC Precision Recall MCC Accuracy OCSVM 0.611 - 0.503 0.777 0.185 0.564 IForest 0.688 - 0.949 0.539 0.592 0.784 LOF 0.498 - 0.724 0.379 0.313 0.663 LSTM (Trained WCT) 0.656 0.766 0.925 0.508 0.552 0.765 Decision Tree (Trained WCT) 0.029 0.51 0.838 0.015 0.071 0.565 SPAE (Trained WCT) 0.37 0.604 0.878 0.234 0.322 0.649 Seq-AD (Final) 0.411 - 0.318 0.579 -0.491 0.269 Ours (Final)** 0.822 0.90 0.754 0.902 0.667 0.828 Fig. 8: Figure shows the percentage of anomalies identified by unsupervised (on the left) and semi-supervised methods (on the right) on test trajectories. TABLE II: Performance Comparison: F1 Scores and Mathews Correlation Coefficient (MCC) Noise Type Metric OCSVM Isolation Forest LSTM SPAE Ours* Low Med High Low Med High Low Med High Low Med High Low Med High Precipitation F1 0.496 0.597 0.603 0.693 0.710 0.747 0.611 0.611 0.611 0.050 0.050 0.050 0.824 0.826 0.831 MCC 0.174 0.041 -0.075 0.596 0.610 0.640 0.515 0.515 0.515 0.094 0.094 0.094 0.672 0.677 0.688 Distance F1 0.596 0.595 0.594 0.707 0.711 0.716 0.611 0.611 0.611 0.051 0.051 0.051 0.822 0.822 0.822 MCC 0.161 0.163 0.165 0.608 0.611 0.616 0.515 0.515 0.515 0.095 0.095 0.095 0.667 0.667 0.667 Ambient F1 0.611 0.611 0.611 0.781 0.834 0.617 0.638 0.714 0.626 0.049 0.038 0.004 0.819 0.814 0.803 MCC 0.000 0.000 0.000 0.669 0.696 0.101 0.537 0.607 0.414 0.094 0.080 0.031 0.661 0.652 0.630 Spurious F1 0.611 0.592 0.611 0.698 0.750 0.813 0.611 0.611 0.610 0.050 0.050 0.051 0.822 0.824 0.829 MCC 0.178 -0.067 -0.026 0.599 0.645 0.704 0.515 0.515 0.515 0.094 0.094 0.095 0.668 0.672 0.681 Composite1 F1 0.611 0.611 0.611 0.802 0.825 0.612 0.638 0.714 0.636 0.049 0.036 0.004 0.820 0.821 0.824 MCC 0.0 0.0 0.0 0.690 0.674 0.042 0.537 0.606 0.417 0.094 0.078 0.029 0.663 0.666 0.671 Gaussian F1 0.599 0.605 0.619 0.752 0.782 0.819 0.612 0.613 0.618 0.051 0.050 0.050 0.822 0.822 0.822 MCC 0.199 0.233 0.281 0.646 0.672 0.710 0.516 0.517 0.521 0.095 0.094 0.094 0.667 0.667 0.667 Dropout F1 0.611 0.611 0.611 0.845 0.865 0.873 0.611 0.611 0.611 0.051 0.050 0.051 0.856 0.873 0.877 MCC 0.0 0.0 0.0 0.741 0.768 0.778 0.515 0.515 0.515 0.095 0.094 0.095 0.739 0.773 0.782 Composite2 F1 0.611 0.611 0.611 0.859 0.874 0.853 0.612 0.613 0.615 0.051 0.049 0.050 0.859 0.872 0.875 MCC 0.0 0.0 0.0 0.759 0.779 0.729 0.516 0.517 0.518 0.095 0.093 0.093 0.744 0.771 0.778 V-A Noise Robustness We introduce eight novel noise groups designed to simulate real-world conditions [ 44 ] affecting LiDAR sensor readings. These noise types are applied to the measurements of 240 LiDAR sensors in various forms: • Precipitation noise simulates rain-induced light refraction and time delay [ 45 , 46 ] . • Distance noise represents inaccuracies in distance measurements due to sensor errors [ 47 ] . • Ambient noise emulates environmental factors such as fog, sunlight, dust, and humidity [ 48 ] . • Gaussian noise introduces random noise affecting the entire beam uniformly [ 45 ] . • Dropout noise models sensor malfunctions by randomly zeroing out measurements [ 47 , 49 ] . Since these noise types are applied individually to each LiDAR beam, we maintain precise control over their impact on the overall sensor readings. Additionally, we define two composite noise configurations that combine fundamental noise types in distinct ways: • Composite1 : A combination of precipitation, distance, ambient, and spurious noise. • Composite2 : A mix of Gaussian, dropout, and spurious noise. These noise models enable a more comprehensive evaluation of LiDAR sensor robustness under real-world perturbations. We note the rather unusual behavior of increased accuracy with increased noise which is not uncommon in unsupervised evaluation. This behavior is also observed in other models under comparison. The proposed results indicate the following: • Our method proves to be inherently robust to certain types, thus letting us perform better by ignoring some inherent irrelevant variations. • Noise, in many cases, can enhance separation and the contrast between normal and anomalous patterns, making anomalies easier to detect. This increased distribution separation can also be visualized in Figure 7 on the right (noisy) compared to the normal on the left. Another key point to note is that recall is more valuable when missing anomalies are costly (e.g., missing to detect a vehicle driving in the wrong lane). Precision is more valuable when false alarms are costly (e.g., making too many false predictions might induce consequences). In ours and most anomaly detection scenarios, high recall is prioritized since missing anomalies can have severe consequences. However, a balance with precision is also needed to avoid too many false positives. In our evaluation, as shown in Table I , we can observe that our method achieves significantly higher recall compared to all the other methods while also maintaining reasonable precision. Isolation forest, even having higher F1 compared to other methods, seems to have significantly lower recall, which explains that it misses a significantly larger proportion of anomalous events. Isolation Forest, despite having a higher F1 score than other methods, exhibits significantly lower recall, indicating it misses a larger proportion of anomalous events. V-B Normal Trajectory Evaluation without additional noise This is the most basic mixed training configuration, where no consideration is given to the types of anomalies present in the expert trajectories. Additionally, no extra noise is introduced, and evaluation is performed in its raw form. The key difference between expert and test trajectories here lies in their sampling from different seed ranges, leading to variations in distribution. As shown in Table I , TRAP demonstrates a significant performance advantage, achieving an F1 score improvement of +0.134. Isolation Forest, despite its high precision, only makes correct predictions when highly confident. However, its low recall suggests it misses a large number of true positive cases, which is costly. Furthermore, Sequential IRL performed poorly, often making predictions opposite to the expected outcome, as indicated by its MCC score. Decision Tree exhibited near-random performance, yielding the lowest F1 score overall. In contrast, LSTM outperformed all other supervised approaches, achieving the highest AUC among supervised models, indicating its effectiveness in this setting. Figure 8 illustrates the percentage of anomalies detected across different anomaly groups in the test trajectories. Seq-AD performs well in the braking scenario but fails in nearly all other cases. Notably, despite applying a grid search to optimize the threshold for maximum F1 score, Seq-AD still under-performs compared to other methods. Similarly, OCSVM achieves high performance in the braking scenario, even surpassing TRAP, but performs worse than our approach in all other cases. Overall, TRAP demonstrates a significant performance advantage across most scenarios, highlighting its robustness in anomaly detection. V-C Expert trajectories biased to specific anomaly types We perform additional experiments to evaluate how trajectories pertaining to certain anomalies might influence the predictions on the test trajectories, as shown in Table III . We consider another approach where an expert dataset might include certain types of anomalies while missing out on some others. We consider 4 different approaches to account for this: • Train by omitting 2 majority anomaly groups from the expert • Train by omitting 3 majority anomaly groups from the expert • Train by omitting 2 minority anomaly groups from the expert • Train by omitting 3 minority anomaly groups from the expert This is more practical in the real world, where normal driving behaviors might not include some of the serious or even menial anomaly types, while others are more apparent. For instance, braking and sudden turns might be more apparent, while gradual drifting on straight roads might not be, which might result from alignment issues or even a consequence of cyber-attacks on the vehicle. The group configuration is also shown in Figure 5 . In this evaluation, TRAP performed better in 3 of the 4 different cases while achieving very close performance to Isolation forest in 2/5 Majority removal configuration. TABLE III: F1-Scores for Different Group Removal Configurations Models 2/5 Majority removal 3/5 Majority removal 3/5 Minority removal 2/5 Minority removal OCSVM 0.719 0.719 0.657 0.629 IForest 0.889 0.849 0.801 0.692 LOF 0.727 0.725 0.723 0.731 LSTM (Trained WCT) 0.416 0.736 0.611 0.617 Ours ** 0.869 0.871 0.820 0.732 TABLE IV: Impact of noise addition on trajectory displacement Noise Type Intensity MSE MAE Mean Displacement DTW Distance Precipitation Low 0.000433 0.000453 0.116576 34.97262 Med 0.002634 0.002757 0.516898 155.06934 High 0.007308 0.007664 0.955337 286.60100 Distance Low 0.000469 0.000703 0.124870 37.460857 Med 0.000470 0.001015 0.130962 39.288517 High 0.000473 0.001563 0.142240 42.672092 Ambient Low 0.022225 0.027014 2.145561 643.6665 Med 0.066651 0.081020 3.772315 1131.6945 High 0.111125 0.135086 4.885277 1465.5833 Spurious Low 0.000167 0.002498 0.211202 63.360645 Med 0.001998 0.014988 0.740258 222.077550 High 0.007499 0.037496 1.437241 431.172200 Composite1 Low 0.02321 0.030438 2.244333 673.3000 Med 0.07130 0.097181 4.041133 1212.3397 High 0.12451 0.171568 5.434584 1630.3752 Gaussian Low 0.000524 0.004846 0.216445 64.93355 Med 0.000688 0.009220 0.323226 96.96787 High 0.001343 0.017945 0.549140 164.74188 Dropout Low 0.042195 0.043958 2.415912 724.7734 Med 0.126722 0.132006 4.202101 1260.6304 High 0.211215 0.220021 5.428938 1628.6816 Composite2 Low 0.042885 0.050559 2.551467 765.4401 Med 0.129203 0.150395 4.605394 1381.6184 High 0.219454 0.255462 6.214792 1864.4377 VI Conclusion In this paper, we introduced a novel reward-guided pretraining approach for detecting anomalous driving behaviors in autonomous vehicles. Our method surpasses conventional and recent IRL-based anomaly detection techniques, demonstrating strong generalization even when trained on expert trajectories with biased anomaly composition. By leveraging worst-case terminus training, we jointly optimize extrapolated rewards with variable-horizon trajectory sampling, implicitly maximizing the time of consequence while reshaping the reward structure within the embedder. This eliminates the need for extensively labeled anomaly datasets while achieving superior performance. Comprehensive evaluations across diverse noise configurations and anomaly-grouped expert training validate the real-world applicability of our approach. Additionally, our method provides interpretable insights into the reward structures guiding driving behavior. Future work can extend this framework to more complex driving scenarios.