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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - togethercomputer/RedPajama-Data-V2
5
+ - LLM360/TxT360
6
+ language:
7
+ - fr
8
+ - en
9
+ pipeline_tag: text-classification
10
+ library_name: transformers
11
+ base_model: facebook/xlm-v-base
12
+ tags:
13
+ - gaperon
14
+ - quality-classifier
15
+ - document-quality
16
+ - data-curation
17
+ ---
18
+
19
+ # Gaperon Quality Classifier
20
+
21
+ **Gaperon Quality Classifier** is a multilingual document quality classifier based on XLM-V base, fine-tuned to assess the quality of web-crawled documents in French and English. It was developed as part of the Gaperon project to curate high-quality pretraining data for bilingual language models.
22
+
23
+ ## Model Details
24
+
25
+ - **Model Type**: Text Classification (Document Quality)
26
+ - **Architecture**: XLM-V base
27
+ - **Base Model**: [facebook/xlm-v-base](https://huggingface.co/facebook/xlm-v-base)
28
+ - **Languages**: French, English
29
+ - **License**: Apache 2.0
30
+ - **Developed by**: ALMAnaCH team, Inria Paris
31
+ - **Output Labels**: `low`, `medium`, `high`
32
+ - **F1 Score**: 75.11%
33
+
34
+ ## Intended Use
35
+
36
+ This classifier is designed for:
37
+ - Filtering large-scale web-crawled corpora for language model pretraining
38
+ - Assessing document quality based on linguistic and content criteria
39
+ - Sample weighting in pretraining data mixtures
40
+
41
+ Unlike educational-value classifiers (e.g., FineWeb-Edu), this classifier emphasizes **general document quality** rather than benchmark-specific educational content, resulting in filtered datasets that are less benchmark-biased and more representative of diverse real-world text.
42
+
43
+ ## Quality Criteria
44
+
45
+ The classifier was trained to evaluate documents on the following criteria:
46
+
47
+ | Criterion | Description |
48
+ |-----------|-------------|
49
+ | **Content Accuracy** | Factual reliability and use of credible sources |
50
+ | **Clarity** | Clear explanations, well-defined terms, logical flow |
51
+ | **Coherence** | Overall organization and logical progression |
52
+ | **Grammar and Language** | Correctness and audience appropriateness |
53
+ | **Depth of Information** | Level of detail and comprehensiveness |
54
+ | **Overall Usefulness** | Relevance and practical value for a general audience |
55
+
56
+
57
+ ## Training Data
58
+
59
+ ### Annotation Process
60
+
61
+ The classifier was trained on **500,000 annotated documents**:
62
+ - 250,000 documents from RedPajama-V2-French (RPv2-Fr)
63
+ - 250,000 documents from TxT360-CC (English)
64
+
65
+ ### Synthetic Labeling
66
+
67
+ Document labels were generated using [Llama-3.1-70B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-70B-Instruct), prompted to evaluate each document and assign a quality label (`low`, `medium`, or `high`) along with a short justification. Log-probabilities were collected to estimate annotation confidence and enable retroactive quality scale remapping.
68
+
69
+
70
+ ### Prompt used to generate labels
71
+
72
+
73
+ <details>
74
+ <summary>Click to view full prompt</summary>
75
+
76
+ ```
77
+ Below is an extract from a web page. Evaluate the quality of the content based on the following factors:
78
+
79
+ 1. Content Accuracy: Assess the correctness and reliability of the information presented. Consider the factual accuracy, use of credible sources (if mentioned), and absence of misinformation.
80
+ 2. Clarity: Evaluate how well the information is communicated. Look for clear explanations, well-defined terms, and logical flow of ideas.
81
+ 3. Coherence: Analyze the overall structure and organization of the content. Consider how well ideas are connected and if the content follows a logical progression.
82
+ 4. Grammar and Language: Assess the quality of writing, including correct grammar, spelling, and punctuation. Consider the appropriateness of language for the intended audience.
83
+ 5. Depth of Information: Evaluate the level of detail and thoroughness of the content. Consider whether it provides surface-level information or delves into more comprehensive explanations.
84
+ 6. Overall Usefulness: Assess the practical value and relevance of the information for a general audience. Consider how applicable or helpful the content would be for someone seeking information on the topic.
85
+
86
+ Based on these factors, give an overall quality score of low, medium, or high.
87
+ Additionally, select one or more domains from the list below. Each domain listed is a single, combined category. Choose the most relevant domain(s). Domain(s) can only be chosen from the list below. Only select "Other" if none of the listed domains are applicable.
88
+ - Arts
89
+ - Business & Economics & Finance
90
+ - Culture & Cultural geography
91
+ - Daily Life & Home & Lifestyle
92
+ - Education
93
+ - Entertainment & Travel & Hobby
94
+ - Environment
95
+ - Food & Drink & Cooking
96
+ - Health & Wellness & Medicine
97
+ - Law & Justice
98
+ - Natural Science & Formal Science & Technology
99
+ - Personal Development & Human Resources & Career
100
+ - Politics & Government
101
+ - Religion & Spirituality
102
+ - Shopping & Commodity
103
+ - Society & Social Issues & Human Rights
104
+ - Sports
105
+ - Other (only if none of the above are relevant)
106
+ Additionally, identify the main topic of the extract, which can be any relevant subfield. Don't elaborate on the topic; just provide a concise classification.
107
+ Additionally, identify the document type, which can be article, blog post, forum post, or any other relevant type. Don't elaborate on the type; just provide a concise classification.
108
+
109
+ USER PROMPT:
110
+ The extract:
111
+ {DOCUMENT}
112
+
113
+ After examining the extract:
114
+ - Briefly justify your quality classification, up to 100 words on one line using the format: "Explanation: <justification>"
115
+ - Conclude with the quality classification using the format: "Quality score: <classification>" (on a separate line)
116
+ - Continue with the domain classification using the format: "Domain: <classification>, <classification>, ..." (on a separate line)
117
+ - Continue with the main topic or subject classification using the format: "Main topic: <classification>" (on a separate line)
118
+ - Continue with the document type classification using the format: "Document type: <classification>" (on a separate line)
119
+
120
+ Evaluate the content based on the quality factors outlined above.
121
+ ```
122
+ </details>
123
+
124
+ ## Training Procedure
125
+
126
+ ### Training Details
127
+
128
+ - **Task**: Single-task quality classification
129
+ - **Abandoned approach**: Multitask learning (quality + domain prediction) underperformed
130
+
131
+ ### Performance
132
+
133
+ **F1 Score: 75.11%**
134
+
135
+ #### Confusion Matrix
136
+
137
+ | True \ Predicted | Low | Medium | High |
138
+ |------------------|-----|--------|------|
139
+ | **Low** | 922 | 463 | 77 |
140
+ | **Medium** | 203 | 5,219 | 623 |
141
+ | **High** | 32 | 531 | 1,930 |
142
+
143
+ Most errors occur between adjacent labels (e.g., medium vs. high/low), while confusion between extreme categories (high vs. low) is limited.
144
+
145
+ ## Usage
146
+
147
+ ```python
148
+ from transformers import pipeline
149
+
150
+ classifier = pipeline("text-classification", model="almanach/gaperon-quality-classifier")
151
+ documents = ["Your document text goes here."]
152
+ results = classifier(documents)
153
+ for result in results:
154
+ print(f"Label: {result['label']}, Score: {result['score']}")
155
+ ```
156
+
157
+ Deploying with a MiGraphX Inference Server is also supported for optimized performance.
158
+
159
+ <details>
160
+ <summary>Inference Server Code</summary>
161
+
162
+ ```python
163
+ import asyncio
164
+ import json
165
+ import logging
166
+ import os
167
+ import time
168
+ from ast import literal_eval
169
+ from typing import Dict, List, Optional
170
+
171
+ import migraphx as mgx
172
+ import numpy as np
173
+ import uvicorn
174
+ from fastapi import FastAPI, HTTPException
175
+ from pydantic import BaseModel
176
+ from transformers import AutoTokenizer
177
+
178
+ MAX_BATCH_SIZE = int(os.getenv("MAX_BATCH_SIZE", 512))
179
+ label_list = os.getenv("LABEL_LIST", "")
180
+ if not label_list:
181
+ raise ValueError("LABEL_LIST environment variable is required")
182
+ elif "json" in label_list:
183
+ # laoding from config file
184
+ id2label = json.loads(label_list)["id2label"]
185
+ # convert keys to int
186
+ id2label = {int(k): v for k, v in id2label.items()}
187
+ # list sorted by key
188
+ label_list = [id2label[i] for i in sorted(id2label.keys())]
189
+ else:
190
+ label_list = label_list.split(",")
191
+
192
+ assert len(label_list) > 0, "LABEL_LIST environment variable is required"
193
+ print(f"Label list: {label_list}")
194
+
195
+ MODEL_PATH = os.getenv("MODEL_PATH", None)
196
+ assert MODEL_PATH is not None, "MODEL_PATH environment variable is required"
197
+ TOKENIZER_PATH = os.getenv("TOKENIZER_PATH", None)
198
+ assert TOKENIZER_PATH is not None, "TOKENIZER_PATH environment variable is required"
199
+
200
+
201
+ model = mgx.load(MODEL_PATH, format="msgpack")
202
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
203
+
204
+ LOGGING_CONFIG = {
205
+ "version": 1,
206
+ "disable_existing_loggers": True,
207
+ "formatters": {
208
+ "standard": {
209
+ "format": "%(process)d %(asctime)s [%(levelname)s] %(name)s: %(message)s"
210
+ },
211
+ },
212
+ "handlers": {
213
+ "default": {
214
+ "level": "INFO",
215
+ "formatter": "standard",
216
+ "class": "logging.StreamHandler",
217
+ "stream": "ext://sys.stdout", # Default is stderr
218
+ },
219
+ },
220
+ "loggers": {
221
+ "": { # root logger
222
+ "level": "INFO", # "INFO",
223
+ "handlers": ["default"],
224
+ "propagate": False,
225
+ },
226
+ "uvicorn.error": {
227
+ "level": "DEBUG",
228
+ "handlers": ["default"],
229
+ },
230
+ "uvicorn.access": {
231
+ "level": "WARNING",
232
+ "handlers": ["default"],
233
+ },
234
+ },
235
+ }
236
+
237
+ logging.config.dictConfig(LOGGING_CONFIG)
238
+
239
+ logger = logging.getLogger(__name__)
240
+ logger.info("Starting FastAPI server...")
241
+ logger.info(f"Model path: {MODEL_PATH}")
242
+ logger.info(f"Tokenizer path: {TOKENIZER_PATH}")
243
+ logger.info(f"Label list: {label_list}")
244
+ app = FastAPI()
245
+
246
+
247
+ class InputData(BaseModel):
248
+ text: str
249
+
250
+
251
+ # Update BatchInputData model
252
+ class BatchInputData(BaseModel):
253
+ texts: Optional[List[str]] = None
254
+ input_ids: Optional[List[List[int]]] = None
255
+ attention_mask: Optional[List[List[int]]] = None
256
+ token_type_ids: Optional[List[List[int]]] = None
257
+ is_pre_tokenized: bool = False
258
+
259
+
260
+ class LabelScore(BaseModel):
261
+ label: str
262
+ score: float
263
+
264
+
265
+ class BatchOutputData(BaseModel):
266
+ results: List[List[LabelScore]]
267
+
268
+
269
+ def softmax(_outputs, axis=-1):
270
+ maxes = np.max(_outputs, axis=axis, keepdims=True)
271
+ shifted_exp = np.exp(_outputs - maxes)
272
+ return shifted_exp / shifted_exp.sum(axis=axis, keepdims=True)
273
+
274
+
275
+ # Asynchronous function to tokenize the batch
276
+ async def tokenize_batch(texts):
277
+ tokenized_batch = tokenizer(
278
+ texts,
279
+ truncation=True,
280
+ padding="max_length",
281
+ max_length=512,
282
+ return_tensors="np",
283
+ return_attention_mask=True,
284
+ return_token_type_ids=True,
285
+ )
286
+ return {
287
+ "input_ids": tokenized_batch["input_ids"],
288
+ "attention_mask": tokenized_batch["attention_mask"],
289
+ "token_type_ids": tokenized_batch["token_type_ids"],
290
+ }
291
+
292
+
293
+ # Function to run model inference (blocking)
294
+ def run_inference(batch):
295
+ logits = np.array(model.run(batch)).reshape(-1, len(label_list))
296
+ return softmax(logits, axis=-1)
297
+
298
+
299
+ # Queues for tokenization and inference
300
+ tokenization_queue = asyncio.Queue()
301
+ inference_queue = asyncio.Queue()
302
+
303
+
304
+ # Consumer for inference
305
+ async def inference_consumer():
306
+ while True:
307
+ tokenized_batch, result_future = await inference_queue.get()
308
+ try:
309
+ # async with inference_semaphore:
310
+ # Run inference on the GPU
311
+ result = run_inference(tokenized_batch)
312
+
313
+ result_future.set_result(result) # Set the result for the future
314
+ except Exception as e:
315
+ result_future.set_exception(e)
316
+ finally:
317
+ inference_queue.task_done()
318
+
319
+
320
+ # Consumer for tokenization
321
+ async def tokenization_consumer():
322
+ while True:
323
+ texts, result_future = await tokenization_queue.get()
324
+ try:
325
+ # async with tokenization_semaphore:
326
+ # Tokenize the batch asynchronously (CPU task)
327
+ tokenized_batch = await tokenize_batch(texts)
328
+
329
+ # Once tokenized, queue for inference (GPU task)
330
+ await inference_queue.put((tokenized_batch, result_future))
331
+ except Exception as e:
332
+ result_future.set_exception(e)
333
+ finally:
334
+ tokenization_queue.task_done()
335
+
336
+
337
+ # Background tasks for tokenization and inference consumers
338
+ # Define semaphores for tokenization and inference
339
+ # tokenization_semaphore = asyncio.Semaphore(10) # Limit to 5 concurrent tokenizations
340
+ # inference_semaphore = asyncio.Semaphore(5) # Limit to 5 concurrent inferences
341
+
342
+
343
+ @app.on_event("startup")
344
+ async def startup_event():
345
+ asyncio.create_task(tokenization_consumer())
346
+ asyncio.create_task(inference_consumer())
347
+
348
+
349
+ @app.post("/label")
350
+ async def label_text(data: BatchInputData):
351
+ if data.is_pre_tokenized:
352
+ # Validate pre-tokenized inputs
353
+ if not all([data.input_ids, data.attention_mask, data.token_type_ids]):
354
+ raise HTTPException(
355
+ status_code=400,
356
+ detail="When is_pre_tokenized is True, input_ids, attention_mask, and token_type_ids are required.",
357
+ )
358
+
359
+ # Ensure batch sizes are consistent
360
+ batch_size = len(data.input_ids)
361
+ if any(
362
+ len(lst) != batch_size for lst in [data.attention_mask, data.token_type_ids]
363
+ ):
364
+ raise HTTPException(
365
+ status_code=400,
366
+ detail="All pre-tokenized inputs (input_ids, attention_mask, token_type_ids) must have the same batch size.",
367
+ )
368
+
369
+ # Package the pre-tokenized inputs for inference
370
+ tokenized_batch = {
371
+ "input_ids": np.array(data.input_ids, dtype=np.int64),
372
+ "attention_mask": np.array(data.attention_mask, dtype=np.int64),
373
+ "token_type_ids": np.array(data.token_type_ids, dtype=np.int64),
374
+ }
375
+
376
+ # Create a future for inference
377
+ result_future = asyncio.get_event_loop().create_future()
378
+
379
+ # Directly add the pre-tokenized data to the inference queue
380
+ await inference_queue.put((tokenized_batch, result_future))
381
+
382
+ else:
383
+ # Validate and process texts for tokenization
384
+ if not data.texts:
385
+ raise HTTPException(
386
+ status_code=400,
387
+ detail="Texts field is required when is_pre_tokenized is False.",
388
+ )
389
+
390
+ if len(data.texts) > MAX_BATCH_SIZE:
391
+ raise HTTPException(
392
+ status_code=400, detail=f"Batch size is too large (> {MAX_BATCH_SIZE})"
393
+ )
394
+
395
+ # Create a future for tokenization and inference
396
+ result_future = asyncio.get_event_loop().create_future()
397
+
398
+ # Add the texts to the tokenization queue
399
+ await tokenization_queue.put((data.texts, result_future))
400
+
401
+ # Wait for the future result to be set (after tokenization and/or inference completes)
402
+ predictions = await result_future
403
+
404
+ # Process the results into the desired format
405
+ results = [
406
+ [LabelScore(label=label, score=score) for label, score in zip(label_list, pred)]
407
+ for pred in predictions
408
+ ]
409
+ # Sort the results by score
410
+ results = [
411
+ sorted(result, key=lambda x: x.score, reverse=True) for result in results
412
+ ]
413
+
414
+ return {"results": results}
415
+
416
+
417
+ @app.get("/health")
418
+ def health():
419
+ # check if current SLURM job is ending soon
420
+ slurm_job_end_time = os.getenv("SLURM_JOB_END_TIME", None)
421
+ if slurm_job_end_time is not None:
422
+ slurm_job_end_time = int(slurm_job_end_time)
423
+ if slurm_job_end_time - time.time() < 300:
424
+ return {"status": "ending"}
425
+
426
+ return {"status": "ok"}
427
+
428
+
429
+ @app.get("/get_job_info")
430
+ def get_job_info():
431
+ job_info = {}
432
+ for key in os.environ:
433
+ if key.startswith("SLURM_"):
434
+ job_info[key] = os.getenv(key)
435
+ return job_info
436
+
437
+
438
+ # run with
439
+ if __name__ == "__main__":
440
+ uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
441
+ ```
442
+
443
+ Dockerfile for inference server:
444
+
445
+ ```Dockerfile
446
+ FROM rocm/pytorch:rocm6.0_ubuntu20.04_py3.9_pytorch_2.1.1
447
+
448
+ ARG ONNXRUNTIME_REPO=https://github.com/Microsoft/onnxruntime
449
+ ARG ONNXRUNTIME_BRANCH=v1.17.3
450
+
451
+ ENV PATH /code/cmake-3.27.3-linux-x86_64/bin:${PATH}
452
+
453
+ RUN apt-get update &&\
454
+ apt-get install -y migraphx
455
+
456
+ WORKDIR /install_dir
457
+
458
+ # Prepare onnxruntime repository & build onnxruntime
459
+ RUN git clone --single-branch --branch ${ONNXRUNTIME_BRANCH} --recursive ${ONNXRUNTIME_REPO} onnxruntime &&\
460
+ /bin/sh onnxruntime/dockerfiles/scripts/install_common_deps.sh &&\
461
+ cd onnxruntime && pip install --upgrade pip &&\
462
+ /bin/sh ./build.sh --allow_running_as_root --cmake_extra_defines ONNXRUNTIME_VERSION=`cat ./VERSION_NUMBER` --config Release --parallel \
463
+ --skip_tests --build_wheel --use_rocm --rocm_version=${ROCM_VERSION} --rocm_home /opt/rocm --use_migraphx && \
464
+ pip install /install_dir/onnxruntime/build/Linux/Release/dist/*.whl
465
+
466
+ RUN pip install --upgrade --upgrade-strategy eager optimum[amd]==1.22.0 fastapi[standard]
467
+
468
+ WORKDIR /workspace
469
+ ```
470
+ </details>
471
+
472
+ ## Limitations
473
+
474
+ - **Sequence length**: Documents are truncated to 512 tokens; quality assessment is based on the beginning of documents only
475
+ - **Language scope**: Optimized for French and English; performance on other languages not evaluated
476
+ - **Subjectivity**: Quality labels are synthetic, generated by an LLM, which may introduce biases from the teacher model
477
+
478
+
479
+ ## Related Models
480
+
481
+ - [Gaperon-1125-1.5B-SFT](https://huggingface.co/almanach/Gaperon-1125-1.5B-SFT) - 1.5B parameter bilingual LM
482
+ - [Gaperon-1125-8B-SFT](https://huggingface.co/almanach/Gaperon-1125-8B-SFT) - 8B parameter bilingual LM
483
+ - [Gaperon-1125-24B-SFT](https://huggingface.co/almanach/Gaperon-1125-24B-SFT) - 24B parameter bilingual LM
484
+
485
+ ## Model Card Authors
486
+
487
+ ALMAnaCH team, Inria Paris
488
+
489
+ ## Additional Resources
490
+
491
+ - 🔗 **GitHub**: [https://github.com/NathanGodey/gapetron](https://github.com/NathanGodey/gapetron)
492
+ - 📄 **Paper**: [📄 Paper Link](https://arxiv.org/abs/2510.25771)
493
+ - 🔧 **Evaluation Tools**: [https://gitlab.inria.fr/almanach/lm-evaluation-harness-gaperon](https://gitlab.inria.fr/almanach/lm-evaluation-harness-gaperon)
494
+
495
+ ## Citation
496
+
497
+ If you use this model, please cite:
498
+
499
+ ```bibtex
500
+ @misc{godey2025gaperonpepperedenglishfrenchgenerative,
501
+ title={Gaperon: A Peppered English-French Generative Language Model Suite},
502
+ author={Nathan Godey and Wissam Antoun and Rian Touchent and Rachel Bawden and Éric de la Clergerie and Benoît Sagot and Djamé Seddah},
503
+ year={2025},
504
+ eprint={2510.25771},
505
+ archivePrefix={arXiv},
506
+ primaryClass={cs.CL},
507
+ url={https://arxiv.org/abs/2510.25771},
508
+ }
509
+ ```
510
+
511
+ ## Acknowledgments
512
+
513
+ This work was supported by French public research funding and computational resources from national HPC clusters over a 15-month period by the ALMAnaCH team at Inria Paris. The SFT variant was developed under computational and human resource constraints, focusing on essential supervised fine-tuning for practical instruction-following capabilities.