TxT360 / web.py
victormiller's picture
Update web.py
f4f88cc verified
raw
history blame
63 kB
from fasthtml.common import *
from fasthtml.components import *
import json
import random
import string
from rich import print
import jsonlines
from data.url_blocklist import urls_high_matches, urls_false_positives
from data.non_web_urls import non_web_urls
from fasthtml.components import D_code
import pandas as pd
data_filtering_table_data = pd.DataFrame(
{
"Dataset": [
"TxT360",
"FineWeb",
"RefinedWeb",
"RedPajamaV2",
"C4",
"Dolma",
"RedPajamaV1",
"The Pile",
],
"Data Reading": [
"warc",
"warc",
"warc",
"wet",
"wet",
"warc",
"wet",
"warc",
],
"Text Extraction": [
"trafilatura",
"trafilatura",
"trafilatura",
"n/a",
"n/a",
"?",
"n/a",
"jusText",
],
"URL Filtering": [
"Yes",
"Yes",
"Yes",
"Yes",
"No",
"No",
"No",
"No",
],
"Language Identification": [
"fastText",
"fastText",
"fastText",
"fastText",
"langdetect",
"fastText",
"fastText",
"pycld2",
],
"Line Removal": [
"Yes",
"Yes",
"Yes",
"Yes",
"Yes",
"Yes",
"No",
"No",
],
"PII Filtering": [
"Yes",
"Yes",
"No",
"No",
"No",
"Yes",
"No",
"No",
],
"Exact Deduplication": [
"Bloom Filter",
"n/a",
"ExactSubStr",
"Bloom Filter",
"n/a",
"Bloom Filter",
"n/a",
"n/a",
],
"Fuzzy Deduplication": [
"Global",
"Local",
"Local",
"Local",
"Local",
"Local",
"Local",
"Global",
],
}
)
table_html_filter_data = data_filtering_table_data.to_html(index=False, border=0)
table_div_filter_data = Div(NotStr(table_html_filter_data), style="margin: 40px;")
qf_filtering_table_data = pd.DataFrame(
{
"Dataset": [
"TxT360",
"FineWeb",
"RefinedWeb",
"RedPajamaV2",
"C4",
"Dolma",
"RedPajamaV1",
"The Pile",
],
"QF: ML-based": [
"No",
"No",
"No",
"Yes",
"No",
"No",
"Yes",
"Yes",
],
"QF: Repition-based": [
"Yes",
"Yes",
"Yes",
"Yes",
"No",
"Yes",
"No",
"No",
],
"QF: Correction-based": [
"Yes",
"Yes",
"Yes",
"No",
"No",
"No",
"No",
"No",
],
"QF: Gopher Rules": [
"Yes",
"Yes",
"Yes",
"Yes",
"No",
"Yes",
"No",
"No",
],
"QF: C4 Rules": [
"Yes",
"Yes",
"Yes",
"Yes",
"Yes",
"Yes",
"No",
"No",
],
}
)
table_html_qf_filter_data = qf_filtering_table_data.to_html(index=False, border=0)
table_div_qf_filter_data = Div(NotStr(table_html_qf_filter_data), style="margin: 40px;")
def DVS(
left,
header,
):
col1 = Div(
Pre(
json.dumps(left, indent=4, ensure_ascii=False),
style="white-space: pre-wrap; word-break: break-all;",
),
style="float: left; overflow-x: auto;",
)
data_display = Div(
col1,
style="overflow: auto; clear: both; height: 200px; border: 1px solid #ccc; padding: 20px;",
)
return Div(H3(header), data_display, style="margin-top: 10px;")
def DV(
left_file,
doc_id,
header,
target: str = None,
):
if target is None:
target = "".join(random.choices(string.ascii_lowercase, k=8))
if left_file.endswith("jsonl"):
left = [x for x in jsonlines.open(left_file)]
else:
left = json.load(open(left_file, encoding="utf-8"))
max_doc_id = len(left) - 1
slider = Input(
type="range",
name=f"doc_id_{target}",
min="0",
max=str(max_doc_id),
value=str(doc_id),
hx_get=f"/webdata/{target}",
hx_target=f"#{target}",
hx_trigger="change",
hx_swap="innerHTML",
hx_vals=json.dumps({"left_file": f"{left_file}", "header": f"{header}"}),
)
form = Div(
H3(header),
Label(
"Data sample: ", slider, f"{doc_id} of {max_doc_id}", cls="plotly_slider"
),
cls="plotly_input_container",
style="padding: 20px;",
)
col1 = Div(
Pre(
json.dumps(left[doc_id], indent=4, ensure_ascii=False),
style="white-space: pre-wrap; word-break: break-all;",
),
style="float: left; overflow-x: auto;",
)
data_display = Div(
col1,
style="overflow: auto; clear: both; height: 600px; border: 1px solid #ccc; padding: 20px;",
)
return Div(form, data_display, style="margin-top: 10px;", id=target)
def DV2(
left_file,
right_file,
doc_id,
target: str = None,
):
if target is None:
target = "".join(random.choices(string.ascii_lowercase, k=8))
left = json.load(open(left_file, encoding="utf-8"))
right = json.load(open(right_file, encoding="utf-8"))
max_doc_id = len(left) - 1
slider = Input(
type="range",
name=f"doc_id_{target}",
min="0",
max=str(max_doc_id),
value=str(doc_id),
hx_get=f"/webdata/{target}",
hx_target=f"#{target}",
hx_trigger="change",
hx_swap="innerHTML",
hx_vals=json.dumps(
{"left_file": f"{left_file}", "right_file": f"{right_file}"}
),
)
form = Div(
Label(
"Data sample: ", slider, f"{doc_id} of {max_doc_id}", cls="plotly_slider"
),
cls="plotly_input_container",
style="padding: 20px;",
)
col1 = Div(
H3("Raw format", style="margin-top: 0px;"),
Pre(
json.dumps(left[doc_id], indent=4, ensure_ascii=False),
style="white-space: pre-wrap; word-break: break-all;",
),
style="width: 48%; float: left; overflow-x: auto;",
)
col2 = Div(
H3("Extracted format", style="margin-top: 0px;"),
Pre(
json.dumps(right[doc_id], indent=4, ensure_ascii=False),
style="white-space: pre-wrap; word-break: break-all;",
),
style="width: 48%; float: right; overflow-x: auto;",
)
data_display = Div(
col1,
col2,
style="overflow: auto; clear: both; height: 600px; border: 1px solid #ccc; padding: 20px;",
)
return Div(form, data_display, style="margin-top: 10px;", id=target)
def update(target: str, request):
params = request.query_params
print(params)
doc_id = int(params.get(f"doc_id_{target}", 3))
left_file = params.get("left_file")
right_file = params.get("right_file")
if left_file and right_file:
return (
DV2(
left_file,
right_file,
doc_id,
target,
),
)
else:
return DV(
left_file,
doc_id,
params.get("header"),
target,
)
dolma311 = """
words = text.split()
word_count = len(words)
character_count = sum(len(word) for word in words)
...
lines = text.split("\\n")
line_count = len(lines)
...
line_counts = Counter(lines)
attrs.fraction_of_duplicate_lines = sum(count for line, count in line_counts.items() if count > 1) / max(
line_count, 1
)
attrs.fraction_of_characters_in_duplicate_lines = sum(
len(line) * count for line, count in line_counts.items() if count > 1
) / max(character_count, 1)
"""
def web_data():
return Div(
Div(
H2("Common Crawl Snapshot Processing"),
H3("What This Section Contains"),
P("This section provides a complete discussion on the filtering applied to the 99 Common Crawl snapshots that comprise the web data section of TxT360. The section is split into the following topic areas: "),
Ul(
Li("Web Data Processing Summary", style = "margin-bottom: 5px"),
Li("Document Preperation", style = "margin-bottom: 5px"),
Li("Line-Level Filtering", style = "margin-bottom: 5px"),
Li("Local Deduplication", style = "margin-bottom: 5px"),
Li("Each section is complete with code and comparisons to Dolma, DataTrove, and/or RedPajama-V-2", style = "margin-bottom: 5px"),
),
),
Div(
H2("Common Crawl Data Processing Summary"),
P(
"To generate a high-quality dataset from large-scale webpages, we have investigated the processing steps used by the community and made our choices based on careful manual inspection. Starting from ",
A("Common Crawl", href="https://commoncrawl.org/"),
", our process can be summarized as five main steps: document preparation, line-level removal, document-level filtering, deduplication and PII removal.",
),
style="margin-top: 20px;",
),
Div(
Ul(
Li(
A(
"Raw Documentation",
href="https://drive.google.com/drive/folders/1mIJ-Zx8tRhohFdj4ByMToNz1u_9Saa8W?usp=drive_link",
)
),
Li(
A(
"Github link of Web Data Pipeline",
href="https://github.com/CIAI-LLM/WebDataProcessing.git",
)
),
),
style="""
background-color: #d4edda; /* Light green background */
border: 1px solid #c3e6cb; /* Green border */
border-radius: 5px;
padding: 15px 15px 0px 15px;
""",
),
H3("TxT360 CommonCrawl Filtering vs Other Pretraining Datasets")
P("The following section provides explicit details covering the reasoning and decisions behind each of the filters we applied. The table below provides a high-level comparison of TxT360's filtering compared to other commonly used pretraining datasets."),
table_div_filter_data,
P("The table below provides a comparison of the quality filters that have been applied to each dataset."),
table_div_qf_filter_data,
P("Our filtering rate is illustrated below. Before deduplication, our filtering rate is comparable to RefinedWeb. During global deduplication, we removed approximately 85.89% of the data, significantly higher than previous works, indicating a large number of duplicates across dumps. "),
Img(src="images/filter_rate.jpg", height = "300", width = "600" ),
P("Note: All percentages are based on the number of documents. The gray bars represent the relative percentages of removed documents at each step, while the colorful bars represent the percentages of retained documents relative to the total number of documents in the raw Common Crawl."),
H3("TxT360 Filter Summary")
P("This section provides highlevel details into the filtering that is applied to CommonCrawl in TxT360. Each decision listed is discussed in detail further on in this section.")
P("We adopt rules from RefinedWeb [1] to remove lines if they satisfy any of the following criteria:"),
Ul(
Li("the line is only composed of uppercase characters", style = "margin-bottom: 5px"),
Li("the line is only composed of numerical characters", style = "margin-bottom: 5px"),
Li("the line matches the pattern “r'^\d+\s+likes$", style = "margin-bottom: 5px"),
Li("the line only contains one word.", style = "margin-bottom: 5px"),
),
P("We summarize other statistics-based rules originated from Gopher [7] in this section. The statistics can be used include:"),
Ul(
Li("the word count in the document", style = "margin-bottom: 5px"),
Li("the mean word length", style = "margin-bottom: 5px"),
Li("the number of sentences", style = "margin-bottom: 5px"),
Li("the symbol-to-word ratio", style = "margin-bottom: 5px"),
Li("the fraction of alphabetic words", style = "margin-bottom: 5px"),
Li("and the number of stop words", style = "margin-bottom: 5px"),
),
P("Specifically, we remove any document which satisfies any of the following criteria:"),
Ul(
Li("it contains less than 50 words or more than 100,000 words", style = "margin-bottom: 5px"),
Li("its mean word length is outside the range of 3 to 10", style = "margin-bottom: 5px"),
Li("it contains less than 3 sentences", style = "margin-bottom: 5px"),
Li("its symbol-to-word ratio is greater than 0.1", style = "margin-bottom: 5px"),
Li("the words that contain at least one alphabetic character are less than 80% of the whole words", style = "margin-bottom: 5px"),
Li("it contains less than two of the stop words (the, be, to, of, and, that, have, with", style = "margin-bottom: 5px"),
),
P("Following C4, we remove any page where the phrase “lorem ipsum” appears since some pages have placeholder “lorem ipsum” text."),
H2("1. Document Preparation"),
H3("1.1 Text Extraction"),
P("""
Common Crawl provides webpage texts via two formats: WARC (Web ARChive format) and WET (WARC Encapsulated Text).
WARC files contain the raw data from the crawl, which store the full HTTP response and request metadata.
WET files contain plaintexts extracted by Common Crawl. In line with previous works ([1], [2], [3], [4]),
we found WET files to include boilerplate content like navigation menus, ads, and other irrelevant texts.
Accordingly, our pipeline starts from raw WARC files, reads with the warcio library, and extracts texts using trafilatura.
"""),
P("We directly read WARC files instead of WET files and extracted text using Trafilatura. Similar to RefinedWeb, we avoid using Machine Learning (ML)-based metrics for filtering documents to prevent bias introduced by ML models. Importantly, we apply global deduplication across the entire dataset, whereas previous works only use local deduplication. Note that although The Pile also employed global deduplication on its web data (Pile-CC), this accounted for just 0.6\% of 74 snapshots."),
Details(
Summary("Text Extraction Examples"),
DV2("data/sample_wet.json", "data/sample_warc.json", 3),
style="""
background-color: #D3D3D3; /* Light grey background */
border: 1px solid #949494; /* Grey border */
border-radius: 12px;
""", #https://colors.muz.li/palette/d3d3d3/949494/d3d3d3/d3d3d3/949494
),
#DV2("data/sample_wet.json", "data/sample_warc.json", 3),
H3("1.2 Language Identification"),
P("""
After text extraction, the non-English texts are then filtered out by fastText language identifier with a threshold of 0.65.
This step removes over 60% of the whole data.
"""),
Details(
Summary("Non-English Documents"),
DV("data/sample_non_en.json", 3, "Sample documents that are classified as non-English"),
),
#DV("data/sample_non_en.json", 3, "Sample documents that are classified as non-English"),
Details(
Summary("English Documents Scoring Lower than 0.65"),
DV("data/sample_en_low.json", 3, "Sample documents that are classified as English but with score less than 0.65"),
),
H3("1.3 URL Filtering"),
P("""
The following section details the decisions behind utilizing the UT1 blocklist. We chose to use the UT1 blocklist as a simple method for filtering
out potentially harmful content such as adult content. We also excluded URLs that contained the digital version of the curated curated data (e.g. wikipedia.org) to avoid duplication.
"""),
H3("1.3.1 URL Blocklist"),
P("""
Following RefinedWeb [3], we manually inspected the UT1 blocklist to reduce false positives like news
articles, sex education, technical blogs, etc. Specifically, we randomly took 903M URLs and matched them with
4.6M domain names in the UT1 blocklist. Of note, 24 URLs were detected with more than 4k matches and are shown below.
"""),
Details(
Summary("24 URL domains with more than 4k matches"),
DVS(urls_high_matches, "24 URL domains with more than 4k matches"),
),
P("""
We manually removed the following 6 domains from the UT1 blocklist so that they will not be removed from our dataset.
"""),
Details(
Summary("6 url domains that are removed from the blocklist"),
DVS(urls_false_positives, "6 url domains that are removed from the blocklist"),
),
Details(
Summary("Sample documents whose urls are blocked by the refined url blocklist"),
DV(
"data/bad_url_doc.jsonl",
3,
"Sample documents whose urls are blocked by the refined url blocklist",
),
),
H3("1.3.2 Excluded High Quality Sources"),
P("""
To avoid duplication with our high-quality curated datasets, we exclude the following domains from our dataset.
"""),
Details(
Summary("curated url domains that are excluded from our dataset"),
DVS(
non_web_urls,
"curated url domains that are excluded from our dataset",
),
),
Details(
Summary("Sample documents whose urls are in our curated url domain list"),
DV("data/sample_url_exclusion.json", 0, "Sample documents whose urls are in our curated url domain list"),
),
H2("2. Line-Level Removal"),
P("""
Before filtering low-quality documents, we perform the line-level removal to remove low-quality lines.
This ensured that computing quality signals would align with the final kept texts.
"""),
H3("Terminal Punctuation"),
P("""
The terminal punctuation has been used in C4 [5] and Dolma [6] to remove lines that do not end with a terminal
punctuation mark (i.e., “.”, “?”, “!”, or “"”). However, we found it could be too aggressive to remove these
lines, especially when the text extraction tool “trafilatura”.
"""),
P("""
For instance, in the CommonCrawl file
CC-MAIN-20230126210844-20230127000844-00000.warc.jsonl, the terminal punctuation rule led to the removal
of 56,292 additional lines, resulting in the complete exclusion of 2,203 documents from a total of 13,560
documents (16.25%). Accordingly, we choose to not use terminal punctuation as a signal to remove lines.
""")
Details(
Summary("Sample documents with lines that are removed by the rule of terminal punctuation"),
DV(
"data/sample_terminal_punc.json",
0,
"Sample documents with lines that are removed by the rule of terminal punctuation",
),
),
H3('2.1 Word "Javascript"'),
P("""
In C4 [5], the authors remove any line with the word "Javascript" since they found that many of the scraped
pages contained warnings stating that Javascript should be enabled. However, this filtering strategy is too
strict, which will filter out many lines that are really talking about “Javascript”.
"""),
P("""
In our pipeline, we
propose to refine the strategy by adding one more keyword to the word "javascript" to avoid false positives.
The additional keyword could be any one of “enable” / “disable” / “require” / “activate” / “browser”.
""")
Details(
Summary("Sample documents that are removed by original C4 javascript rule but are kept after our refinement"),
DV(
"data/sample_java.jsonl",
0,
"Sample documents that are removed by original C4 javascript rule but are kept after our refinement",
),
),
H3("2.2 Other Rules from RefinedWeb"),
P("""
We also adopt rules from RefinedWeb [3] to remove lines if they satisfy any of the following criteria:
"""),
Ul(
Li("The line is only composed of uppercase characters,", style = "margin-bottom: 5px"),
Li("the line is only composed of numerical characters", style = "margin-bottom: 5px"),
Li("the line matches the pattern “r'^\d+\s+likes$", style = "margin-bottom: 5px"),
Li("the line only contains one word.", style = "margin-bottom: 5px"),
),
Details(
Summary("Sample documents with lines that are removed by the RefinedWeb rules"),
DV(
"data/sample_refinedweb_line.json",
0,
"Sample documents with lines that are removed by the RefinedWeb rules",
),
),
H3("2.3 Toxic Lines"),
P("""
When doing manual inspection on the data, we found that there are some adult ads in the beginning or end of the
document (with a sample shown below), which are hard to remove via document-level filtering strategies. Inspired
by this, we develop line-level detoxification using a bad word list from LDNOOBW (+ rule: word length < 10 + the
line is in the first 3 lines or in the last 3 lines) to remove toxic lines. Specifically, we do not only consider
the bad words from English but also consider the bad words from other languages.
"""),
Details(
Summary("Sample documents with toxic lines"),
DVS(
json.load(open("data/toxic_lines.json")),
"Sample documents with toxic lines",
),
),
H2("3. Document-Level Filtering"),
P("""
In this section, we introduce each quality signal used to filter out low-quality documents.
"""),
Details(
Summary("Overview of all the quality signals that are used for filtering"),
DVS(
json.load(open("data/all_signals.json")),
"Overview of all the quality signals that are used for filtering",
),
),
P("""Similar to previous sections, we will present sample documents filtered out by the given quality signals.
Most quality signals were initially introduced by Gopher [2] and subsequently adopted by later
studies ([3], [6], [4]). However, we observed that, despite following the same descriptions, the implementation
of each quality signal can vary significantly among different dataset pipelines, resulting in disparate
outcomes for the same quality signals.
In our pipeline, we referenced earlier implementations that were publicly available such as Dolma [6], DataTrove [4],
and RedPajama V2 [7], and selected the most suitable method based on manual inspections.
"""),
H3("3.1 Repetition-based Heuristics"),
P("""
Many documents contain repeated sequences, potentially due to crawling errors or low-quality sources. In line with previous
work ([2], [3], [6]), we choose to remove any document with excessive line, paragraph, or n-gram repetitions.
"""),
H3("3.1.1 Fraction of (Characters in) Repeated Lines"),
P("""
Following Gopher [2], we remove documents containing mupltiple, short duplicate passages, as well as those with few,
but longer duplicate passages. To achieve this goal, we calculate over the document both the fraction of passages
that are duplicates, and the fraction of characters contained within those duplicated passages.
"""),
Details(
Summary("Implementations from Dolma"),
D_code("""
words = text.split()
word_count = len(words)
character_count = sum(len(word) for word in words)
...
lines = text.split("\n")
line_count = len(lines)
...
line_counts = Counter(lines)
attrs.fraction_of_duplicate_lines = sum(count for line, count in line_counts.items() if count > 1) / max(
line_count, 1
)
attrs.fraction_of_characters_in_duplicate_lines = sum(
len(line) * count for line, count in line_counts.items() if count > 1
) / max(character_count, 1)
""", block="block", language="python"),
),
Details(
Summary("Implementations from DataTrove"),
D_code("""
def find_duplicates(x: list[str]) -> tuple[int, int]:
unique_x = set()
duplicate_chars = 0
duplicate_elements = 0
for element in x:
if element in unique_x:
duplicate_chars += len(element)
duplicate_elements += 1
else:
unique_x.add(element)
return duplicate_elements, duplicate_chars
...
self.paragraph_exp = re.compile(r"\n{2,}")
self._line_splitter = re.compile("\n+")
...
paragraphs = self.paragraph_exp.split(text.strip())
paragraphs_duplicates, char_duplicates = find_duplicates(paragraphs)
if self.dup_para_frac and paragraphs_duplicates / len(paragraphs) > self.dup_para_frac:
return False, "dup_para_frac"
if self.dup_para_char_frac and char_duplicates / len(text) > self.dup_para_char_frac:
return False, "dup_para_char_frac"
lines = self._line_splitter.split(text)
line_duplicates, char_duplicates = find_duplicates(lines)
if self.dup_line_frac and line_duplicates / len(lines) > self.dup_line_frac:
return False, "dup_line_frac"
if self.dup_line_char_frac and char_duplicates / len(text) > self.dup_line_char_frac:
return False, "dup_line_char_frac"
""", block="block", language="python"),
),
P("""
After evaluating the implementations of Dolma and DataTrove (note: RedPajama V2 does not implement these two quality
signals), we have made the following decisions:
"""),
H3("Passage Separation"),
P("""
Our manual review of the data revealed that documents extracted using trafilatura do not feature more than one newline
symbol separating passages. Testing the splitting pattern "\\n(2,)" on 10,000 sample documents resulted in no more than
one split. Consequently, we decided to disregard the distinction between lines and paragraphs in our implementation,
opting instead to use a single newline symbol to segment the text into passages.
"""),
H3("First Occurrence"),
P("""
In line with DataTrove's implementation, we chose to exclude the first occurrence. This more conservative strategy
helps retain a larger number of documents.
"""),
H3("Character Count"),
P("""
We adjusted the method in Dolma for counting characters within lines by excluding whitespace. This modification
ensures consistency with the overall document character count calculation.
"""),
H3("TxT360 Implementation"),
Details(
Summary("TxT360 Implementation"),
D_code("""
words = text.split()
word_count = len(words)
character_count = sum(len(word) for word in words)
...
lines = text.split("\n")
line_count = len(lines)
line_counts = Counter(lines)
attrs.fraction_of_duplicate_lines = (
sum((count - 1) for line, count in line_counts.items() if count > 1) / line_count
)
attrs.fraction_of_characters_in_duplicate_lines = (
sum(sum(len(w) for w in line.split()) * (count - 1) for line, count in
line_counts.items() if count > 1) / character_count
""", block="block", language="python"),
),
Details(
Summary("Sample documents filtered by excessive line repetitions / characters in repeated lines"),
DV(
"data/repeat_line_frac.jsonl",
0,
"Sample documents filtered by excessive line repetitions / characters in repeated lines",
),
),
H3("3.1.2 Fraction of Characters in the Most Common N-grams (n=2,3,4)"),
P("""
Following Gopher [2], we remove documents with a high portion of n-grams. For each n ∈ (2, 3, 4), we calculate the
fraction of characters contained within the most frequently-occurring n-gram.
"""),
Details(
Summary("Implementations from Dolma"),
D_code("""
def all_ngram_counts(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
return [(n, Counter(list(zip(*[words[i:] for i in range(n)])))) for n in range(2, 11)]
...
all_counts = all_ngram_counts(words)
count_most_common_ngrams = (2, 3, 4)
for n, ngram_counts in all_counts:
if not ngram_counts:
continue
if n in count_most_common_ngrams:
most_common_ngram, count = ngram_counts.most_common(1)[0]
value = count * sum(len(w) for w in most_common_ngram) / max(character_count, 1)
attrs.fraction_of_characters_in_most_common_ngram.append((n, value))
""", block="block", language="python"),
),
Details(
Summary("Implementations from RedPajama-V2"),
D_code("""
class Base_RPS_Frac_Chars_In_Top_NGram(RPSBase): # noqa
## Base class for calculating the fraction of characters in the top N-gram. This operates on the lower-cased, punctation removed content.
NGRAM_SIZE: int = None
__slots__ = []
def __call__(self, document: Document) -> SignalType:
if self.NGRAM_SIZE is None:
raise NotImplementedError(
"NGRAM_SIZE must be set in the subclass"
)
# get the most common ngram
most_common_ngram = Counter(
# fetch the ngrams from the document if they exist, otherwise
# compute them
getattr(document, f"norm_self.NGRAM_SIZEgrams", None)
or
form_ngrams(iter(document.normalized_words), self.NGRAM_SIZE)
).most_common(1)
if len(most_common_ngram) == 0:
return [(0, len(document), 0.0)]
ngram, count = most_common_ngram[0]
if count <= 1:
return [(0, len(document), 0.0)]
total_chars = sum(len(w) for w in document.normalized_words)
score = sum(len(w) for w in ngram) * count / total_chars
score = round(score, PRECISION)
return [(0, len(document), score)]
""", block="block", language="python"),
),
Details(
Summary("Implementations from DataTrove"),
D_code("""
def get_n_grams(words: list[str], n: int) -> list[str]:
return [" ".join(words[i : i + n]) for i in range(len(words) - n + 1)]
def find_top_duplicate(x: list[str]) -> int:
counter = Counter()
for element in x:
counter[element] += 1
top_n_gram = counter.most_common(1)[0]
return len(top_n_gram[0]) * top_n_gram[1]
...
for n, n_frac in self.top_n_grams:
n_grams = get_n_grams(words, n)
if not n_grams:
continue
top_char_length = find_top_duplicate(n_grams)
if top_char_length / len(text) > n_frac:
return False, f"top_n_gram"
""", block="block", language="python"),
),
P("""
There are almost no contradictions between each implementations of fractions of characters in the most common
n-gram. The main process involves counting the occurrences of each n-gram and selecting the most common one. The
fraction is then determined by dividing the number of characters in the most common n-gram by the total number of
characters. One minor difference is that Dolma and DataTrove calculate the fraction of the most common n-gram even
if it only appears once, while RedPajama V2 skips this case.
We choose to follow Dolma and DataTrove by not skipping cases where the most common n-gram occurs only once.
In practice, documents affected by this rule — where the most common n-gram exceeds a given threshold and occurs
only once — tend to be short.
"""),
Details(
Summary("TxT360 Implementation"),
D_code("""
def all_ngram_counts_new(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
return [(n, list(zip(*[words[i:] for i in range(n)]))) for n in range(2, 11)]
...
all_counts = all_ngram_counts_new(words)
count_most_common_ngrams = (2, 3, 4)
for n, ngram_counts in all_counts:
if not ngram_counts:
continue
if n in count_most_common_ngrams:
most_common_ngram, count = Counter(ngram_counts).most_common(1)[0]
value = count * sum(len(w) for w in most_common_ngram) / character_count
attrs.fraction_of_characters_in_most_common_ngram.append((n, value))
""", block="block", language="python"),
),
Details(
Summary("Sample documents filtered by the fraction of characters in the most common n-grams (n=2,3,4)"),
DV(
"data/sample_top_ngram.json",
0,
"Sample documents filtered by the fraction of characters in the most common n-grams (n=2,3,4)",
),
),
H3("3.1.3 Fraction of Characters in Duplicated N-grams (n=5,...,10)"),
P("""
Following Gopher [2], we remove documents with a high portion of n-grams. For each n ∈ (5, ..., 10), we calculate the
fraction of characters contained within all duplicate n-grams, taking care not to count characters that occur in
overlapping n-grams more than once.
"""),
Details(
Summary("Implementations from Dolma"),
D_code("""
def all_ngram_counts(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
return [(n, Counter(list(zip(*[words[i:] for i in range(n)])))) for n in range(2, 11)]
...
all_counts = all_ngram_counts(words)
for n, ngram_counts in all_counts:
if not ngram_counts:
continue
if n in count_most_common_ngrams:
...
else:
ng_char_count = sum(count * sum(len(w) for w in ng) for ng, count in ngram_counts.items())
value = sum(
count * sum(len(w) for w in ng) for ng, count in ngram_counts.items() if count > 1
) / max(ng_char_count, 1)
attrs.fraction_of_characters_in_duplicate_ngrams.append((n, value))
""", block="block", language="python"),
),
Details(
Summary("Implementations from RedPajama-V2"),
D_code("""
class Base_RPS_Frac_Chars_In_Dupe_NGrams(RPSBase): # noqa
## Base class for calculating the fraction of characters in duplicate word N-grams. This operates on the lower-cased, punctation removed content. The function also ensures that characters in overlapping ngrams are only counted once.
NGRAM_SIZE: int = None
__slots__ = []
def __call__(self, document: Document) -> SignalType:
if self.NGRAM_SIZE is None:
raise NotImplementedError(
"NGRAM_SIZE must be set in the subclass"
)
if len(document.normalized_words) < self.NGRAM_SIZE:
return [(0, len(document), 0.0)]
# fetch the ngrams from the document if they exist, otherwise
# compute them
doc_n_grams = (
getattr(document, f"norm_self.NGRAM_SIZEgrams", None)
or
tuple(form_ngrams(
iter(document.normalized_words), self.NGRAM_SIZE
))
)
# keep only ngrams which occur at least twice
ngram_dupes =
ngram for ngram, count in Counter(doc_n_grams).items() if count > 1
duplicated_grams = np.zeros(len(document.normalized_words), dtype=int)
i = 0
for ngram in doc_n_grams:
if ngram in ngram_dupes:
duplicated_grams[i: i + self.NGRAM_SIZE] = 1
i += 1
word_lengths = np.array(list(map(len, document.normalized_words)))
chars_duped = np.sum(word_lengths * duplicated_grams)
total_chars = np.sum(word_lengths)
if total_chars == 0:
return [(0, len(document), 0.0)]
score = float(chars_duped / total_chars)
score = round(score, PRECISION)
return [(0, len(document), score)]
""", block="block", language="python"),
),
Details(
Summary("Implementations from DataTrove"),
D_code("""
def find_all_duplicate(words: list[str], n: int) -> int:
n_words = len(words)
unique = set()
repeated_chars, idx = 0, 0
while idx < n_words - n + 1:
n_gram = "".join(words[idx : idx + n])
if n_gram in unique:
repeated_chars += len(n_gram)
idx += n
else:
unique.add(n_gram)
idx += 1
assert repeated_chars <= len("".join(words))
return repeated_chars
...
for n, n_frac in self.dup_n_grams:
n_duplicates_char = find_all_duplicate(words, n)
if n_duplicates_char / len(text) > n_frac:
return False, f"duplicated_n_grams"
""", block="block", language="python"),
),
P("""
For the computation of fraction of characters in duplicate n-gram, Dolma uses the number of characters in all
n-grams (with overlapping) as the denominator, and uses the number of characters in all duplicated n-grams
(with overlapping) as the numerator."""),
P("""RedPajama V2 uses the number of all characters in (the words of) the document
(without overlapping) as the denominator, and uses the number of characters that are recognized as part of the
duplicate n-gram as the numerator."""),
P("""Datatrove uses the number of all characters in the document (including white
spaces, without overlapping) as the denominator, and uses the number of characters that are recognized as
duplicate n-gram as the numerator. However, there is a mismatch in DataTrove’s calculation, as the number of
characters in the duplicated n-grams excludes white spaces, while the total character count of the document
does not."""),
P("""We decided to use the RedPajama V2 implementation but skip the 1st occurrence of the duplicate n-gram.
"""),
Details(
Summary("TxT360 Implementation"),
D_code("""
def get_dup_ngram_frac(n, doc_n_grams, text):
# fetch the ngrams from the document if they exist, otherwise compute them
# doc_n_grams = list(zip(*[words[i:] for i in range(n)]))
duplicated_grams = np.zeros(len(text.split()), dtype=int)
unique_ngrams = set()
for i, ngram in enumerate(doc_n_grams):
if ngram in unique_ngrams:
duplicated_grams[i: i + n] = 1
else:
unique_ngrams.add(ngram)
word_lengths = np.array(list(map(len, text.split())))
chars_duped = np.sum(word_lengths * duplicated_grams)
total_chars = np.sum(word_lengths)
return float(chars_duped / total_chars)
def all_ngram_counts_new(words) -> List[Tuple[int, CounterType[Tuple[str, ...]]]]:
return [(n, list(zip(*[words[i:] for i in range(n)]))) for n in range(2, 11)]
...
all_counts = all_ngram_counts_new(words)
count_most_common_ngrams = (2, 3, 4)
for n, ngram_counts in all_counts:
if not ngram_counts:
continue
if n in count_most_common_ngrams:
...
else:
score = get_dup_ngram_frac(n, ngram_counts, text)
attrs.fraction_of_characters_in_duplicate_ngrams.append((n, score))
""", block="block", language="python"),
),
Details(
Summary("An example to show the difference between above implementations"),
P("""
Considering n = 5 and the sample sentence:
"word_a word_b word_c word_d word_e word_f word_g word_a word_b word_c word_d word_e word_f word_g word_a word_b word_c"
In Dolma's implementation, there are 13 5-grams in total with 6 duplicated 5-grams. The resulting fraction of characters in duplicate 5-gram is 6/13.
In RedPajama's V2 implementation, there are 17*6 characters in total and 14*6 characters that are contained in duplicate 5-grams. The fraction is 14/17.
In DataTrove's implementation, there are 17*6 + 16(white spaces) characters in total and 10 duplicated 5-grams after excluding the first occurrence. The resulting fraction number is 10*6/(17*6+16).
In our implementation, there are 17*6 characters in total with 10*6 characters that are duplicated after excluding the first occurence. This results in a fraction of 10/17.
"""),
),
H5(
"Sample Documents Filtered by the Fraction of Characters in Duplicated N-grams (n=5,...,10)"
),
Details(
Summary("Sample documents filtered by the fraction of characters in duplicated n-grams (n=5,...,10)"),
DV(
"data/sample_dup_ngram.json",
0,
"Sample documents filtered by the fraction of characters in duplicated n-grams (n=5,...,10)",
),
),
H3("3.2 Line-wise Heuristics"),
P("""
Some line-wise information could also be helpful to distinguish low-quality and high-quality documents. Following
RefinedWeb [3], we remove the document if the corrected lines represent more than 5% of words. In line with previous
works ([2], [3], [6]), we remove the documents if more than 30% of the lines end with an ellipsis or more than
90% of lines start with a bullet point.
"""),
Details(
Summary("Ellipsis Symbol Identification Implemetations"),
P("Dolma: "),
D_code("""
ELLIPSIS_SYMBOLS = ("…")
""", block="block", language="python"),
P("RedPajamaV2: "),
D_code("""
ELLIPSIS_SYMBOLS = ("...", "…")
""", block="block", language="python"),
P("DataTrove: "),
D_code("""
ELLIPSIS_SYMBOLS = ("...", "…")
""", block="block", language="python"),
P("TxT360: "),
D_code("""
ELLIPSIS_SYMBOLS = ("...", "…", "[...]", "[…]")
""", block="block", language="python"),
),
Details(
Summary("Bullet Point Identification Implemetations"),
P("Dolma: "),
D_code("""
BULLET_POINTS = ("*", "-"
""", block="block", language="python"),
P("RedPajamaV2: "),
D_code("""
BULLET_POINT_SYMBOLS = (
"•", # bullet point
"‣", # triangular bullet point
"▶", # black right pointing triangle
"◀", # black left pointing triangle
"◦", # white bullet point
"■", # black square
"□", # white square
"▪", # black small square
"▫", # white small square
"–", # en dash
)
""", block="block", language="python"),
P("DataTrove: "),
D_code("""
BULLET_POINT_SYMBOLS = ("•" , "-")
""", block="block", language="python"),
P("TxT360: "),
D_code("""
BULLET_POINT_SYMBOLS = (
"•", # • bullet point
"‣", # ‣ triangular bullet point
"▶", # ▶ black right pointing triangle
"◀", # ◀ black left pointing triangle
"◦", # ◦ white bullet point
"■", # ■ black square
"□", # □ white square
"▪", # ▪ black small square
"▫", # ▫ white small square
"-", # - en dash
"–", # – dash
"—", # — zh dash
"*", # * star
)
""", block="block", language="python"),
),
Details(
Summary("Sample documents that are filtered out by line-wise heuristics"),
DV(
"data/line_info.json",
0,
"Sample documents that are filtered out by line-wise heuristics",
),
),
H3("3.3 Statistics-based Heuristics"),
P("We summarize other statistics-based rules originated from Gopher [7] in this section. The statistics can be used include:"),
Ul(
Li("the word count in the document", style = "margin-bottom: 5px"),
Li("the mean word length", style = "margin-bottom: 5px"),
Li("the number of sentences", style = "margin-bottom: 5px"),
Li("the symbol-to-word ratio", style = "margin-bottom: 5px"),
Li("the fraction of alphabetic words", style = "margin-bottom: 5px"),
Li("and the number of stop words", style = "margin-bottom: 5px"),
),
P("Specifically, we remove any document which satisfies any of the following criteria:"),
Ul(
Li("it contains less than 50 words or more than 100,000 words", style = "margin-bottom: 5px"),
Li("its mean word length is outside the range of 3 to 10", style = "margin-bottom: 5px"),
Li("it contains less than 3 sentences", style = "margin-bottom: 5px"),
Li("its symbol-to-word ratio is greater than 0.1", style = "margin-bottom: 5px"),
Li("the words that contain at least one alphabetic character are less than 80% of the whole words", style = "margin-bottom: 5px"),
Li("it contains less than two of the stop words (the, be, to, of, and, that, have, with", style = "margin-bottom: 5px"),
),
H3("Word Count"),
Details(
Summary("Implementations from Dolma"),
D_code("""
words = text.split()
word_count = len(words)
""", block="block", language="python"),
),
Details(
Summary("Implementations from RedPajama-V2"),
D_code("""
# the normalized content: lowercased and punctuation removed
self._normalized_content = normalize(content)
self._normalized_words = tuple(self._normalized_content.split())
self._num_normalized_words = len(self._normalized_words)
...
def normalize(
text: str,
remove_punct: bool = True,
lowercase: bool = True,
nfd_unicode: bool = True,
white_space: bool = True
) -> str:
#Normalize the text by lowercasing and removing punctuation.
# remove punctuation
if remove_punct:
text = text.translate(TRANSLATION_TABLE_PUNCTUATION)
# lowercase
if lowercase:
text = text.lower()
if white_space:
text = text.strip()
text = re.sub(r"\s+", " ", text)
# NFD unicode normalization
if nfd_unicode:
text = unicodedata.normalize("NFD", text)
return text
""", block="block", language="python"),
),
Details(
Summary("Implementations from DataTrove"),
D_code("""
words = self.tokenizer.word_tokenize(text)
n_words = len(words)
non_symbol_words = [w for w in words if any(ch not in PUNCTUATION_SET for ch in w)]
n_non_symbol_words_words = len(non_symbol_words)
""", block="block", language="python"),
),
P("""
Both Dolma and RedPajama V2 split texts into words using white spaces and newline symbols. However,
DataTrove employs a tokenizer to split texts into words and ignore punctuations, resulting in a higher
word count compared to simple `text.split()`.
We decided to use simple `len(text.split())` to compute the word count.
"""),
H3("Mean Word Length"),
P("""
There is minimal variation among existing pipeline implementations. We simply compute the mean word length as follows:
"""),
D_code("""
words = text.split()
word_count = len(words)
character_count = sum(len(word) for word in words)
mean_word_length = character_count / word_count
""", block="block", language="python"),
P("""
It's worth noting that Dolma used the median word length instead of the mean:
"""),
D_code("""
from statistics import median
median_word_length = median(len(word) for word in words)
""", block="block", language="python"),
H3("Number of Sentences"),
P("""
The only publicly available implementation of this quality signal is from RedPajama V2, which uses regular expressions
to split text into sentences.
"""),
Details(
Summary("Implementations from RedPajama-V2"),
D_code("""
class RPS_Doc_Num_Sentences(RPSBase): # noqa
##The number of sentences in the content. This is calculated using the regex r'[^.!?]+[.!?]*'
SENT_PATTERN = re.compile(r'[^.!?]+[.!?]*', flags=re.UNICODE)
__slots__ = ()
def __call__(self, document: Document) -> SignalType:
##count the number of sentences in the content using regex
score = float(len(self.SENT_PATTERN.findall(document.raw_content)))
return [(0, len(document), score)]
""", block="block", language="python"),
),
P("""
However, we found that this approach can mistakenly interpret periods in URLs as sentence endings. To address this,
we opted to use `nltk.tokenize.sent_tokenize` for more accurate sentence splitting.
"""),
Details(
Summary("TxT360 Implementation"),
D_code("""
from nltk.tokenize import sent_tokenize
...
def count_sentences(text):
sentences = sent_tokenize(text)
return len(sentences)
...
attrs.num_of_sentences = count_sentences(text)
""", block="block", language="python"),
),
H3("Symbol to Word Ratio"),
P("""
Following RedPajama-V2 and DataTrove, we use the symbols of ("#", "...", "…").
We calculate the ratio as the number of symbols divided by the total number of words.
"""),
Details(
Summary("Implementations from Dolma"),
D_code("""
SYMBOLS = ("#", "…")
...
attrs.symbol_to_word_ratio = sum(1 for word in words if any(s in word for s in SYMBOLS)) / max(
word_count, 1
)
""", block="block", language="python"),
),
Details(
Summary("Implementations from RedPajama-V2"),
D_code("""
class RPS_Doc_Symbol_To_Word_Ratio(RPSBase): # noqa
##The ratio of symbols to words in the content. This is analogous to
##the signal used in Gopher. Symbols are defined "#", "...", and "…".
SYMBOLS = ("#", "...", "…")
__slots__ = ()
def __call__(self, document: Document) -> SignalType:
num_words = document.num_raw_words
if num_words == 0:
return [(0, len(document), None)]
# count the number of symbols in the content
num_symbols = float(sum(
document.raw_content.count(x) for x in self.SYMBOLS
))
score = num_symbols / num_words
score = round(score, PRECISION)
return [(0, len(document), score)]
""", block="block", language="python"),
),
Details(
Summary("Implementations from DataTrove"),
D_code("""
if self.max_symbol_word_ratio and text.count("#") / n_words > self.max_symbol_word_ratio:
return False, "gopher_too_many_hashes"
if self.max_symbol_word_ratio and (text.count("...") + text.count("…")) / n_words > self.max_symbol_word_ratio:
return False, "gopher_too_many_ellipsis"
""", block="block", language="python"),
),
Details(
Summary("TxT360 Implementation"),
D_code("""
SYMBOLS = ("#", "...", "…")
...
symbol_pattern = re.compile("|".join(re.escape(symbol) for symbol in SYMBOLS))
...
attrs.symbol_to_word_ratio = sum(1 for word in words if symbol_pattern.search(word)) / word_count
""", block="block", language="python"),
),
H3("Fraction of Alphabetic Words"),
Details(
Summary("Implementations from Dolma"),
D_code("""
attrs.fraction_of_words_with_alpha_character = sum(
1 for word in words if any(c.isalpha() for c in word)
) / max(word_count, 1)
""", block="block", language="python"),
),
Details(
Summary("Implementations from RedPajama-V2"),
D_code("""
class RPS_Doc_Frac_No_Alph_Words(RPSBase): # noqa
ALPH_REGEX = re.compile(r"[a-zA-Z]")
__slots__ = ()
def __call__(self, document: Document) -> SignalType:
num_words = document.num_raw_words
if num_words == 0:
return [(0, len(document), None)]
num_words_with_alpha = float(sum(
int(self.ALPH_REGEX.search(word) is not None)
for word in document.raw_words
))
score = 1.0 - num_words_with_alpha / num_words
score = round(score, PRECISION)
return [(0, len(document), score)]
""", block="block", language="python"),
),
Details(
Summary("Implementations from DataTrove"),
D_code("""
# that 80 % of words in a document contain at least one alphabetic character
if (
self.max_non_alpha_words_ratio
and sum([any((c.isalpha() for c in w)) for w in words]) / n_words < self.max_non_alpha_words_ratio
):
return False, "gopher_below_alpha_threshold"
""", block="block", language="python"),
),
P("""
Both Dolma and DataTrove use `char.isalpha()` to detect whether a word contains alphabetic characters while
RedPajama-V2 employs regular expressions for this purpose. We opt to use regular expressions since `char.isalpha()`
can also match words in other languages as long as they are not punctuations.
"""),
H5("Number of Stop Words"),
P("""
The implementations across existing pipelines are largely identical. We adopt them and apply them to our pipeline.
"""),
D_code("""
STOP_WORDS = ('the', 'be', 'to', 'of', 'and', 'that', 'have', 'with')
...
stop_words_pattern = re.compile("|".join(re.escape(symbol) for symbol in STOP_WORDS))
...
attrs.num_of_stop_words = sum(1 for word in words if stop_words_pattern.search(word))
""", block="block", language="python"),
H3("TxT360 Implementation"),
Details(
Summary("Sample documents that are filtered out by statistics-based heuristics"),
DV(
"data/sample_doc_stat.json",
0,
"Sample documents that are filtered out by statistics-based heuristics",
),
),
H3("3.4 Others"),
P("""
Following C4, we remove any page where the phrase “lorem ipsum” appeared since some pages had placeholder “lorem ipsum”
text.
"""),
Details(
Summary("Sample documents containing 'lorem ipsum'"),
DV("data/lorem_ipsum.json", 0, "Sample documents containing 'lorem ipsum'"),
),
H2("4. Deduplication"),
P("""
After careful filtering, although data quality has improved, a large fraction of the content is repeated across documents. This may be due to the crawler indirectly hitting the same page multiple times, to boilerplate content being repeated (e.g., licences), or even to plagiarism. These duplicates can strongly impact models, favoring memorization instead of generalization.
"""), # Add detailed content and images as needed
P("We perform two-level deduplication: local exact deduplication and global fuzzy deduplication"),
P(B("Local Exact Deduplication")),
P("To reduce the expensive cost of global deduplication, we apply a local exact deduplication before it. Specifically, each dump is split into 70 splits. A bloom filter is applied within each split."),
P(B("Global Fuzzy Deduplication")),
P("NEED TO UPDATE"),
H2("5. PII Removal"),
P("..."), # Add detailed content and images as needed
)