fh-new-vm1 / web.py
victormiller's picture
Update web.py
8813482 verified
raw
history blame
28.3 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
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,
)
def web_data():
return Div(
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;
""",
),
Div(
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;",
),
H3("1. Document Preparation"),
H4("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.
"""),
DV2("data/sample_wet.json", "data/sample_warc.json", 3),
H4("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.
"""),
DV(
"data/sample_non_en.json",
3,
"Sample documents that are classified as non-English",
),
DV(
"data/sample_en_low.json",
3,
"Sample documents that are classified as English but with score less than 0.65",
),
H4("1.3 URL Filtering"),
P("""
Following RefinedWeb [3], we use a manually inspected URL blocklist to filter fraudulent and/or adult websites.
We also exclude our high-quality curated data from it to avoid duplication.
"""),
H5("1.3.1 URL Blocklist"),
P("""
Following RefinedWeb [3], we applied manual inspection on 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. 24 URL domains were detected with more than 4k matches, which are shown below.
"""),
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.
"""),
DVS(urls_false_positives, "6 url domains that are removed from the blocklist"),
DV(
"data/bad_url_doc.jsonl",
3,
"Sample documents whose urls are blocked by the refined url blocklist",
),
H5("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.
"""),
DVS(
non_web_urls,
"curated url domains that are excluded from our dataset",
),
DV(
"data/sample_url_exclusion.json",
0,
"Sample documents whose urls are in our curated url domain list",
),
H3("2. Line-Level Removal"),
P("""
Before computing the quality signals that can be used for filtering low-quality documents, we perform the line-level
removal to remove low-quality lines so that the final quality signals align with our final kept texts.
"""),
H4("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 using a better text extraction tool “trafilatura”. For instance, in the 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.
"""),
DV(
"data/sample_terminal_punc.json",
0,
"Sample documents with lines that are removed by the rule of terminal punctuation",
),
H4('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”. 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”.
"""),
DV(
"data/sample_java.jsonl",
0,
"Sample documents that are removed by original C4 javascript rule but are kept after our refinement",
),
H4("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:
- The line is only composed of uppercase characters,
- The line is only composed of numerical characters,
- The line matches the pattern “r'^\\d+\\s+likes$'”,
- The line contains only one word.
"""),
DV(
"data/sample_refinedweb_line.json",
0,
"Sample documents with lines that are removed by the RefinedWeb rules",
),
H4("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.
"""),
DVS(
json.load(open("data/toxic_lines.json")),
"Sample documents with toxic lines",
),
H3("3. Document-Level Filtering"),
P("""
In this section, we introduce all the quality signals that we have used to filter out low-quality documents.
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 of these 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], selecting the most suitable method based on manual inspections.
"""),
H4("3.1 Repetition-based Heuristics"),
P("""
Due to crawling errors or low-quality sources, many documents contain repeated sequences. In line with previous
work ([2], [3], [6]), we choose to remove any document with excessive line, paragraph, or n-gram repetitions.
"""),
H5("3.1.1 Fraction of (Characters in) Repeated Lines"),
P("""
Following Gopher [2], we remove documents containing many 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.
"""),
H6("Implementations from Dolma"),
P("..."), # Add specific implementation details if available
H6("Implementations from DataTrove"),
P("..."), # Add specific implementation details if available
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:
"""),
H5("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.
"""),
H5("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.
"""),
H5("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.
"""),
H5("Our Implementation"),
DV(
"data/repeat_line_frac.jsonl",
0,
"Sample documents filtered by excessive line repetitions / characters in repeated lines",
),
H5("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.
"""),
H6("Implementations from Dolma"),
P("..."), # Add specific implementation details if available
H6("Implementations from RedPajama-V2"),
P("..."), # Add specific implementation details if available
H6("Implementations from DataTrove"),
P("..."), # Add specific implementation details if available
P("""
There are almost no contradictions between above 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.
"""),
H5("Our Implementations"),
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)",
),
H5("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.
"""),
H6("Implementations from Dolma"),
P("..."), # Add specific implementation details if available
H6("Implementations from RedPajama-V2"),
P("..."), # Add specific implementation details if available
H6("Implementations from DataTrove"),
P("..."), # Add specific implementation details if available
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. 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. 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.
We decided to use the RedPajama V2 implementation but skip the 1st occurrence of the duplicate n-gram.
"""),
H5("Our Implementations"),
H5("An Example to Show the Difference Between Above Implementations"),
P("..."), # Add specific examples if available
H5(
"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)",
),
H4("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.
"""),
DV(
"data/line_info.json",
0,
"Sample documents that are filtered out by line-wise heuristics",
),
H4("3.3 Statistics-based Heuristics"),
P("""
We summarize other statistics-based rules originating from Gopher [2] in this section, which include:
- Word count in the document,
- Mean word length,
- Number of sentences,
- Symbol-to-word ratio,
- Fraction of alphabetic words,
- Number of stop words.
Specifically, we remove any document which meets any of the following criteria:
- Contains fewer than 50 words or more than 100,000 words
- Has a mean word length outside the range of 3 to 10 characters
- Contains fewer than 3 sentences
- Has a symbol-to-word ratio greater than 0.1
- Contains less than 80% alphabetic words
- Contains fewer than two of the following stop words: "the," "be," "to," "of," "and," "that," "have," "with"
"""),
H5("Word Count"),
P("""
Implementations from Dolma
Implementations from RedPajama-V2
Implementations from DataTrove
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.
"""),
H5("Mean Word Length"),
P("""
There is minimal variation among existing pipeline implementations. We simply compute the mean word length as follows:
"""),
Div(
Code("""
words = text.split()
word_count = len(words)
character_count = sum(len(word) for word in words)
mean_word_length = character_count / word_count
"""),
cls="code-block",
),
P("""
It's worth noting that Dolma used the median word length instead of the mean in their codes.
"""),
Div(
Code("""
from statistics import median
median_word_length = median(len(word) for word in words)
"""),
cls="code-block",
),
H5("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.
"""),
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.
"""),
H5("Symbol to Word Ratio"),
P("""
Implementations from Dolma
Implementations from RedPajama-V2
Implementations from DataTrove
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.
"""),
H5("Fraction of Alphabetic Words"),
P("""
Implementations from Dolma
Implementations from RedPajama-V2
Implementations from DataTrove
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.
"""),
Img(
src="path/to/sample_alphabetic_words.png",
alt="Sample documents filtered by fraction of alphabetic words",
),
H5("Number of Stop Words"),
P("""
The implementations across existing pipelines are largely identical. We adopt them and apply them to our pipeline.
"""),
Img(
src="path/to/sample_stop_words.png",
alt="Sample documents filtered by number of stop words",
),
H5("Our Implementations"),
DV(
"data/sample_doc_stat.json",
0,
"Sample documents that are filtered out by statistics-based heuristics",
),
H4("3.4 Others"),
P("""
Following C4, we remove any page where the phrase “lorem ipsum” appeared since some pages had placeholder “lorem ipsum”
text.
"""),
DV("data/lorem_ipsum.json", 0, "Sample documents containing 'lorem ipsum"),
H3("4. Deduplication"),
P("..."), # Add detailed content and images as needed
H3("5. PII Removal"),
P("..."), # Add detailed content and images as needed
H2("Reference"),
Ul(
Li(
P(
"The {P}ile: An 800{GB} dataset of diverse text for language modeling Gao, Leo and Biderman, Stella and Black, Sid and Golding, Laurence and Hoppe, Travis and Foster, Charles and Phang, Jason and He, Horace and Thite, Anish and Nabeshima, Noa and others. 2020."
)
),
Li(
P("""Scaling Language Models: Methods, Analysis & Insights from Training Gopher [link]
Jack W. Rae and Sebastian Borgeaud and Trevor Cai and Katie Millican and Jordan Hoffmann and H. Francis
Song and John Aslanides and Sarah Henderson and Roman Ring and Susannah Young and Eliza Rutherford and Tom
Hennigan and Jacob Menick and Niklas Muennighoff and Aakanksha Naik and Crystal Nam and Matthew E. Peters
and Abhilasha Ravichander and Kyle Richardson and Zejiang Shen and Emma Strubell and Nishant Subramani
and Oyvind Tafjord and Pete Walsh and Luke Zettlemoyer and Noah A. Smith and Hannaneh Hajishirzi and Iz Beltagy
and Dirk Groeneveld and Jesse Dodge and Kyle Lo. 2021.""")
),
Li(
P("""The RefinedWeb Dataset for Falcon LLM: Outperforming Curated Corpora with Web Data, and Web Data Only
Guilherme Penedo and Quentin Malartic and Daniel Hesslow and Ruxandra Cojocaru and Alessandro Cappelli and
Hamza Alobeidli and Baptiste Pannier and Ebtesam Almazrouei and Julien Launay. 2023.""")
),
Li(
P("""🍷 FineWeb: decanting the web for the finest text data at scale [link]
Guilherme Penedo, Hynek Kydlíček, Loubna Ben Allal, Anton Lozhkov, Colin Raffel, Leandro Werra and Thomas Wolf. 2024.""")
),
Li(
P("""Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and
Wei Li and Peter J. Liu. 2023.""")
),
Li(
P("""Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research
Luca Soldaini and Rodney Kinney and Akshita Bhagia and Dustin Schwenk and David Atkinson and Russell Authur and
Ben Bogin and Khyathi Chandu and Jennifer Dumas and Yanai Elazar and Valentin Hofmann and Ananya Harsh Jha and
Sachin Kumar and Li Lucy and Xinxi Lyu and Nathan Lambert and Ian Magnusson and Jacob Morrison and Niklas Muennighoff and
Aakanksha Naik and Crystal Nam and Matthew E. Peters and Abhilasha Ravichander and Kyle Richardson and Zejiang Shen
and Emma Strubell and Nishant Subramani and Oyvind Tafjord and Pete Walsh and Luke Zettlemoyer and Noah A. Smith and
Hannaneh Hajishirzi and Iz Beltagy and Dirk Groeneveld and Jesse Dodge and Kyle Lo. 2024.""")
),
Li(
P("""RedPajama-Data-v2: an Open Dataset with 30 Trillion Tokens for Training Large Language Models [link]
Together Computer. 2023.""")
),
),
)