fa
Feedback

فریب کلاهبرداران را نخورید! تل‌متریو این کانال‌ها را شناسایی و برچسب‌گذاری می‌کند 👉 برای مشاهده برچسب، اشتراک تهیه کنید

Data eXplore : Data Science, ML, Big Data, LLMs and AI Security

Data eXplore : Data Science, ML, Big Data, LLMs and AI Security

رفتن به کانال در Telegram

Exploring Data Science, Big Data Analytics & Visualization, ML/DL, Neural Networks, LLMs with GitHub, Kaggle, HuggingFace and some white papers by big institutions. Not just data, but science behind data Paid project? premodi@zohomail.in ★ @DataML

نمایش بیشتر
کشور مشخص نشده استفناوری و برنامه‌ها50 641
588
مشترکین
+224 ساعت
+17 روز
-130 روز
آرشیو پست ها
The human ability to write secure code is indeed weak. People are good at other things, and AI is good at other things. The top engineers will still be there, happily watching as the AI fixes and implements things, while they just make sure it doesn't drift or become overly complex. 90% will be laid off, yes. IT will remain a valuable field, but not for everyone. So, are we at the point where we no longer trust humans to write code for critical systems or do we not trust AI yet?
22 نوامبر, 00:10

I have 2 debit cards, 2 credit cards, 1 metro card, 1 PAN card, 1 driving licence, 1 Voter ID card, and 1 Aadhaar card. A total of 9, and most of you have more than 10. Why doesn't any startup do something to solve this? There should be only one or two cards: One with all your IDs like Aadhaar, PAN, DL, and Voter ID. And another for all your banking-related cards like debit, credit, and others. And when you get another card, you can simply load it to one permanent banking card. There is no one in the market who's doing this.
20 نوامبر, 01:01
20 نوامبر, ~01:01

How to promote banking products and avoid turning communication into spam with ML System? Imagine a bank with dozens of produ
How to promote banking products and avoid turning communication into spam with ML System? Imagine a bank with dozens of products: current accounts, payment processing, accounting, payroll services, insurance, and safe deposit boxes. Each of these needs to be promoted and business targets need to be met. But there's a problem, all these products are needed by the same customers. Here's how the promotion process usually looks: A manager and analyst come up with a hypothesis → they select an audience based on business filters (e.g., "clients with a turnover of more than X) → they upload the list to Excel → they launch a mailing campaign. The problem is that all the other product teams work the same way. As a result, the same client can receive several offers in a single week: to connect payment processing, sign up for accounting services, open a deposit, or use a new service for businesses. Each communication may seem logical on its own, but together they start to be perceived as spam. This reduces customer loyalty and increases churn. For a bigger bank, If we increased the number of connections by 1%, we would: } generate tens of millions in additional profit; } reduce the manual workload of managers by 10%; } reduce churn and increase customer lifetime value (LTV). To solve this problem, we decided to use a Next Best Action (NBA) engine. Using analytics and machine learning, it determines which next action will be most beneficial for the customer. At any given moment, the system helps to understand: ~ Which product is currently relevant to the customer? ~ Which channel is best to communicate with them through? ~ Is it even worth contacting them right now? In other words, instead of maximizing the number of mailing campaigns, NBA aims to increase the value of each individual communication. I will share more details about building the ML model in future posts. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
18 نوامبر, 22:17

Evolution of Attention: Era of Hybrid Models This concludes my series of posts of linear attention. Following the S4 architec
Evolution of Attention: Era of Hybrid Models This concludes my series of posts of linear attention. Following the S4 architecture, several stages of development have occurred: 1️⃣ Mamba : For the first time, Mamba made the parameters dependent on the input. This allows the model to store context in memory and adaptively decide what to forget and what to remember, depending on the context. Therefore, when selectively copying information, it outperforms the standard S4. Main drawback: Over time, the memory accumulates not only useful information but also errors. When the model tries to retrieve something, it receives not a clean signal, but a mixture of data and noise (retrieval error). This is especially noticeable in long sequences. 2️⃣ DeltaNet : DeltaNet was able to solve the problem of "dirty memory." Each time the model adds new information, it performs a check: • It retrieves the current representation from memory along with the accumulated noise. • It assesses how different it is from what is needed. • It corrects the state by subtracting the error and writing a more accurate value. The process is similar to a gradient descent step: we reduce the error by gradually adjusting the state of the memory. In this way, the memory ceases to be a passive storage and becomes a dynamic system that can clean itself. 3️⃣ Hybrid Models : This is the direction that many major labs have taken, as they allow combining the strengths of different approaches. For example, Kimi Linear, Qwen3 Next, and MiniMax-Text-01 combine linear attention with standard attention: • Linear attention - excels at handling long sequences, puts minimal strain on memory, and maintains the overall picture. • Standard attention - accurately finds the necessary tokens and works with details. Thanks to this, the system can work with the global context, focus locally, and avoid being overwhelmed by noise. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
17 نوامبر, 21:32

Evolution of Attention: S4 and Working with Long Context I'm continuing the series of posts about the journey of linear atten
Evolution of Attention: S4 and Working with Long Context I'm continuing the series of posts about the journey of linear attention. After RWKV, it became clear: TO move away FROM expensive Attention, memory needs to be able to work with long contexts. It's not enough to simply store information; it needs to be updated over time. Parallel to RWKV, the State Space Models (SSM) architecture was developing. Initially, SSMs came from physics and mathematics: they were used to describe systems with memory. x'(t) = Ax(t) + Bu(t) y(t) = Cx(t) + Du(t) What happens inside: The input signal is transformed → it is mixed with the current state (memory) → the state is updated → the output is formed from it. In other words, memory becomes not just a sum of the past, but a dynamic state. Since language is a discrete sequence, a parameter Δ was added to SSMs. It is responsible for the "time step" between tokens: how much the memory should change when transitioning from one token to another. One of the first successful implementations of SSM was the S4 architecture. It introduced two important changes: • Special initialization of the matrix A (HIPPO): This allowed the model to better retain long contexts and not forget information. • Parallel computations through convolutions: This avoids calculating the state for each token sequentially (as in RNNs). This model could work with long sequences, but it still lacked flexibility: the model processed each input token in the same way. I will explain how this shortcoming was corrected in the next post. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
16 نوامبر, 21:31

Hello, Coding Family! Prem here, Admin. First of all, Saal Mubarak! Nutan Varshabhinandan! A very happy New Year 🪔❤️ For those who don't know, I'm from Gujarat, where we celebrate our New Year the day after Diwali and today is that special day! 😊 It's been almost 6 months since I last actively connected with this channel. Life got a little busy, i think too much with a new job, work, and everything that comes along with it. But yes, even if the developer goes offline, the project doesn't get abandoned! We all know that 😁 I'm happy to be back and looking forward to connecting with you all again. On this Gujarati New Year, I wish everyone in our coding family a year full of clean code without bugs, New growth opportunities and successful projects. Now, let's break this silence I want to hear from you all again. What's going on? How have you been? What's new in your tech journey? Are you studying, working, building something, or Exploring? I'll be happy if you drop a comment and say hello and let's reconnect if this community is still not dead! ❤️ Saal Mubarak!
09 نوامبر, 16:04

While you light up for Diwali, engineers are working so the celebration never stops. The lights in your home stay steady because someone is monitoring the grid through the night. Your phone works, your UPI payment goes through, and your call with family doesn't drop because someone is still fixing what breaks. Your festival crowd stays safe because someone is monitoring bridges, flyovers, and metro stations under heavy load. Your factories, plants, and pumps keep running because someone is on shift. Your kitchen gas keeps burning and you're getting fuel because someone keeps refineries and gas supply running. And your hospitals are still running because someone is ensuring biomedical equipment works. Because not everyone gets to enjoy the festival. Someone is still fixing a transformer, someone is still finding a bug in the system, and someone is still on duty so you don't have to worry. To every "someone" working this Diwali, in software, power, energy, telecom, civil, mechanical, chemical, and beyond, they are the quiet light behind our celebration. Thank you for keeping the world running while it celebrates. Happy Diwali! 🪔
- Admin
06 نوامبر, 07:36

Dynamic Adjustment of Batch Normalization How to Avoid "Breaking" Your Model Due to Data Drift? Batch Normalization can signi
Dynamic Adjustment of Batch Normalization How to Avoid "Breaking" Your Model Due to Data Drift? Batch Normalization can significantly speed up training convergence, but in production, it can become a hidden trap when dealing with non-stationary data drift. The most common mistake is to rely on frozen moving averages, even when the data distribution has already changed. ➡️ Why Standard BN Fails with Drift? During training, BN calculates the mean and variance based on the current batch. During inference, it uses frozen moving averages accumulated during the training process. As long as the data is stable, everything works fine. However, as soon as the distribution starts to drift (non-stationary drift), these fixed statistics no longer reflect the actual data. Internal representations shift, metrics drop, and you spend a long time trying to find the cause. An example from practice: a model for anomaly detection in time series, after retraining on a new regime, "remembered" it in the BN layers. When the data returned to the old pattern during inference, the BN statistics became invalid, and the false positive rate increased, even though the model itself was not overtrained. ➡️ Adaptive Updates During Inference Instead of rigidly fixing the moving averages, you can implement dynamic adjustment directly during inference. The idea is to measure the drift using a normalized deviation (Z-score) and adjust the update rate. The greater the discrepancy between the current batch and the accumulated statistics, the faster you adapt the BN. An example in PyTorch: we replace the fixed momentum with a drift_factor that increases when there is a large deviation (batch_mean - running_mean) / std.
class AdaptiveBatchNorm(nn.BatchNorm1d):
    def init(self, num_features, eps=1e-5, momentum=0.1, drift_factor=0.5):
        super().init(num_features, eps)
        self.base_momentum = momentum
        self.drift_factor = drift_factor

    def forward(self, x):
        if self.training:
            return super().forward(x)
        with torch.no_grad():
            batch_mean = x.mean(dim=(0,))
            batch_var = x.var(dim=(0,), unbiased=False)
            drift = torch.abs((batch_mean - self.running_mean) / (torch.sqrt(self.running_var + self.eps) + 1e-8))
            adaptive_momentum = self.base_momentum  (1 + self.drift_factor  drift.mean())
            self.running_mean = (1 - adaptive_momentum)  self.running_mean + adaptive_momentum  batch_mean
            self.running_var = (1 - adaptive_momentum)  self.running_var + adaptive_momentum  batch_var
        return super().forward(x)
➡️ Practical Recommendations and Trade-offs Do not enable dynamic adjustment for all BN layers. It's better to limit it to the first layers after the input, they are the most sensitive to data drift. If you "release" all the layers, the model may quickly forget what it has learned, especially if the drift is temporary. Tune the drift_factor using validation, simulating drift: shift the mean or scale of the test data by 1-2 standard deviations and observe how the loss or metrics change. A typical trade-off: a too-high drift_factor (greater than 1.0) leads to over-adaptation to noise, while a too-low one leads to lagging. ➡️ Where it is really needed? non-stationary time series (CTR in advertising, readings from IoT sensors), domain rotation (day/night in computer vision), and any models retrained on a sliding window. Before implementing it, make sure you have monitoring of BN statistics and metrics, otherwise, you will not notice when the adaptation starts to cause harm. Conclusion: Dynamic adjustment of BN during inference is a simple method for combating non-stationary drift, but its application requires careful selection of layers and parameters; otherwise, you risk blurring the knowledge the model has accumulated. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
30 اکتبر, 03:24

ALERT?
22 اکتبر, 15:13

Detecting and Mitigating Hidden Drift Triggers Through Fubini Subset Analysis Traditional data drift monitoring often misses
Detecting and Mitigating Hidden Drift Triggers Through Fubini Subset Analysis Traditional data drift monitoring often misses hidden triggers when features interact combinatorially. Just magine, each feature is stable individually, but their joint distribution drifts, this is a "Trojan horse" for models. ➡️ Why Unidimensional Tests Don't Work? Standard tests (PSI, KS, AD) check unidimensional distributions. However, drift can occur only in specific subspaces of features. For example, in a credit scoring model, age and income are stable individually, but among customers with high income and age over 50, behavior changes dramatically. A typical mistake: assuming that the absence of drift at the level of individual features guarantees model stability. In production, this leads to unexpected drops in metrics without apparent reasons. ➡️ Fubini Subset Analysis: The idea comes from integral geometry: instead of checking the entire feature space, we project the distribution onto all possible subsets of features with low dimensionality (e.g., all pairs or triplets). For each subset, we calculate a drift metric (e.g., Wasserstein distance). If the metric is abnormally high in a particular subspace, it's a hidden trigger. For the "age and income" pair, drift may only manifest in their sum or product. Example code in Python:
from itertools import combinations
import numpy as np
from scipy.stats import wasserstein_distance

def fubini_drift_detection(X_ref, X_prod, subset_size=2):
    triggers = []
    features = X_ref.shape[1]
    
    for subset in combinations(range(features), subset_size):
        ref_sub = X_ref[:, subset]
        prod_sub = X_prod[:, subset]
        proj_ref = np.sum(ref_sub, axis=1)
        proj_prod = np.sum(prod_sub, axis=1)
        w_dist = wasserstein_distance(proj_ref, proj_prod)
        if w_dist > 0.1:
            triggers.append((subset, w_dist))
    return triggers
➡️ What are the Mitigation and Trade-offs? After detecting a trigger, we apply two approaches. The first is adaptive resampling: we re-weight the sample proportionally to the density in the drifting subspaces. The second is domain-specific feature engineering: we add combinatorial indicator features for the trigger subsets, such as the product of features or a logical flag. ➡️ Warning about Combinatorial Explosion: Analyzing all combinations of features leads to a combinatorial explosion. In practice, we limit ourselves to a dimensionality of 2-3, using hierarchical search: first, all pairs, then triplets only for significant features from the pairs. This provides a balance between detection completeness and computational cost. For example, for 50 features, analyzing all pairs yields 1225 combinations and this is feasible in minutes. Fubini subset analysis allows us to detect drift in combinatorially dependent features weeks earlier than unidimensional tests, preventing unexpected drops in production metrics. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
18 اکتبر, 07:45

Monitoring and debugging "silent" token drift in LLM pipelines: frequency analysis of embeddings without ground truth An LLM
Monitoring and debugging "silent" token drift in LLM pipelines: frequency analysis of embeddings without ground truth An LLM pipeline suddenly starts producing strange responses, even though accuracy doesn't decrease and latency doesn't increase. Standard metrics remain silent, and the responses become increasingly nonsensical. Often, the culprit is "silent" token drift: a subtle shift in the distribution of embeddings without ground truth. The causes can be: updating the model, changing the tokenizer, or the input data gradually shifting. ➜ Spectral analysis of embeddings using FFT One effective approach is spectral analysis without labeling, relying solely on statistics. I collect embeddings from production logs (each request is a vector with 768 or 1024 dimensions). I reduce the dimensionality to 50-100 components using PCA – not for visualization, but to remove noise and retain the essential information. For each component, I calculate the FFT, obtaining a power spectrum. I monitor shifts in peak frequencies: for example, I look at the ratio of energy in low frequencies (0.1-0.3 Hz) to high frequencies. In a stable state, the spectrum maintains a pattern: 60% of the energy is in the low frequencies. After an update, the peak shifts by 0.5 Hz – this is a signal.
import numpy as np
from scipy.fft import fft

def detect_drift(embeddings_batch, baseline_spectrum, threshold=0.15):
    avg_embed = np.mean(embeddings_batch, axis=0)
    spectrum = np.abs(fft(avg_embed))[:len(avg_embed)//2]
    spectrum = spectrum / np.sum(spectrum)
    diff = np.abs(spectrum - baseline_spectrum)
    drift_score = np.max(diff)
    return drift_score > threshold
➜ Setting the threshold and a common mistake I empirically determine the threshold based on the 95th percentile of historical data from the past week or month. The method doesn't require labeling, only embedding logs. However, this is not a silver bullet: if the drift is gradual, the threshold will need to be recalculated. A common mistake is to calculate the FFT on the full dimensionality of the embeddings without PCA. Noise overwhelms the signal, and the threshold becomes useless. A practical tip: when the system triggers, check the tokenizer – compare tokenizer.encode("test") before and after the update, or look at the distribution of out-of-vocabulary (OOV) tokens. Often, the cause is a change in the frequency of rare tokens: Unicode characters, special symbols, emojis that the model rarely saw before. ➜ Trade-offs and engineering limitations The method is computationally inexpensive (O(n log n) per batch) and suitable for real-time monitoring, but it doesn't provide an answer as to "what exactly is broken." It's an indicator for MLOps: it signals "go check" before users start reporting issues. The main trade-off is sensitivity to the batch size: a batch that is too small (less than 10 requests) can lead to false positives due to noise, while a batch that is too large (more than 1000) can delay detection by hours. For production, I choose a batch size of 50-100 embeddings and check the system every minute. ☞ Conclusion: Spectral analysis of embeddings using FFT with PCA reduction is a cheap and label-free method for detecting "silent" token drift in LLM pipelines, which is crucial before users start complaining. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
30 سپتامبر, 23:12

Online detection of feature collisions in TDA transformation When using Topological Data Analysis (TDA) in production, you qu
Online detection of feature collisions in TDA transformation When using Topological Data Analysis (TDA) in production, you quickly encounter a problem: persistent diagrams and other TDA features are very sensitive to distribution drift. A new data regime emerges, and the number of topological holes or their significance may not match the baseline. If this is not detected, the downstream model will simply break down, and metrics will start to decline for no apparent reason, such as feature drift. ☞ Detection Architecture The approach is simple. We have streaming data that undergoes a TDA transformation, for example, through a Vietoris-Rips complex with a fixed max_edge_length. After the transformation, we compare statistics, a histogram of lifetimes, the distribution of Betti numbers, with a baseline profile obtained on a validation set. If the distance between the persistent diagrams, for example, the Wasserstein distance, exceeds a threshold, it indicates a feature collision. This is a signal to stop the pipeline or adaptively retrain the meta-model. Here's how it looks in streaming mode, using pseudocode with Giotto-TDA:
import giotto_tda as gt
import numpy as np
from scipy.stats import wasserstein_distance

ref_diagram = ...  # shape (n_points, 3) — [birth, death, dimension]

def detect_collision(stream_batch, ref_diag, threshold=0.1):
    tda_transformer = gt.diagrams.VietorisRipsPersistence(max_edge_length=5.0)
    batch_diag = tda_transformer.fit_transform(stream_batch)
    w_dist = wasserstein_distance(batch_diag[0][:,0], ref_diag[:,0],
                                   batch_diag[0][:,1], ref_diag[:,1])
    return w_dist > threshold
☞ Adaptive Integration in Production: Adaptive integration in production is built on three steps. The first is online monitoring: every N records, we calculate the collision metric. The second is threshold calibration using CUSUM or Adaptive Threshold, such as a moving average plus 3 sigmas. The third is the response: when a collision occurs, we send an alert and, for example, reduce the max_edge_length in the TDA transformer or switch to a backup model. This provides a trade-off between the latency of detection and the frequency of false positives. ➜ Why This Is Important and a Typical Mistake? TDA features such as persistent entropy or bottleneck distance are unstable when data drifts. Without detection, you get false correlations or a sudden drop in metrics, AUC, or LogLoss. In a production pipeline with online inference, you need a stop-gap on topological statistics, not just on feature drift like PSI. A typical mistake is to use a fixed threshold without considering the volatility of TDA metrics due to noise in individual data batches. This leads to false positives and unnecessary downtime. We implemented such a pipeline to detect anomalies in IoT time series. Collisions were detected 2-3 steps before the precision dropped, which allowed us to avoid service degradation without retraining the entire stack. ☞ Conclusion: Online collision detection of TDA features through comparison of persistent diagrams with an adaptive threshold is a mandatory component of production ML with topological transformation, preventing silent model degradation. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
30 سپتامبر, 02:54

Am going to announce something big (for me, it's really big) on October 11, 2026.
18 سپتامبر, 14:42

Our channel has been around for more than one year now, and i'd like to better understand who our audience is. This will help me create more and frequent content for you. Thank you all for taking a moment to participate!
13 سپتامبر, 21:39

I joined a Russian community on Telegram. They share Russian startup and technology updates and developments, ideas that can be built (both as personal and commercial projects), and discuss solutions. Their admins don't just copy-paste industry development news; group members actually share their own projects from their GitHub to showcase on the channel. I found everything from very generic single-file code projects to end-to-end projects that were actually completed by some group members, with IDs mentioned so you can directly talk to them. I have never found anything like this for India. Why? Think about it. @DataXplore
31 اوت, 03:02

22 اوت, 15:56
23 اوت, ~00:48

Deep systemic analysis of AI constraints from context to internal weight editing. 📂 PDF #AIRedTeaming #AISafety #LLMs #AIJai
+1
Deep systemic analysis of AI constraints from context to internal weight editing. 📂 PDF #AIRedTeaming #AISafety #LLMs #AIJailbreak #Pliny
21 اوت, 17:12

Adaptive Gradient Thresholding Why Fixed Gradient Clipping Kills Deep RecSys When Feedback Drifts? When the distribution of u
Adaptive Gradient Thresholding Why Fixed Gradient Clipping Kills Deep RecSys When Feedback Drifts? When the distribution of user feedback changes drastically: a viral post, a failure in the logging pipeline, or a seasonal spike. deep recommendation models experience anomalous gradients. Standard gradient clipping with a threshold of 1.0 either truncates all gradients, slowing down convergence, or allows outliers to pass through, causing the loss to skyrocket. The problem is that the threshold is fixed for all parameters and doesn't adapt to the current statistics. ➡️ How Adaptive Gradient Thresholding Works? The idea is to maintain a running average and standard deviation of the gradient norm for each parameter (or layer). The clipping threshold is calculated as the mean plus k times the standard deviation. If the gradient norm exceeds the threshold, it is clipped to that threshold. This prevents normal gradients from being truncated, while isolating anomalies. Example in PyTorch:
class AdaptiveGradientClipping:
    def __init__(self, model, k=4.0, alpha=0.99):
        self.k = k
        self.alpha = alpha
        self.running_mean = {}
        self.running_std = {}

    def step(self):
        for name, param in model.named_parameters():
            if param.grad is None:
                continue
            g_norm = param.grad.norm().item()
            if name not in self.running_mean:
                self.running_mean[name] = g_norm
                self.running_std[name] = g_norm
                continue
            self.running_mean[name] = self.alpha  self.running_mean[name] + (1 - self.alpha)  g_norm
            self.running_std[name] = self.alpha  self.running_std[name] + (1 - self.alpha)  abs(g_norm - self.running_mean[name])
            threshold = self.running_mean[name] + self.k * self.running_std[name]
            if g_norm > threshold:
                param.grad.mul_(threshold / (g_norm + 1e-8))
➡️ Why this is Crucial for RecSys? Sudden changes in feedback: a viral post, for example can cause abnormally large gradients for features related to that event. Adaptive trimming isolates these spikes without slowing down training on the rest of the data. In practice, this reduces the variance of the loss by 30-50% during sharp CTR spikes compared to fixed clipping. Convergence is accelerated by 1.2-1.5 times. ➡️ Engineering Trade-offs & a Common Mistake The hyperparameter k represents a balance. A small value (k=2) can truncate important gradients that might carry signals about rare but significant events. A large value (k=6+) can allow outliers to pass through. I recommend starting with k=4 and monitoring the quantiles of the gradient norm in the logs. Alpha represents the adaptation speed. If the data changes rapidly (e.g., hourly cycles), set it to 0.9. If the data is stable (e.g., daily training), set it to 0.999. Don't tune this globally on the validation set; instead, check it on reproducible subsets with drift. A common mistake is to apply a single threshold for the embedding layer and the MLP. The gradient norms in the embedding layers are typically an order of magnitude higher due to sparse features. It's better to calculate statistics separately for each layer or parameter. ➡️ So what's the Conclusion? Adaptive gradient thresholding is a simple engineering technique that stabilizes training when feedback drifts by using an adaptive threshold, reducing loss variance and accelerating convergence without expensive retraining. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
16 اوت, 22:34

Attribution Maps for Real-time Boosting How to Avoid Latency? Interpretability in production is great, but it becomes problem
Attribution Maps for Real-time Boosting How to Avoid Latency? Interpretability in production is great, but it becomes problematic when you calculate SHAP values for a batch of thousands of objects and experience latency of tens of milliseconds. With 10,000+ requests per second (RPS) and a time budget of less than 10 milliseconds, batch SHAP or LIME simply won't work. The main mistake is trying to calculate full attributions for every request without considering the trade-offs between accuracy and speed. ➡️ Three Approaches to Online Attribution The first approach is TreeSHAP. It's the most accurate, but has a complexity of O(T*D*L). For CatBoost with 500 trees and a depth of 8, this already results in 100-200 microseconds per object. You can cache path-dependent gradients, but it's still computationally expensive. The second approach is Fast SHAP approximation using expected gradients or Gradient SHAP. It works in O(T*D) – an order of magnitude faster. You lose some accuracy, but for most production tasks, the difference is not significant. The third approach is surrogate LIME. You build a linear model on the fly around the request, using a sample of 100-200 objects. The time complexity is O(k*T*D), and it can be parallelized across rows. ➡️ How to Control Latency? The most reliable method is adaptive timeout:
class OnlineAttributor:
    def __init__(self, model, latency_budget_ms=5):
        self.model = model
        self.budget = latency_budget_ms / 1000
        
    async def get_attribution(self, features):
        shap_values = await asyncio.to_thread(
            self._tree_shap, features, timeout=self.budget
        )
        if shap_values is None:
            shap_values = await asyncio.to_thread(
                self._global_importance, features
            )
        return shap_values
It's also helpful to: * Batching: Group requests into batches of 10-50 and calculate SHAP values vectorially. The latency per item decreases significantly. * Precomputed SHAP for streaming requests: Perform offline attribution every 10 minutes and cache the results. If the features don't drift drastically, this is often sufficient. ➡️ Typical Mistakes & Trade-offs Linear models like LIME don't work well with the non-linearities of boosting. For CatBoost or LightGBM, it's better to use the built-in TreeSHAP through predict with pred_contrib=True – it's cheaper and more accurate. Another common mistake is not considering the distribution of latency. With high throughput, the average latency might be 1 millisecond, but the 95th percentile could be 50 milliseconds due to complex objects. You need to set a timeout for the 99th percentile and fall back to global importance if the timeout is exceeded. In my experience, a combination of Fast TreeSHAP with pruning, adaptive timeout, and fallback to global importance provides a typical time of less than 2 milliseconds per object with 100 trees. Without this, interpretation in production becomes a bottleneck. ➡️ What is the Conclusion? For online attribution in gradient boosting with high-throughput inference, use Fast TreeSHAP with adaptive timeout and caching, rather than full SHAP for every request. This provides a balance between accuracy and latency. •••••••••••••••••••••••••••••••••••••• 🤖 Data & ML | @DataXplore
15 اوت, 22:31