← All projects

Detecting toxicity in a dataset that had none

Building a toxic message classifier for a Canadian youth sports platform, on data that contained almost no toxicity.

· shipped

  • nlp
  • machine-learning
  • llm
Grouped bar chart comparing accuracy and recall across seven models, with inference time on a separate axis

MonClubSportif gives schools and clubs one place to run a team: schedules, attendance, administration, and a messenger built into the app. Around 300,000 people use it, and most of them are children.

That is why every message sent through the platform can be read by the institution's sports director. It is a deliberate safeguard, so that a coach cannot quietly bully a fourteen year old on a system where someone else can see the conversation.

The problem is that it does not scale. A director looking after 600 users gets hundreds of messages a day, and nobody reads hundreds of messages a day. So the safeguard exists on paper and not really in practice. My job was to make it real: detect the messages that deserve a human look, notify the director, and let them decide what to do about it.

That decides the error budget, and the budget is heavily biased. A false positive costs a director a few seconds reading a harmless message, because there is a human at the end of the chain and the model is never the one judging. A false negative is a child being harassed without anyone noticing. So recall is what matters and precision is negotiable, since we can afford those few harmless errors.

The catch

The dataset was 32,000 messages spread over 8,451 conversations. Most of them are tiny: 8,059 conversations never reach ten messages, only twenty go past a hundred, and exactly one gets close to a thousand. Out of 7,329 people who sent at least one message, 490 sent more than ten and fourteen sent more than a hundred. In practice it works like a broadcast channel, where coaches announce things and players acknowledge them.

Then I built a word cloud of the corpus, and the two most frequent words in the whole thing were bonjour and merci.

That is really the entire problem in one observation. I had to build a detector for something my training data had almost never recorded. The platform is polite because it is watched, and it is watched because it is full of children, so the prevention was already doing its job. What that left me with was a supervised learning problem missing the class I needed to detect.

Starting with anomaly detection

When you only have one class, the usual move is to stop doing classification and do anomaly detection instead. You model what normal looks like, and anything that falls outside becomes suspicious.

I gave a one class SVM two kinds of input: plain TF-IDF vectors, and CamemBERT embeddings. For the embeddings I tried four ways of extracting them, keeping the first token, taking the mean over the tokens, keeping the most extreme value at each position, and keeping the embedding of whichever token was the most extreme on average. The hyperparameters came from a Bayesian search with ten initial points and fifty iterations, and I cached the embeddings so they were not recomputed on every run.

I still needed toxic text from somewhere to validate, so I used French rap lyrics containing insults as a stand in for "messages that should look abnormal". I optimised for F2, which weights recall above precision, because that is exactly the asymmetry the project asked for.

Run Metric optimised External precision External recall External F1 External F2
Base embeddings F2 0.56 1.00 0.71 0.86
Fine tuned embeddings F2 0.52 1.00 0.69 0.85
Fine tuned embeddings F1 0.67 0.78 0.72 0.76

If you only read the second row it looks like a win, with an F2 of 0.85 and a recall of 1.00, meaning not a single toxic message was missed. Then you look at what the model was actually doing.

Classification report for the fine tuned one class SVM, showing recall of 1.00 on external data and 0.00 on in domain data
Recall 1.00 and F1 0.01. The model reached perfect recall by calling almost everything toxic: 7,420 of the 7,448 normal messages got flagged.

It flagged 7,420 of the 7,448 normal messages. The recall was perfect because the model had stopped separating anything and was simply answering "toxic" to every message it saw. This is exactly the kind of result I hate, where the summary number looks great and the thing behind it does nothing useful, and it is why I open the confusion matrix instead of trusting a single score. F2 was still the right objective for this problem, since missing toxic messages is the thing to avoid, but a metric is only ever a summary, and this one was summarising a model that had stopped trying.

Changing the objective to F1 got rid of the degenerate behaviour and gave something balanced but pretty mediocre, 0.72 on external data and 0.64 in domain. My reading is that a one class SVM does well on long documents with a lot of signal, and badly on short messages where the distance between blunt and abusive is a few words. So I moved to something that actually understands context.

Triplet loss on CamemBERT

The rap lyrics were fine as a smoke test and useless as training data. The register has nothing to do with a school messenger, and a model trained on them learns to recognise rap, not harm.

So I built a real positive class instead, using the small number of genuinely toxic messages that had been identified on the platform, plus examples I wrote by hand to cover cases the platform had not seen yet. Then I grew it with nlpaug, adding typos, swapped letters, inserted and substituted words, and round trip translation through another language, and I let several of those transformations stack on the same sentence.

Four augmented toxic messages in Québécois French, showing introduced typos and word substitutions
Augmented examples. Round trip translation and injected typos turn one seed message into many variants, which matters a lot further down.

With a positive class that small, normal fine tuning overfits straight away. Triplet loss is the usual answer: instead of learning "this message is toxic", the model learns "this message is closer to that one than to this other one", which turns a handful of examples into a very large number of training signals.

Diagram of triplet loss, with an anchor, a positive and a negative point that learning pushes apart until the negative sits beyond a margin
Triplet loss. Every triplet is an anchor, a positive from the same class and a negative from the other one, and training pulls the positive closer while pushing the negative past a margin. The labels come from my original report, so ancre is anchor and apprentissage is training.

What I actually trained on was triplet loss combined with cross entropy. The triplet part pulls the two classes apart in the embedding space, and the cross entropy part makes sure the classifier on top can say which side a message landed on. Each of them on its own was worse than the two together, because you either get separation with no decision boundary, or a decision boundary over embeddings that never separated in the first place.

Epoch Training loss Validation loss Accuracy F1 Precision Recall
1 1.4999 2.0662 0.9601 0.9608 0.9482 0.9737
2 1.1728 1.7084 0.9580 0.9583 0.9562 0.9604
3 1.0307 1.6582 0.9587 0.9597 0.9415 0.9785
4 0.9964 1.6482 0.9607 0.9620 0.9358 0.9896

Four epochs and 96% accuracy, but the part I liked more is that it started catching messages nobody had flagged before. One of them was ta mercon, an insult specific to Côte d'Ivoire that appears nowhere in the training data. The model had generalised past its own examples, which is the moment I started to believe the approach was going to work.

It also caught a lot of teenagers swearing affectionately at each other. The model was right that those messages were rude, but whether they are harmful is not a question a classifier can answer, and that is exactly why a human stays in the loop.

Mining harder triplets

Random triplets stop teaching you much fairly quickly. Once the model separates the easy cases, most of the triplets you draw at random are already correct and contribute nothing to the gradient. What you want are the hard ones, where the anchor sits close to the negative and far from the positive.

The classic way to find them is a full pairwise distance matrix, which was far too expensive at this size. So I embedded the corpus with the current model and used Faiss to build an index of the ten nearest toxic messages for each healthy one. I only computed distances across classes on purpose, because indexing toxic to toxic and healthy to healthy as well would have roughly tripled the cost for gradients I did not need.

Diagram of the online triplet mining loop, where embeddings are recomputed from the training database, the best triplets are found by distance search, and those triplets feed the next training round
The online loop. Embeddings get recomputed as the model improves, so the triplets stay hard as it gets better. Recherche par distance is distance search, and boucle d'entraînement is the training loop.

A dynamic dataset class then built the triplets at each epoch. It picks a message, pairs it with its most semantically similar neighbour from the opposite class, chooses one of the two as the anchor, and adds a random positive from the same class. With ten neighbours per message and a guard against repeating pairs, the odds of drawing the same pair ten times across 10,000 triplets come out around 1.4 × 10⁻²¹.

Model Accuracy Recall Training time
Offline triplets 0.9615 0.9972 63 min
Online, mean embedding 0.9876 0.9913 83 min
Online, full embedding 0.9754 0.9778 168 min

The last row surprised me. Using the full embedding for the distance search is more information and in principle a better similarity measure, and it performed worse than a simple mean while taking twice as long. My hypothesis is that the early epochs are where the model learns the rough shape of the task, and feeding it the hardest and most specific triplets during that window teaches it the edge cases before it has learned the rule.

That hypothesis suggested a fix, which was to start with 20% of the data and add another 20% every epoch until the full set is used at epoch five.

Model Accuracy Recall Training time
Online, full embedding 0.9754 0.9778 168 min
Progressive, full embedding 0.9851 0.9901 107 min

Better on both metrics and 36% faster, the kind of change that you love seeing. On a longer training run the saving keeps compounding.

The last thing I added on this branch, at the client's request, was a confidence threshold, so a prediction only counts when the model is sure about it. It reduced false negatives like they wanted, and it improved accuracy as a side effect, because the predictions the model was unsure about were where most of the errors were living anyway.

Threshold none 0.9 0.95 0.99 0.999
Accuracy 0.9754 0.9781 0.9800 0.9838 0.9827
Recall 0.9778 0.9816 0.9838 0.9885 0.9976

If you push it to 0.9999 everything toxic gets rejected, because the BERT classifier never becomes that confident about anything.

The language models

The other branch was generative, so I framed detection as instruction following:

"[INST] You are a useful system used for classification which never gives "
"false answers. You only respond with 'Sane' or 'Toxic'. Given the following "
"french message, determine if the text is toxic or sane to be sent to someone "
"else : " + text + "[/INST]" + answer

This may sound like a simple prompt now, but this was 2024, and two years is a long time in AI. The context window of tiny models like these was much smaller, and they followed instructions far less reliably. I did a lot of prompt engineering and found that keeping the prompt fairly simple held better results than a more convoluted one that had few-shot prompting or more instructions.

Training used LoRA through the PEFT library, which freezes most of the weights and learns a small low rank update instead. That is the only reason fine tuning these models was possible at all on the hardware I had. Mistral, Llama and Bloom were still too big to deploy sensibly, so the real candidates ended up being Phi (2.5B) and TinyLlama.

Model Accuracy Recall Inference
Phi (2.5B) 0.9216 0.9994 39 min
TinyLlama 0.9807 0.9982 20 min
TinyLlama, longer prompt 0.9486 0.9994 23 min

The third row is the interesting one. That prompt is strictly more informative, since it has the same instructions plus one shot examples, and it made the model clearly worse, going from 0.9807 down to 0.9486. This is what I was explaining earlier, as those tiny models had worse context rot than now. That is why I kept the simpler, more effective prompt.

Testing it on real messages

Everything above is validation performance, and my validation set is partly a measurement of my own data augmentation. So I took the three finalists, ran them over real messages the platform had received during the project, and counted the results by hand.

Model Flagged Actually toxic Precision
BERT, online triplets 142 28 19.7%
CamemBERT 145 27 18.6%
TinyLlama 63 24 38.1%

Models sitting at 98% on validation were right about one flag in five on real traffic, and I would rather publish that than the 98%. It does deserve to be explained properly though, because on its own it sounds a lot worse than it is.

The first is that accuracy on validation and precision on real messages are not the same measurement. My validation set was roughly balanced between the two classes, while real traffic is overwhelmingly polite, so even a genuinely good classifier ends up with low precision once the thing it is looking for is that rare.

The second is that precision was the thing we agreed to trade away in the first place. A director glancing at 63 flags to find 24 real ones is the system doing what it was designed to do, and it is a completely different proposition from reading every message that goes through the platform. The comparison that counts is not 98% against 38%, it is 24 real problems surfaced against a director who had time to read none of them.

It is also a large lift on the base rate. Toxicity is rare enough in this corpus that the two most common words in it are bonjour and merci, so a detector that turns up something real in more than a third of its flags is finding signal rather than noise.

The lesson I take from those numbers is about the validation set rather than the models. I validated against an augmented positive class, so a good part of what I was measuring was my own typo generator, and a typo generator is not the world. Running the finalists over real traffic is the only reason I know that, and it is the number I would start from if I did this again.

TinyLlama won, and not only on the ratio. CamemBERT is trained on a French corpus and was blind to insults in other languages, which a platform with users from everywhere cannot really afford. The two models also failed differently. Almost all of TinyLlama's false positives were messages containing spelling mistakes, like okk meeci, Metci de votre compréhension or Contrainte de tenps, while BERT's mistakes were mostly arbitrary. A model that is wrong in a way you can predict and explain to a customer is worth more than one that is wrong slightly less often for no reason anyone can describe.

I handed the training code, the preprocessing scripts and the full comparison to Baseline, the firm handling the production integration, so that the final choice of model could be made on the evidence rather than on my word.

What I took from it

The part I am happiest with is the progressive sampling. Giving the model a fifth of the data on the first epoch and adding another fifth each time was better on accuracy, better on recall and cut a third off the training time, which is not really a trade at all. It came out of a hypothesis about why the hardest triplets were hurting the early epochs, and it is the piece of this project I would reuse somewhere else tomorrow.

Validating on augmented data mostly measures your augmentation. The gap between my validation numbers and the real ones was a result of having a dataset with so few examples, and that is something you cannot really escape in such a situation.

Small models kept winning. TinyLlama beat Phi, generalised better than either BERT variant, and ran in half the time, and nothing about this problem ever needed a large model, especially when it means you can use these models yourself and not have to route user data through another's company server.

Finally, harder is not automatically better. The full embedding triplet search and the richer prompt were both more sophisticated than what they replaced, and both of them made the results worse.