File size: 10,282 Bytes
07d3644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""
Data preparation script for downloading and preparing finetuning data:
- New language data from FineWeb2-HQ (dan_Latn, fas_Arab, swe_Latn)
- English data from FineWeb-Edu (FineWeb2-HQ does not include English)
"""

import argparse
import json
from pathlib import Path

from datasets import load_dataset
from tqdm import tqdm


def download_new_language_data(
    language: str,
    output_dir: Path,
    num_samples: int | None = None,
    full_download: bool = False,
    streaming: bool = True,
):
    """
    Download new language data from FineWeb2-HQ.


    Args:
        language: Language code (e.g. dan_Latn, fas_Arab, swe_Latn).
        output_dir: Directory where the output JSONL file will be written.
        num_samples: Number of samples to collect when full_download is False.
        full_download: If True, download the entire split; num_samples is ignored.
        streaming: Whether to stream the dataset instead of loading it into memory.
    """
    print(f"\n{'=' * 60}")
    print(f"Downloading new language from FineWeb2-HQ: {language}")
    if full_download:
        print("Mode: full download (entire train split)")
    else:
        print(f"Mode: sampled download (target: {num_samples} samples)")
    print(f"{'=' * 60}\n")

    # Load the language-specific subset from FineWeb2-HQ in streaming mode.
    try:
        dataset = load_dataset(
            "HuggingFaceFW/fineweb-2-HQ",
            name=language,
            split="train",
            streaming=streaming,
        )
        print(f"Successfully loaded dataset: {language}")
    except Exception as e:
        print(f"Failed to load dataset: {e}")
        return

    output_dir.mkdir(parents=True, exist_ok=True)
    output_file = output_dir / f"{language}.jsonl"

    # Write samples as JSONL (one JSON object per line).
    progress_total = None if full_download else num_samples
    print("Writing samples to disk...")
    with open(output_file, "w", encoding="utf-8") as f:
        for i, sample in enumerate(tqdm(dataset, total=progress_total)):
            # Stop early when a fixed sample count is requested.
            if not full_download and i >= num_samples:
                break
            json.dump(sample, f, ensure_ascii=False)
            f.write("\n")

    print(f"Data saved to: {output_file}")
    print(f"  File size: {output_file.stat().st_size / 1024 / 1024:.2f} MB\n")


def download_english_data(
    output_dir: Path,
    num_samples: int | None = None,
    full_download: bool = False,
    subset: str = "sample-10BT",
    streaming: bool = True,
):
    """
    Download English data from FineWeb-Edu.

    FineWeb2-HQ does not include English (only non-English multilingual data),
    so English data is sourced from FineWeb-Edu instead.

    Args:
        output_dir: Directory where the output JSONL file will be written.
        num_samples: Number of samples to collect when full_download is False.
        full_download: If True, download the entire split; num_samples is ignored.
        subset: FineWeb-Edu subset (sample-10BT, sample-100BT, sample-350BT, default).
        streaming: Whether to stream the dataset instead of loading it into memory.
    """
    print(f"\n{'=' * 60}")
    print("Downloading English data from FineWeb-Edu")
    print(f"  Subset: {subset}")
    if full_download:
        print("  Mode: full download (entire train split)")
    else:
        print(f"  Mode: sampled download (target: {num_samples} samples)")
    print("  Note: FineWeb2-HQ has no English; using FineWeb-Edu instead")
    print(f"{'=' * 60}\n")

    # Load the requested FineWeb-Edu subset in streaming mode.
    try:
        dataset = load_dataset(
            "HuggingFaceFW/fineweb-edu",
            name=subset,
            split="train",
            streaming=streaming,
        )
        print(f"Successfully loaded FineWeb-Edu subset: {subset}")
    except Exception as e:
        print(f"Failed to load dataset: {e}")
        return

    output_dir.mkdir(parents=True, exist_ok=True)
    output_file = output_dir / "eng_Latn.jsonl"

    # Write samples as JSONL (one JSON object per line).
    progress_total = None if full_download else num_samples
    print("Writing samples to disk...")
    with open(output_file, "w", encoding="utf-8") as f:
        for i, sample in enumerate(tqdm(dataset, total=progress_total)):
            # Stop early when a fixed sample count is requested.
            if not full_download and i >= num_samples:
                break
            json.dump(sample, f, ensure_ascii=False)
            f.write("\n")

    print(f"Data saved to: {output_file}")
    print(f"  File size: {output_file.stat().st_size / 1024 / 1024:.2f} MB\n")


def verify_data_quality(data_file: Path, language: str):
    """
    Run basic quality checks on a downloaded JSONL file.

    Args:
        data_file: Path to the JSONL data file.
        language: Language code used for logging.
    """
    print(f"\nVerifying data quality for {language}...")

    with open(data_file, "r", encoding="utf-8") as f:
        lines = f.readlines()

    total = len(lines)
    text_lengths = []

    # Inspect the first 100 samples to estimate text length statistics.
    for line in lines[:100]:
        sample = json.loads(line)
        if "text" in sample:
            text_lengths.append(len(sample["text"]))

    if text_lengths:
        avg_length = sum(text_lengths) / len(text_lengths)
        min_length = min(text_lengths)
        max_length = max(text_lengths)

        print(f"  Total samples: {total}")
        print(f"  Average text length: {avg_length:.0f} characters")
        print(f"  Shortest text: {min_length} characters")
        print(f"  Longest text: {max_length} characters")

        # Flag potentially low-quality samples based on length heuristics.
        if min_length < 100:
            print("  Warning: some texts are very short (< 100 characters)")
        if avg_length < 500:
            print("  Warning: average text length is short (< 500 characters)")
        else:
            print("  Data quality looks good")


def main():
    parser = argparse.ArgumentParser(
        description="Prepare finetuning data for Marco-MoE"
    )
    parser.add_argument(
        "--languages",
        nargs="+",
        default=["dan_Latn", "fas_Arab", "swe_Latn"],
        help="New language codes to download from FineWeb2-HQ "
        "(default: dan_Latn fas_Arab swe_Latn)",
    )
    parser.add_argument(
        "--include-english",
        action="store_true",
        help="Also download English data from FineWeb-Edu",
    )
    parser.add_argument(
        "--full-download",
        action="store_true",
        help="Download the entire train split for each language. "
        "When set, --num-samples and --english-samples are ignored.",
    )
    parser.add_argument(
        "--num-samples",
        type=int,
        default=50000,
        help="Number of samples per new language when --full-download is not set "
        "(default: 50000)",
    )
    parser.add_argument(
        "--english-samples",
        type=int,
        default=150000,
        help="Number of English samples when --full-download is not set "
        "(default: 150000)",
    )
    parser.add_argument(
        "--english-subset",
        type=str,
        default="sample-10BT",
        choices=["sample-10BT", "sample-100BT", "sample-350BT", "default"],
        help="FineWeb-Edu subset for English data (default: sample-10BT)",
    )
    parser.add_argument(
        "--output-dir",
        type=str,
        default="../outputs/prepared_data",
        help="Output directory for JSONL files (default: ../outputs/prepared_data)",
    )
    parser.add_argument(
        "--verify",
        action="store_true",
        help="Run basic quality checks after each download",
    )

    args = parser.parse_args()
    output_dir = Path(args.output_dir)

    # Print run configuration before starting downloads.
    print("\n" + "=" * 60)
    print("Marco-MoE Finetuning Data Preparation")
    print("=" * 60)
    print("\nConfiguration:")
    print(f"  New languages (FineWeb2-HQ): {', '.join(args.languages)}")
    if args.full_download:
        print("  Download mode: full (entire train split per language)")
    else:
        print("  Download mode: sampled")
        print(f"  Samples per new language: {args.num_samples}")
    print(f"  Include English: {args.include_english}")
    if args.include_english:
        print(f"  English source: FineWeb-Edu ({args.english_subset})")
        if not args.full_download:
            print(f"  English samples: {args.english_samples}")
    print(f"  Output directory: {output_dir}")
    print()

    # Download new language data from FineWeb2-HQ.
    for lang in args.languages:
        download_new_language_data(
            language=lang,
            output_dir=output_dir,
            num_samples=args.num_samples,
            full_download=args.full_download,
            streaming=True,
        )

        if args.verify:
            verify_data_quality(output_dir / f"{lang}.jsonl", lang)

    # Download English data from FineWeb-Edu (optional).
    if args.include_english:
        download_english_data(
            output_dir=output_dir,
            num_samples=args.english_samples,
            full_download=args.full_download,
            subset=args.english_subset,
            streaming=True,
        )

        if args.verify:
            verify_data_quality(
                output_dir / "eng_Latn.jsonl", "eng_Latn (FineWeb-Edu)"
            )

    # Print a summary of all generated files.
    print("\n" + "=" * 60)
    print("Data preparation complete!")
    print("=" * 60)
    print(f"\nData location: {output_dir.absolute()}")
    print("\nGenerated files:")
    for file in sorted(output_dir.glob("*.jsonl")):
        size_mb = file.stat().st_size / 1024 / 1024
        print(f"  - {file.name}: {size_mb:.2f} MB")

    print("\nNext steps:")
    print("  1. Verify data quality: python data/prepare_data.py --verify")
    print("  2. Start finetuning:")
    print("     - Marco-Mini: bash scripts/quickstart_finetune.sh marco-mini")
    print("     - Marco-Nano: bash scripts/quickstart_finetune.sh marco-nano")


if __name__ == "__main__":
    main()