cmeister commited on
Commit
08cbff1
·
verified ·
1 Parent(s): b44cef2

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. LICENSE +202 -0
  2. NOTICE +48 -0
  3. README.md +95 -0
  4. corpora_manifest.json +0 -0
  5. lm_training_mixture/lm_dataset_sampler.py +1093 -0
  6. lm_training_mixture/metadata.json +281 -0
  7. lm_training_mixture/shard_00001.parquet +3 -0
  8. lm_training_mixture/shard_00004.parquet +3 -0
  9. lm_training_mixture/shard_00009.parquet +3 -0
  10. lm_training_mixture/shard_00010.parquet +3 -0
  11. lm_training_mixture/shard_00012.parquet +3 -0
  12. lm_training_mixture/shard_00017.parquet +3 -0
  13. lm_training_mixture/shard_00021.parquet +3 -0
  14. lm_training_mixture/shard_00025.parquet +3 -0
  15. lm_training_mixture/shard_00026.parquet +3 -0
  16. lm_training_mixture/shard_00030.parquet +3 -0
  17. lm_training_mixture/shard_00035.parquet +3 -0
  18. lm_training_mixture/shard_00038.parquet +3 -0
  19. lm_training_mixture/shard_00040.parquet +3 -0
  20. lm_training_mixture/shard_00044.parquet +3 -0
  21. lm_training_mixture/shard_00047.parquet +3 -0
  22. lm_training_mixture/shard_00048.parquet +3 -0
  23. lm_training_mixture/shard_00049.parquet +3 -0
  24. lm_training_mixture/shard_00051.parquet +3 -0
  25. lm_training_mixture/shard_00056.parquet +3 -0
  26. lm_training_mixture/shard_00067.parquet +3 -0
  27. lm_training_mixture/shard_00070.parquet +3 -0
  28. lm_training_mixture/shard_00073.parquet +3 -0
  29. lm_training_mixture/shard_00074.parquet +3 -0
  30. lm_training_mixture/shard_00079.parquet +3 -0
  31. lm_training_mixture/shard_00081.parquet +3 -0
  32. lm_training_mixture/shard_00084.parquet +3 -0
  33. lm_training_mixture/shard_00091.parquet +3 -0
  34. lm_training_mixture/shard_00096.parquet +3 -0
  35. tokenizer_training_pool/fineweb2/mic_Latn.parquet +3 -0
  36. tokenizer_training_pool/sampling_stats.json +0 -0
  37. tokenizer_training_pool/starcoder/assembly.parquet +3 -0
  38. tokenizer_training_pool/starcoder/c-sharp.parquet +3 -0
  39. tokenizer_training_pool/starcoder/c.parquet +3 -0
  40. tokenizer_training_pool/starcoder/dart.parquet +3 -0
  41. tokenizer_training_pool/starcoder/haskell.parquet +3 -0
  42. tokenizer_training_pool/starcoder/java.parquet +3 -0
  43. tokenizer_training_pool/starcoder/lua.parquet +3 -0
  44. tokenizer_training_pool/starcoder/mathematica.parquet +3 -0
  45. tokenizer_training_pool/starcoder/protocol-buffer.parquet +3 -0
  46. tokenizer_training_pool/starcoder/python.parquet +3 -0
  47. tokenizer_training_pool/starcoder/scala.parquet +3 -0
  48. tokenizer_training_pool/starcoder/stan.parquet +3 -0
  49. tokenizer_training_pool/starcoder/tcl.parquet +3 -0
  50. tokenizer_training_pool/tokenizer_dataset_sampler.py +591 -0
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tokenizer-lm
2
+ Copyright 2026 Clara Meister
3
+
4
+ This product includes software developed as part of the tokenizer-lm study,
5
+ licensed under the Apache License, Version 2.0. See LICENSE.
6
+
7
+ --------------------------------------------------------------------------------
8
+ Third-party components
9
+ --------------------------------------------------------------------------------
10
+
11
+ nanochat
12
+ https://github.com/karpathy/nanochat
13
+ MIT License, Copyright (c) 2025 Andrej Karpathy
14
+
15
+ The model architecture, optimizer and dataloader come from nanochat. This project
16
+ uses a patched copy (https://github.com/cimeister/nanochat, branch
17
+ tokenizer-lm-patches) that adds a configurable value-embedding dimension, a
18
+ configurable logit soft cap, and a configurable learning-rate width exponent for
19
+ muP. The released model class scripts/hf_release/nanochat_model.py reimplements that
20
+ architecture for the HuggingFace transformers interface. The full MIT license text
21
+ is at nanochat/LICENSE.
22
+
23
+ --------------------------------------------------------------------------------
24
+ Training data
25
+ --------------------------------------------------------------------------------
26
+
27
+ The released model weights were trained on a mixture of:
28
+
29
+ FineWeb-Edu HuggingFaceFW/fineweb-edu ODC-By
30
+ FineWeb-2 (filtered) HuggingFaceFW/fineweb-2 ODC-By
31
+ FineMath 4plus HuggingFaceTB/finemath ODC-By
32
+ StarCoderData bigcode/starcoderdata listed as "other"
33
+
34
+ Licenses as stated on each dataset's Hugging Face card, read 2026-08-17. The
35
+ multilingual and code portions were used through quality-filtered derivatives
36
+ prepared inside the Swiss AI initiative; see EXPERIMENTAL_SETUP.md for the exact
37
+ paths and filters.
38
+
39
+ --------------------------------------------------------------------------------
40
+ Tokenizers not redistributed
41
+ --------------------------------------------------------------------------------
42
+
43
+ Two off-the-shelf tokenizers were used as reference points and are cited rather than
44
+ redistributed: the Apertus tokenizer (swiss-ai/Apertus-70B-2509, the same artifact as
45
+ Mistral-Nemo's tokenizer) and the Llama-3 tokenizer (recorded at training time as
46
+ NousResearch/Meta-Llama-3-8B). In the names of the tokenizers this project trained,
47
+ "gpt4o", "claude" and "gpt2" refer to a borrowed pretokenization regular expression,
48
+ not to those vendors' tokenizers.
README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: odc-by
3
+ language:
4
+ - multilingual
5
+ task_categories:
6
+ - text-generation
7
+ tags:
8
+ - tokenizer
9
+ - pretraining-corpus
10
+ ---
11
+
12
+ # tokenizer-lm training corpora
13
+
14
+ The two corpora behind [`cmeister/tokenizer-lm-ablations`](https://huggingface.co/cmeister/tokenizer-lm-ablations): the
15
+ mixture every released language model trained on, and the pool the tokenizers were trained
16
+ from. Both are samples of public corpora, released so the models' results can be
17
+ reproduced rather than taken on faith.
18
+
19
+ Staged 2026-10-19.
20
+
21
+ ## `lm_training_mixture/`
22
+
23
+ 100 parquet shards, **5,000,000 documents**, 24.97 GB
24
+ of text, 13.71 GB on disk. Sampled with seed 42;
25
+ `metadata.json` records every source path, weight, document count and byte count, and
26
+ `lm_dataset_sampler.py` is the script that produced it.
27
+
28
+ Composition by sampling weight: FineWeb-Edu 36.8%, FineWeb-2 31.6% across
29
+ 30 languages, FineMath 15.8%, StarCoder python and javascript 15.8%.
30
+
31
+ ### Read this before using it
32
+
33
+ **The shards have one column, `text`.** No document id, no URL, no source dataset, no
34
+ repository name. Every provenance field was dropped when the mixture was sampled, and the
35
+ sampling was not recorded per document.
36
+
37
+ The practical consequences are worth stating rather than leaving to be discovered:
38
+
39
+ - The 15.8% of the mixture that came from StarCoder cannot be identified after the
40
+ fact, so it cannot be separated from the prose, attributed to the repositories it came
41
+ from, or removed on request. If you maintain a repository that was in The Stack and you
42
+ have opted out, we cannot honour that opt-out inside this file, because the information
43
+ needed to act on it no longer exists. We can remove the corpus as a whole; please open a
44
+ discussion on this repository.
45
+ - Per-language analysis of the multilingual portion is not possible from the file alone.
46
+ - Deduplication against another corpus has to be done on text, not on identifiers.
47
+
48
+ The tokenizer pool below does not have this problem, and is the better starting point for
49
+ anything that depends on knowing where a document came from.
50
+
51
+ ## `tokenizer_training_pool/`
52
+
53
+ 1,921 parquet files over 6 sources, 3.21 GB.
54
+ This is the pool the tokenizer-training compositions draw from; a given tokenizer uses a
55
+ weighted subset of it, with the weights recorded in `scripts/train_custom_tokenizers.py` in
56
+ the study's code repository. `sampling_stats.json` records the per-source targets and
57
+ sampling temperatures, and `tokenizer_dataset_sampler.py` is the script that produced it.
58
+
59
+ | Source | Files | GB | Columns |
60
+ |---|---|---|---|
61
+ | `finemath` | 1 | 0.05 | `id`, `metadata`, `text` |
62
+ | `fineweb` | 50 | 1.41 | `id`, `metadata`, `text` |
63
+ | `fineweb2` | 1,781 | 1.36 | `id`, `metadata`, `text` |
64
+ | `infimath` | 1 | 0.05 | `id`, `metadata`, `text` |
65
+ | `megamath` | 1 | 0.11 | `id`, `metadata`, `text` |
66
+ | `starcoder` | 87 | 0.22 | `clarity`, `content`, `difficulty`, `educational`, `id`, `max_stars_count`, `max_stars_repo_name`, `max_stars_repo_path`, `output`, `practice`, `quality`, `quantile` |
67
+
68
+ Provenance is intact here. StarCoder rows carry `max_stars_repo_name` and
69
+ `max_stars_repo_path`, so code can be attributed to its repository and removed on request.
70
+ Web and math rows carry an `id` and a `metadata` struct holding the Common Crawl path and
71
+ the source domain.
72
+
73
+ ## Where this came from, and what that means for licensing
74
+
75
+ The underlying public datasets are
76
+ [FineWeb-Edu](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) (ODC-By),
77
+ [FineWeb-2](https://huggingface.co/datasets/HuggingFaceFW/fineweb-2) (ODC-By),
78
+ [FineMath](https://huggingface.co/datasets/HuggingFaceTB/finemath) (ODC-By) and
79
+ [StarCoderData](https://huggingface.co/datasets/bigcode/starcoderdata), whose card lists
80
+ its license as "other" and which carries The Stack's opt-out undertaking. Licenses as
81
+ stated on each dataset's card, read 2026-08-17.
82
+
83
+ What is published here is not sampled from those public versions directly. It was sampled
84
+ from quality-filtered derivatives prepared inside the Swiss AI initiative, so this release
85
+ also redistributes that filtering work. Attribution for the filtering belongs to that
86
+ project.
87
+
88
+ If you are an author or maintainer with a removal request, open a discussion here. For the
89
+ tokenizer pool we can act on it precisely; for the language-model mixture, see the
90
+ limitation stated above.
91
+
92
+ ## Citation
93
+
94
+ See the model repository [`cmeister/tokenizer-lm-ablations`](https://huggingface.co/cmeister/tokenizer-lm-ablations) for the
95
+ study these corpora belong to.
corpora_manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
lm_training_mixture/lm_dataset_sampler.py ADDED
@@ -0,0 +1,1093 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ corpus_sampler.py
4
+
5
+ Takes an existing corpus directory containing parquet files and creates a
6
+ sampled version of it. Two modes are supported:
7
+
8
+ MULTILINGUAL mode (default)
9
+ input_dir/
10
+ <lang_code>/
11
+ *.parquet
12
+ <lang_code>/
13
+ ...
14
+ output_dir/
15
+ <lang_code>/
16
+ data.parquet
17
+ ...
18
+
19
+ Language proportions are computed from **UTF-8 text byte sizes** (measured
20
+ from the text column) using a temperature formula:
21
+ scaled_size = size ^ (1 / temperature)
22
+ T=1.0 → strictly proportional to input sizes
23
+ T>1.0 → upsamples smaller languages (flattens the distribution)
24
+ A 50% cap is applied per language after temperature scaling.
25
+ A minimum row floor per language is enforced.
26
+
27
+ Because reading the full text column of a multi-TB corpus would be
28
+ prohibitively slow, text byte sizes are *estimated* by sampling a
29
+ configurable number of rows per language (--text_sample_rows, default 2000)
30
+ and extrapolating.
31
+
32
+ MONOLINGUAL mode (--monolingual)
33
+ input_dir/
34
+ *.parquet
35
+ ...
36
+ output_dir/
37
+ data.parquet
38
+
39
+ All parquet files in input_dir are treated as a single pool.
40
+ The target row count is derived directly from --total_size_gb.
41
+ Temperature and the per-language cap are not applicable.
42
+ --min_rows_floor still acts as a lower bound.
43
+
44
+ In both modes the total target is specified in GB of **raw text bytes**
45
+ (uncompressed UTF-8), not on-disk parquet bytes.
46
+ """
47
+
48
+ import os
49
+ import json
50
+ import math
51
+ import random
52
+ import logging
53
+ import argparse
54
+ from pathlib import Path
55
+ from typing import Dict, List, Optional, Tuple
56
+
57
+ import pandas as pd
58
+ import pyarrow as pa
59
+ import pyarrow.compute as pc
60
+ import pyarrow.parquet as pq
61
+ from tqdm import tqdm
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Logging
65
+ # ---------------------------------------------------------------------------
66
+
67
+ logging.basicConfig(
68
+ level=logging.INFO,
69
+ format="%(asctime)s - %(levelname)s - %(message)s",
70
+ )
71
+ log = logging.getLogger(__name__)
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Defaults
75
+ # ---------------------------------------------------------------------------
76
+
77
+ DEFAULT_TEMP = 5.0 # same default as XLM_R_TEMP in corpus_downloader.py
78
+ DEFAULT_CAP = 0.5 # 50 % cap per language
79
+ DEFAULT_MIN_ROWS = 1000 # minimum row floor per language
80
+ DEFAULT_SEED = 42
81
+ DEFAULT_TEXT_COLUMN = "text"
82
+ DEFAULT_TEXT_SAMPLE_ROWS = 2000
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # Proportion helpers (mirror of _calculate_proportions in corpus_downloader.py)
86
+ # ---------------------------------------------------------------------------
87
+
88
+ def _calculate_proportions(
89
+ original_sizes: Dict[str, float],
90
+ temperature: float,
91
+ cap: float = DEFAULT_CAP,
92
+ ) -> Dict[str, float]:
93
+ """
94
+ Compute per-language sampling proportions with temperature scaling and
95
+ a per-language cap.
96
+
97
+ Formula (same as corpus_downloader.py):
98
+ powered_size[lg] = size[lg] ^ (1 / temperature)
99
+ proportion[lg] = powered_size[lg] / sum(powered_sizes)
100
+
101
+ After computing raw proportions any language exceeding `cap` is clamped;
102
+ the remaining budget is re-distributed among uncapped languages and the
103
+ result is re-normalised to 1.
104
+ """
105
+ if not original_sizes:
106
+ return {}
107
+
108
+ # --- 1. Temperature scaling ---
109
+ if temperature == 1.0:
110
+ powered = dict(original_sizes)
111
+ else:
112
+ log.info(f"Applying temperature {temperature} to size-based proportions.")
113
+ powered = {lg: size ** (1.0 / temperature) for lg, size in original_sizes.items()}
114
+
115
+ total_powered = sum(powered.values())
116
+ if total_powered == 0:
117
+ return {}
118
+
119
+ proportions: Dict[str, float] = {
120
+ lg: p / total_powered for lg, p in powered.items()
121
+ }
122
+
123
+ # --- 2. Cap ---
124
+ capping_needed = any(p > cap for p in proportions.values())
125
+ if capping_needed:
126
+ for lg, prop in proportions.items():
127
+ if prop > cap:
128
+ log.warning(
129
+ f"[{lg}] proportion {prop*100:.1f}% exceeds cap. "
130
+ f"Capping at {cap*100:.0f}%."
131
+ )
132
+ proportions[lg] = cap
133
+
134
+ capped_total = sum(p for p in proportions.values() if p == cap)
135
+ remaining = 1.0 - capped_total
136
+ uncapped_powered_total = sum(
137
+ powered[lg] for lg, p in proportions.items() if p < cap
138
+ )
139
+ if uncapped_powered_total > 0:
140
+ for lg in proportions:
141
+ if proportions[lg] < cap:
142
+ proportions[lg] = (powered[lg] / uncapped_powered_total) * remaining
143
+ elif remaining > 0:
144
+ log.warning("All languages are at the cap. Distribution may not sum to 1.")
145
+
146
+ # --- 3. Re-normalise ---
147
+ total = sum(proportions.values())
148
+ if not math.isclose(total, 1.0, rel_tol=1e-5):
149
+ log.info(f"Proportions sum to {total:.6f}; re-normalising.")
150
+ proportions = {lg: p / total for lg, p in proportions.items()}
151
+
152
+ return proportions
153
+
154
+
155
+ # ---------------------------------------------------------------------------
156
+ # Filesystem helpers
157
+ # ---------------------------------------------------------------------------
158
+
159
+ def discover_languages(input_dir: Path, lang_subdir: str = "") -> Dict[str, List[Path]]:
160
+ """
161
+ Walk input_dir and return a mapping of language_code → list of parquet files.
162
+ Only immediate subdirectories that contain at least one .parquet file are
163
+ included.
164
+
165
+ If lang_subdir is set, parquet files are looked for inside
166
+ input_dir/<lang_code>/<lang_subdir>/ rather than directly inside
167
+ input_dir/<lang_code>/.
168
+ """
169
+ langs: Dict[str, List[Path]] = {}
170
+ for subdir in sorted(input_dir.iterdir()):
171
+ if not subdir.is_dir():
172
+ continue
173
+ search_dir = subdir / lang_subdir if lang_subdir else subdir
174
+ if not search_dir.is_dir():
175
+ log.debug(f"Skipping '{subdir.name}': subdirectory '{lang_subdir}' not found.")
176
+ continue
177
+ parquets = validate_parquet_files(sorted(search_dir.glob("*.parquet")))
178
+ if parquets:
179
+ langs[subdir.name] = parquets
180
+ else:
181
+ log.debug(f"Skipping '{subdir.name}': no valid parquet files found in '{search_dir}'.")
182
+ return langs
183
+
184
+
185
+ def discover_monolingual(input_dir: Path) -> List[Path]:
186
+ """
187
+ Return all .parquet files directly inside input_dir (non-recursive).
188
+ Raises ValueError if none are found.
189
+ """
190
+ parquets = validate_parquet_files(sorted(input_dir.glob("*.parquet")))
191
+ if not parquets:
192
+ raise ValueError(f"No valid .parquet files found directly in '{input_dir}'.")
193
+ return parquets
194
+
195
+
196
+ def validate_parquet_files(files: List[Path]) -> List[Path]:
197
+ """
198
+ Return only the files that can be opened as valid parquet files.
199
+ Corrupt or invalid files are logged as warnings and excluded.
200
+ """
201
+ valid = []
202
+ for f in files:
203
+ try:
204
+ pq.ParquetFile(f)
205
+ valid.append(f)
206
+ except Exception as e:
207
+ log.warning(f"Skipping corrupt/invalid parquet file '{f}': {e}")
208
+ return valid
209
+
210
+
211
+ def total_parquet_bytes(files: List[Path]) -> int:
212
+ """Return the sum of on-disk sizes (bytes) for a list of parquet files."""
213
+ return sum(f.stat().st_size for f in files)
214
+
215
+
216
+ def count_rows(files: List[Path]) -> int:
217
+ """Count total rows across a list of parquet files without loading data."""
218
+ total = 0
219
+ for f in files:
220
+ pf = pq.ParquetFile(f)
221
+ total += pf.metadata.num_rows
222
+ return total
223
+
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # Text byte measurement
227
+ # ---------------------------------------------------------------------------
228
+
229
+ def _measure_text_bytes_in_table(table: pa.Table, text_column: str) -> int:
230
+ """Sum UTF-8 byte lengths of the text column in an Arrow table."""
231
+ col = table.column(text_column)
232
+ # Cast to binary to get raw UTF-8 byte lengths (not character counts)
233
+ byte_lengths = pc.binary_length(col.cast(pa.large_binary()))
234
+ return pc.sum(byte_lengths, skip_nulls=True).as_py() or 0
235
+
236
+
237
+ def estimate_text_bytes(
238
+ files: List[Path],
239
+ text_column: str,
240
+ sample_rows: int = DEFAULT_TEXT_SAMPLE_ROWS,
241
+ seed: int = DEFAULT_SEED,
242
+ ) -> Tuple[float, float]:
243
+ """
244
+ Estimate total UTF-8 text bytes by sampling rows and extrapolating.
245
+
246
+ Returns (estimated_total_text_bytes, avg_text_bytes_per_row).
247
+ """
248
+ total_rows = count_rows(files)
249
+ if total_rows == 0:
250
+ return 0.0, 0.0
251
+
252
+ rng = random.Random(seed)
253
+ sampled_count = 0
254
+ sampled_text_bytes = 0
255
+
256
+ # Distribute sample budget across files proportionally
257
+ file_row_counts = []
258
+ for f in files:
259
+ pf = pq.ParquetFile(f)
260
+ file_row_counts.append((f, pf.metadata.num_rows))
261
+
262
+ remaining = min(sample_rows, total_rows)
263
+
264
+ for f, frows in file_row_counts:
265
+ if remaining <= 0:
266
+ break
267
+ # Proportional allocation of sample budget to this file
268
+ file_budget = max(1, int(remaining * frows / max(total_rows - sampled_count, 1)))
269
+ file_budget = min(file_budget, frows, remaining)
270
+
271
+ table = pq.read_table(f, columns=[text_column])
272
+ # Cast to large_string to avoid offset overflow on take/concat
273
+ col = table.column(text_column)
274
+ if pa.types.is_string(col.type):
275
+ table = table.set_column(
276
+ table.schema.get_field_index(text_column),
277
+ text_column,
278
+ col.cast(pa.large_string()),
279
+ )
280
+ if len(table) > file_budget:
281
+ indices = sorted(rng.sample(range(len(table)), file_budget))
282
+ table = table.take(indices)
283
+
284
+ sampled_text_bytes += _measure_text_bytes_in_table(table, text_column)
285
+ sampled_count += len(table)
286
+ remaining -= len(table)
287
+
288
+ if sampled_count == 0:
289
+ return 0.0, 0.0
290
+
291
+ avg_text_bytes_per_row = sampled_text_bytes / sampled_count
292
+ estimated_total = avg_text_bytes_per_row * total_rows
293
+ return estimated_total, avg_text_bytes_per_row
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # Schema helpers
298
+ # ---------------------------------------------------------------------------
299
+
300
+ def _promote_type(types: List[pa.DataType]) -> pa.DataType:
301
+ """
302
+ Given a list of Arrow types for the same column across files, return
303
+ the promoted (widest) type that can losslessly represent all of them.
304
+
305
+ Falls back to the first type if promotion is not needed or not possible.
306
+ """
307
+ if not types:
308
+ raise ValueError("Empty type list")
309
+
310
+ unique = list({str(t): t for t in types}.values())
311
+ if len(unique) == 1:
312
+ return unique[0]
313
+
314
+ # Let PyArrow try automatic unification via a dummy schema merge
315
+ try:
316
+ dummy_schemas = [pa.schema([pa.field("_", t)]) for t in unique]
317
+ unified = pa.unify_schemas(dummy_schemas, promote_options="permissive")
318
+ return unified.field("_").type
319
+ except pa.ArrowInvalid:
320
+ log.warning(
321
+ f"Could not auto-promote types {[str(t) for t in unique]}; "
322
+ f"using first encountered type: {types[0]}"
323
+ )
324
+ return types[0]
325
+
326
+
327
+ def get_common_schema(files: List[Path]) -> pa.Schema:
328
+ """
329
+ Determine the common schema across all parquet files.
330
+
331
+ - Intersects column names (only columns present in *every* file are kept).
332
+ - For struct columns, intersects subfield names.
333
+ - Promotes types across files (e.g. int32 + int64 → int64) so that every
334
+ file can be safely cast to the resulting schema.
335
+ - Excludes pandas ``__index_level_*`` columns.
336
+ """
337
+ if not files:
338
+ raise ValueError("No files provided")
339
+
340
+ schemas = []
341
+ for f in files:
342
+ pf = pq.ParquetFile(f)
343
+ schemas.append(pf.schema_arrow)
344
+
345
+ # Find common column names, excluding pandas index columns
346
+ common_names = set(schemas[0].names)
347
+ for schema in schemas[1:]:
348
+ common_names &= set(schema.names)
349
+ common_names = {n for n in common_names if not n.startswith("__index_level_")}
350
+
351
+ if not common_names:
352
+ raise ValueError("No common columns found across all files")
353
+
354
+ # Build common schema with type promotion and struct subfield intersection
355
+ common_fields = []
356
+ for name in sorted(common_names):
357
+ # Collect the field from every schema
358
+ fields_across_files = [s.field(name) for s in schemas]
359
+
360
+ if all(pa.types.is_struct(f.type) for f in fields_across_files):
361
+ # --- struct column: intersect subfield names, promote subfield types ---
362
+ subfield_name_sets = []
363
+ for f in fields_across_files:
364
+ subfield_name_sets.append(
365
+ {f.type.field(i).name for i in range(f.type.num_fields)}
366
+ )
367
+ common_subfield_names = subfield_name_sets[0]
368
+ for s in subfield_name_sets[1:]:
369
+ common_subfield_names &= s
370
+
371
+ if not common_subfield_names:
372
+ log.warning(
373
+ f"Struct column '{name}' has no common subfields across files; skipping."
374
+ )
375
+ continue
376
+
377
+ # For each common subfield, promote its type
378
+ promoted_subfields = []
379
+ for sf_name in sorted(common_subfield_names):
380
+ sf_types = []
381
+ for f in fields_across_files:
382
+ for i in range(f.type.num_fields):
383
+ sf = f.type.field(i)
384
+ if sf.name == sf_name:
385
+ sf_types.append(sf.type)
386
+ break
387
+ promoted_subfields.append(pa.field(sf_name, _promote_type(sf_types)))
388
+
389
+ common_fields.append(pa.field(name, pa.struct(promoted_subfields)))
390
+
391
+ elif any(pa.types.is_struct(f.type) for f in fields_across_files):
392
+ # Mixed struct / non-struct across files — skip to be safe
393
+ log.warning(
394
+ f"Column '{name}' is struct in some files but not others; skipping."
395
+ )
396
+ continue
397
+
398
+ else:
399
+ # --- scalar column: promote type ---
400
+ col_types = [f.type for f in fields_across_files]
401
+ common_fields.append(pa.field(name, _promote_type(col_types)))
402
+
403
+ if not common_fields:
404
+ raise ValueError("No common columns survived schema intersection")
405
+
406
+ return pa.schema(common_fields)
407
+
408
+
409
+ def project_to_schema(table: pa.Table, target_schema: pa.Schema) -> pa.Table:
410
+ """
411
+ Project *and cast* a table to the target schema.
412
+
413
+ - Selects only the columns present in ``target_schema``.
414
+ - For struct columns, selects only the subfields present in the target
415
+ struct type and rebuilds the struct.
416
+ - Casts every column to the exact type declared in ``target_schema`` so
417
+ that all output tables are schema-identical and safe to concatenate.
418
+ """
419
+ projected_arrays = []
420
+ projected_fields = []
421
+
422
+ for field in target_schema:
423
+ if field.name not in table.schema.names:
424
+ continue
425
+
426
+ col = table[field.name]
427
+
428
+ # Handle struct fields: select common subfields, then cast
429
+ if pa.types.is_struct(field.type) and pa.types.is_struct(col.type):
430
+ target_subfield_names = [field.type.field(i).name
431
+ for i in range(field.type.num_fields)]
432
+
433
+ subfield_arrays = []
434
+ for subfield_name in target_subfield_names:
435
+ subfield_array = pc.struct_field(col, [subfield_name])
436
+ subfield_arrays.append(subfield_array)
437
+
438
+ col = pc.make_struct(*subfield_arrays, field_names=target_subfield_names)
439
+
440
+ # Cast to the exact target type (handles e.g. int32→int64 promotion)
441
+ if col.type != field.type:
442
+ col = col.cast(field.type)
443
+
444
+ projected_arrays.append(col)
445
+ projected_fields.append(field)
446
+
447
+ return pa.table(projected_arrays, schema=pa.schema(projected_fields))
448
+
449
+
450
+ def cast_to_large_string(schema: pa.Schema) -> pa.Schema:
451
+ """Cast all string columns to large_string to avoid 2GB offset overflow."""
452
+ new_fields = []
453
+ for field in schema:
454
+ if pa.types.is_string(field.type):
455
+ new_fields.append(pa.field(field.name, pa.large_string()))
456
+ elif pa.types.is_struct(field.type):
457
+ # Also handle string fields inside structs
458
+ subfields = []
459
+ for i in range(field.type.num_fields):
460
+ sf = field.type.field(i)
461
+ if pa.types.is_string(sf.type):
462
+ subfields.append(pa.field(sf.name, pa.large_string()))
463
+ else:
464
+ subfields.append(sf)
465
+ new_fields.append(pa.field(field.name, pa.struct(subfields)))
466
+ else:
467
+ new_fields.append(field)
468
+ return pa.schema(new_fields)
469
+
470
+
471
+ # ---------------------------------------------------------------------------
472
+ # Core sampling logic
473
+ # ---------------------------------------------------------------------------
474
+
475
+ def sample_language(
476
+ lang: str,
477
+ parquet_files: List[Path],
478
+ target_rows: int,
479
+ output_path: Path,
480
+ seed: int,
481
+ common_schema: Optional[pa.Schema] = None,
482
+ keep_columns: Optional[List[str]] = None,
483
+ ) -> int:
484
+ """
485
+ Sample `target_rows` rows from the combined pool of `parquet_files` for
486
+ one language and write them to `output_path` as a single parquet file.
487
+
488
+ Returns the actual number of rows written.
489
+ """
490
+ total_rows = count_rows(parquet_files)
491
+ actual_target = min(target_rows, total_rows)
492
+
493
+ if actual_target <= 0:
494
+ log.warning(f"[{lang}] target_rows={target_rows}, total_rows={total_rows}. Nothing to write.")
495
+ return 0
496
+
497
+ # If no common schema provided, compute it from these files
498
+ if common_schema is None:
499
+ common_schema = get_common_schema(parquet_files)
500
+
501
+ # Pre-compute the large_string schema once for reuse
502
+ large_schema = cast_to_large_string(common_schema)
503
+
504
+ # Sampling ratio determines strategy
505
+ sampling_ratio = actual_target / total_rows
506
+
507
+ if sampling_ratio > 0.5:
508
+ # High ratio: load all, then sample
509
+ tables = []
510
+ for f in parquet_files:
511
+ table = pq.read_table(f)
512
+ table = project_to_schema(table, common_schema)
513
+ table = table.cast(large_schema)
514
+ tables.append(table)
515
+
516
+ full_table = pa.concat_tables(tables)
517
+
518
+ rng = random.Random(seed)
519
+ indices = sorted(rng.sample(range(len(full_table)), actual_target))
520
+ table = full_table.take(indices)
521
+ else:
522
+ # Low ratio: per-file sampling
523
+ rng = random.Random(seed)
524
+ collected = []
525
+ remaining = actual_target
526
+
527
+ file_order = list(parquet_files)
528
+ rng.shuffle(file_order)
529
+
530
+ for f in file_order:
531
+ if remaining <= 0:
532
+ break
533
+
534
+ file_rows = pq.ParquetFile(f).metadata.num_rows
535
+ file_target = min(remaining, max(1, int(file_rows * sampling_ratio * 1.2)))
536
+
537
+ if file_target > 0:
538
+ table_chunk = pq.read_table(f)
539
+ table_chunk = project_to_schema(table_chunk, common_schema)
540
+ table_chunk = table_chunk.cast(large_schema)
541
+
542
+ if len(table_chunk) > file_target:
543
+ indices = sorted(rng.sample(range(len(table_chunk)), file_target))
544
+ table_chunk = table_chunk.take(indices)
545
+
546
+ collected.append(table_chunk)
547
+ remaining -= len(table_chunk)
548
+
549
+ if collected:
550
+ table = pa.concat_tables(collected)
551
+ if len(table) > actual_target:
552
+ indices = sorted(rng.sample(range(len(table)), actual_target))
553
+ table = table.take(indices)
554
+ else:
555
+ log.warning(f"[{lang}] No rows collected")
556
+ return 0
557
+
558
+ # Drop columns not in the keep list (if specified)
559
+ if keep_columns is not None:
560
+ keep_set = set(keep_columns)
561
+ drop = [name for name in table.schema.names if name not in keep_set]
562
+ if drop:
563
+ table = table.drop(drop)
564
+
565
+ output_path.parent.mkdir(parents=True, exist_ok=True)
566
+ pq.write_table(table, output_path, compression="snappy")
567
+
568
+ return len(table)
569
+
570
+
571
+ # ---------------------------------------------------------------------------
572
+ # Main sampler class
573
+ # ---------------------------------------------------------------------------
574
+
575
+ class CorpusSampler:
576
+ def __init__(self, args: argparse.Namespace):
577
+ self.args = args
578
+ self.input_dir = Path(args.input_dir)
579
+ self.output_dir = Path(args.output_dir)
580
+ self.total_target_bytes = int(args.total_size_gb * (1024 ** 3))
581
+
582
+ def run(self):
583
+ if self.args.monolingual:
584
+ self._run_monolingual()
585
+ else:
586
+ self._run_multilingual()
587
+
588
+ def _run_monolingual(self):
589
+ # ------------------------------------------------------------------ #
590
+ # 1. Discover parquet files
591
+ # ------------------------------------------------------------------ #
592
+ log.info(f"Monolingual mode. Scanning: {self.input_dir}")
593
+ try:
594
+ parquet_files = discover_monolingual(self.input_dir)
595
+ except ValueError as e:
596
+ log.error(str(e))
597
+ return
598
+
599
+ log.info(f"Found {len(parquet_files)} parquet file(s).")
600
+
601
+ # ------------------------------------------------------------------ #
602
+ # 2. Measure input (text bytes)
603
+ # ------------------------------------------------------------------ #
604
+ log.info("Estimating text byte sizes (sampling rows)…")
605
+ total_text_bytes, text_bpr = estimate_text_bytes(
606
+ parquet_files,
607
+ self.args.text_column,
608
+ sample_rows=self.args.text_sample_rows,
609
+ seed=self.args.seed,
610
+ )
611
+ total_rows = count_rows(parquet_files)
612
+
613
+ log.info(
614
+ f"Input: {total_rows:,} rows, ~{total_text_bytes / 1e9:.3f} GB text "
615
+ f"(~{text_bpr:.0f} text bytes/row)."
616
+ )
617
+
618
+ if self.total_target_bytes >= total_text_bytes:
619
+ log.warning(
620
+ f"Target ({self.args.total_size_gb} GB text) >= estimated input "
621
+ f"({total_text_bytes / 1e9:.3f} GB text). Using all available rows."
622
+ )
623
+
624
+ # ------------------------------------------------------------------ #
625
+ # 3. Compute target row count
626
+ # ------------------------------------------------------------------ #
627
+ estimated_rows = int(self.total_target_bytes / text_bpr) if text_bpr > 0 else total_rows
628
+ floored_rows = max(estimated_rows, self.args.min_rows_floor)
629
+ target_rows = min(floored_rows, total_rows)
630
+
631
+ if floored_rows > estimated_rows:
632
+ log.info(
633
+ f"Proportional allocation ({estimated_rows:,} rows) is below "
634
+ f"floor ({self.args.min_rows_floor:,}). Using floor → {target_rows:,} rows."
635
+ )
636
+ if target_rows < floored_rows:
637
+ log.warning(
638
+ f"Available rows ({total_rows:,}) < requested ({floored_rows:,}). "
639
+ "Using all available rows."
640
+ )
641
+
642
+ log.info(f"Target: {target_rows:,} / {total_rows:,} rows.")
643
+
644
+ # ------------------------------------------------------------------ #
645
+ # 4. Compute common schema across all input files
646
+ # ------------------------------------------------------------------ #
647
+ common_schema = get_common_schema(parquet_files)
648
+ log.info(
649
+ "Common schema across all files:\n"
650
+ + "\n".join(f" {f.name}: {f.type}" for f in common_schema)
651
+ )
652
+
653
+ # ------------------------------------------------------------------ #
654
+ # 5. Sample and write
655
+ # ------------------------------------------------------------------ #
656
+ out_file = self.output_dir / "data.parquet"
657
+
658
+ if out_file.exists():
659
+ log.info(f"Output already exists at {out_file}. Skipping.")
660
+ else:
661
+ written = sample_language(
662
+ lang="monolingual",
663
+ parquet_files=parquet_files,
664
+ target_rows=target_rows,
665
+ output_path=out_file,
666
+ seed=self.args.seed,
667
+ common_schema=common_schema,
668
+ keep_columns=self.args.columns,
669
+ )
670
+ log.info(f"Wrote {written:,} rows → {out_file}")
671
+
672
+ # ------------------------------------------------------------------ #
673
+ # 6. Save manifest
674
+ # ------------------------------------------------------------------ #
675
+ total_parquet = total_parquet_bytes(parquet_files)
676
+ manifest_path = self.output_dir / "sampling_manifest.json"
677
+ with open(manifest_path, "w", encoding="utf-8") as f:
678
+ json.dump(
679
+ {
680
+ "args": vars(self.args),
681
+ "total_input_parquet_gb": total_parquet / 1e9,
682
+ "total_input_text_gb": total_text_bytes / 1e9,
683
+ "target_text_gb": self.args.total_size_gb,
684
+ "rows_available": total_rows,
685
+ "rows_written": target_rows,
686
+ "schema": [
687
+ {"name": f.name, "type": str(f.type)} for f in common_schema
688
+ ],
689
+ "output": str(out_file),
690
+ },
691
+ f,
692
+ indent=2,
693
+ )
694
+ log.info(f"Manifest saved to {manifest_path}")
695
+ log.info("--- Monolingual sampling finished ---")
696
+
697
+ def _run_multilingual(self):
698
+ # ------------------------------------------------------------------ #
699
+ # 1. Discover languages and their parquet files
700
+ # ------------------------------------------------------------------ #
701
+ log.info(f"Multilingual mode. Scanning input directory: {self.input_dir}")
702
+ lang_files = discover_languages(self.input_dir, self.args.lang_subdir)
703
+ if not lang_files:
704
+ log.error("No language subdirectories with parquet files found. Exiting.")
705
+ return
706
+
707
+ log.info(f"Found {len(lang_files)} language(s) with valid parquet files: {sorted(lang_files)}")
708
+
709
+ # ------------------------------------------------------------------ #
710
+ # 2. Measure sizes (UTF-8 text bytes) to drive proportions
711
+ # ------------------------------------------------------------------ #
712
+ log.info(
713
+ f"Estimating text byte sizes (sampling {self.args.text_sample_rows} "
714
+ f"rows per language from column '{self.args.text_column}')…"
715
+ )
716
+ lang_text_sizes: Dict[str, float] = {}
717
+ lang_text_bpr: Dict[str, float] = {}
718
+ lang_row_counts: Dict[str, int] = {}
719
+
720
+ for lang, files in tqdm(lang_files.items(), desc="Measuring text sizes"):
721
+ lang_row_counts[lang] = count_rows(files)
722
+ est_total, est_bpr = estimate_text_bytes(
723
+ files,
724
+ self.args.text_column,
725
+ sample_rows=self.args.text_sample_rows,
726
+ seed=self.args.seed,
727
+ )
728
+ lang_text_sizes[lang] = est_total
729
+ lang_text_bpr[lang] = est_bpr
730
+ log.debug(
731
+ f"[{lang}] {lang_row_counts[lang]:,} rows, "
732
+ f"~{est_total / 1e6:.1f} MB text "
733
+ f"(~{est_bpr:.0f} text bytes/row)"
734
+ )
735
+
736
+ total_input_text_bytes = sum(lang_text_sizes.values())
737
+ log.info(
738
+ f"Total input corpus: ~{total_input_text_bytes / 1e9:.3f} GB text "
739
+ f"across {sum(lang_row_counts.values()):,} rows."
740
+ )
741
+
742
+ if self.total_target_bytes >= total_input_text_bytes:
743
+ log.warning(
744
+ f"Target size ({self.args.total_size_gb} GB text) >= estimated "
745
+ f"input size ({total_input_text_bytes / 1e9:.3f} GB text). "
746
+ "Will use all available rows per language."
747
+ )
748
+
749
+ # ------------------------------------------------------------------ #
750
+ # 3. Compute proportions with temperature + cap
751
+ # ------------------------------------------------------------------ #
752
+ proportions = _calculate_proportions(
753
+ lang_text_sizes,
754
+ self.args.sampling_temp,
755
+ cap=DEFAULT_CAP,
756
+ )
757
+ log.info(
758
+ "Language proportions (based on text bytes):\n"
759
+ + "\n".join(
760
+ f" {lg}: {p*100:.2f}%" for lg, p in sorted(proportions.items())
761
+ )
762
+ )
763
+
764
+ # ------------------------------------------------------------------ #
765
+ # 4. Convert proportions → target row counts with redistribution
766
+ # Each language's text-byte budget is converted to rows using
767
+ # that language's estimated text_bytes_per_row.
768
+ #
769
+ # Languages that are exhausted (budget > available) can't use
770
+ # their full allocation. The surplus text-byte budget is
771
+ # redistributed proportionally among non-exhausted languages.
772
+ # This repeats until stable or a maximum number of iterations.
773
+ # ------------------------------------------------------------------ #
774
+ MAX_REDIST_ITERS = 20
775
+
776
+ # Track which languages are "frozen" (exhausted or floored)
777
+ frozen: Dict[str, int] = {} # lang → final row count
778
+ active_proportions = dict(proportions) # lang → current proportion
779
+ remaining_budget = float(self.total_target_bytes)
780
+
781
+ for iteration in range(MAX_REDIST_ITERS):
782
+ newly_frozen = {}
783
+
784
+ for lang, prop in list(active_proportions.items()):
785
+ lang_text_budget = remaining_budget * prop
786
+ bpr = lang_text_bpr[lang]
787
+ if bpr > 0:
788
+ estimated_rows = int(lang_text_budget / bpr)
789
+ else:
790
+ estimated_rows = 0
791
+
792
+ floored_rows = max(estimated_rows, self.args.min_rows_floor)
793
+ available = lang_row_counts[lang]
794
+
795
+ if floored_rows >= available:
796
+ # Exhausted: freeze at available, reclaim surplus
797
+ newly_frozen[lang] = available
798
+ if floored_rows > available:
799
+ log.debug(
800
+ f"[{lang}] iter {iteration}: requested "
801
+ f"{floored_rows:,} > available {available:,}. "
802
+ f"Freezing at {available:,}."
803
+ )
804
+
805
+ if not newly_frozen:
806
+ # Nothing new to freeze — allocate final rows for active langs
807
+ break
808
+
809
+ # Freeze newly exhausted languages and reclaim their budget
810
+ for lang, rows in newly_frozen.items():
811
+ frozen[lang] = rows
812
+ # Reclaim the text bytes that this language actually uses
813
+ remaining_budget -= rows * lang_text_bpr[lang]
814
+ del active_proportions[lang]
815
+
816
+ # Re-normalise active proportions
817
+ active_total = sum(active_proportions.values())
818
+ if active_total > 0:
819
+ active_proportions = {
820
+ lg: p / active_total for lg, p in active_proportions.items()
821
+ }
822
+ else:
823
+ break
824
+
825
+ log.info(
826
+ f"Redistribution iter {iteration}: froze {len(newly_frozen)} "
827
+ f"language(s), {len(active_proportions)} still active, "
828
+ f"~{remaining_budget / 1e9:.2f} GB budget remaining."
829
+ )
830
+
831
+ # Final allocation for still-active languages
832
+ target_rows: Dict[str, int] = dict(frozen)
833
+ for lang, prop in active_proportions.items():
834
+ lang_text_budget = remaining_budget * prop
835
+ bpr = lang_text_bpr[lang]
836
+ if bpr > 0:
837
+ estimated_rows = int(lang_text_budget / bpr)
838
+ else:
839
+ estimated_rows = 0
840
+ floored_rows = max(estimated_rows, self.args.min_rows_floor)
841
+ capped_rows = min(floored_rows, lang_row_counts[lang])
842
+ target_rows[lang] = capped_rows
843
+
844
+ # Summary logging
845
+ total_target_text = sum(
846
+ target_rows[lg] * lang_text_bpr[lg] for lg in target_rows
847
+ )
848
+ log.info(
849
+ f"Allocation complete after redistribution: "
850
+ f"~{total_target_text / 1e9:.2f} GB text across "
851
+ f"{sum(target_rows.values()):,} rows."
852
+ )
853
+ log.info(
854
+ "Target row counts:\n"
855
+ + "\n".join(
856
+ f" {lg}: {n:,} / {lang_row_counts[lg]:,} available"
857
+ for lg, n in sorted(target_rows.items())
858
+ )
859
+ )
860
+
861
+ # ------------------------------------------------------------------ #
862
+ # 5. Compute common schema across languages
863
+ # Reading schemas from every file on a parallel FS is very slow,
864
+ # so we sample one file per language — the schema should be
865
+ # consistent within a single corpus source.
866
+ # ------------------------------------------------------------------ #
867
+ schema_sample_files = [files[0] for files in lang_files.values()]
868
+ log.info(
869
+ f"Computing common schema from {len(schema_sample_files)} files "
870
+ f"(1 per language)…"
871
+ )
872
+ common_schema = get_common_schema(schema_sample_files)
873
+
874
+ log.info("Common schema across all languages:")
875
+ for field in common_schema:
876
+ if pa.types.is_struct(field.type):
877
+ subfields = [field.type.field(i).name for i in range(field.type.num_fields)]
878
+ log.info(f" {field.name} (struct): {subfields}")
879
+ else:
880
+ log.info(f" {field.name}: {field.type}")
881
+
882
+ # ------------------------------------------------------------------ #
883
+ # 6. Sample and write
884
+ # ------------------------------------------------------------------ #
885
+ manifest = {}
886
+ self.output_dir.mkdir(parents=True, exist_ok=True)
887
+
888
+ for lang, n_rows in tqdm(target_rows.items(), desc="Sampling languages"):
889
+ out_file = self.output_dir / lang / "data.parquet"
890
+
891
+ if out_file.exists():
892
+ log.info(f"[{lang}] Output already exists, skipping.")
893
+ manifest[lang] = {"status": "skipped", "output": str(out_file)}
894
+ continue
895
+
896
+ log.info(f"[{lang}] Sampling {n_rows:,} rows → {out_file}")
897
+ written = sample_language(
898
+ lang=lang,
899
+ parquet_files=lang_files[lang],
900
+ target_rows=n_rows,
901
+ output_path=out_file,
902
+ seed=self.args.seed,
903
+ common_schema=common_schema,
904
+ keep_columns=self.args.columns,
905
+ )
906
+ manifest[lang] = {
907
+ "status": "ok",
908
+ "rows_written": written,
909
+ "rows_available": lang_row_counts[lang],
910
+ "estimated_text_bytes": lang_text_sizes[lang],
911
+ "text_bytes_per_row": lang_text_bpr[lang],
912
+ "output": str(out_file),
913
+ }
914
+ log.info(f"[{lang}] Wrote {written:,} rows.")
915
+
916
+ # ------------------------------------------------------------------ #
917
+ # 7. Save manifest
918
+ # ------------------------------------------------------------------ #
919
+ total_parquet = sum(total_parquet_bytes(files) for files in lang_files.values())
920
+ manifest_path = self.output_dir / "sampling_manifest.json"
921
+ with open(manifest_path, "w", encoding="utf-8") as f:
922
+ json.dump(
923
+ {
924
+ "args": vars(self.args),
925
+ "total_input_parquet_gb": total_parquet / 1e9,
926
+ "total_input_text_gb": total_input_text_bytes / 1e9,
927
+ "target_text_gb": self.args.total_size_gb,
928
+ "schema": [
929
+ {"name": f.name, "type": str(f.type)} for f in common_schema
930
+ ],
931
+ "languages": manifest,
932
+ },
933
+ f,
934
+ indent=2,
935
+ )
936
+ log.info(f"Manifest saved to {manifest_path}")
937
+ log.info("--- Sampling finished ---")
938
+
939
+
940
+ # ---------------------------------------------------------------------------
941
+ # CLI
942
+ # ---------------------------------------------------------------------------
943
+
944
+ def parse_args() -> argparse.Namespace:
945
+ parser = argparse.ArgumentParser(
946
+ description=(
947
+ "Create a sampled copy of a parquet corpus. "
948
+ "In the default multilingual mode the input directory must contain "
949
+ "one subdirectory per language code, each holding one or more .parquet files. "
950
+ "In monolingual mode (--monolingual) the input directory contains "
951
+ ".parquet files directly, with no subdirectories. "
952
+ "Language proportions are determined from UTF-8 text byte sizes "
953
+ "(estimated by sampling) rather than on-disk parquet sizes."
954
+ ),
955
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
956
+ )
957
+
958
+ parser.add_argument(
959
+ "--monolingual",
960
+ action="store_true",
961
+ default=False,
962
+ help=(
963
+ "Enable monolingual mode. The input directory should contain .parquet "
964
+ "files directly (no language subdirectories). The output is a single "
965
+ "data.parquet file in --output_dir. "
966
+ "Temperature sampling and the per-language cap are not applied."
967
+ ),
968
+ )
969
+
970
+ parser.add_argument(
971
+ "--lang_subdir",
972
+ type=str,
973
+ default="",
974
+ help=(
975
+ "Optional subdirectory name to look for parquet files within each "
976
+ "language directory (multilingual mode only). "
977
+ "E.g., '--lang_subdir train' will look for parquet files in "
978
+ "<input_dir>/<lang_code>/train/*.parquet. "
979
+ "Ignored in monolingual mode."
980
+ ),
981
+ )
982
+
983
+ parser.add_argument(
984
+ "--input_dir",
985
+ type=str,
986
+ required=True,
987
+ help=(
988
+ "Root directory of the source corpus. In multilingual mode this must "
989
+ "contain per-language subdirectories; in monolingual mode it must "
990
+ "contain .parquet files directly."
991
+ ),
992
+ )
993
+ parser.add_argument(
994
+ "--output_dir",
995
+ type=str,
996
+ required=True,
997
+ help="Root directory where the sampled corpus will be written.",
998
+ )
999
+ parser.add_argument(
1000
+ "--total_size_gb",
1001
+ type=float,
1002
+ required=True,
1003
+ help=(
1004
+ "Target total size in GB of raw UTF-8 text. This is measured against "
1005
+ "the estimated text byte content (not on-disk parquet size). "
1006
+ "If this exceeds the estimated input text size, all available rows "
1007
+ "are used."
1008
+ ),
1009
+ )
1010
+ parser.add_argument(
1011
+ "--text_column",
1012
+ type=str,
1013
+ default=DEFAULT_TEXT_COLUMN,
1014
+ help="Name of the text column in the parquet files.",
1015
+ )
1016
+ parser.add_argument(
1017
+ "--text_sample_rows",
1018
+ type=int,
1019
+ default=DEFAULT_TEXT_SAMPLE_ROWS,
1020
+ help=(
1021
+ "Number of rows to sample per language for estimating average text "
1022
+ "byte size. Higher values give more accurate estimates but take "
1023
+ "longer on large corpora."
1024
+ ),
1025
+ )
1026
+ parser.add_argument(
1027
+ "--sampling_temp",
1028
+ type=float,
1029
+ default=DEFAULT_TEMP,
1030
+ help=(
1031
+ "Temperature for language proportion sampling (multilingual mode only). "
1032
+ "T=1.0 → proportional to text byte sizes. "
1033
+ "T>1.0 → upsamples smaller languages (flattens distribution). "
1034
+ "Uses the same size^(1/T) formula as corpus_downloader.py."
1035
+ ),
1036
+ )
1037
+ parser.add_argument(
1038
+ "--min_rows_floor",
1039
+ type=int,
1040
+ default=DEFAULT_MIN_ROWS,
1041
+ help=(
1042
+ "Minimum number of rows to sample per language. "
1043
+ "If the proportional allocation is below this value the floor is "
1044
+ "used instead (capped at whatever is available). "
1045
+ "Will NOT oversample beyond the available rows."
1046
+ ),
1047
+ )
1048
+ parser.add_argument(
1049
+ "--seed",
1050
+ type=int,
1051
+ default=DEFAULT_SEED,
1052
+ help="Random seed for reproducible sampling.",
1053
+ )
1054
+ parser.add_argument(
1055
+ "--columns",
1056
+ type=str,
1057
+ nargs="+",
1058
+ default=None,
1059
+ help=(
1060
+ "Keep only these columns in the output parquet files. "
1061
+ "If not specified, all columns are kept. "
1062
+ "The text column (--text_column) is always included."
1063
+ ),
1064
+ )
1065
+
1066
+ args = parser.parse_args()
1067
+
1068
+ if args.total_size_gb <= 0:
1069
+ parser.error("--total_size_gb must be positive.")
1070
+ if args.sampling_temp <= 0:
1071
+ parser.error("--sampling_temp must be positive.")
1072
+ if args.min_rows_floor < 0:
1073
+ parser.error("--min_rows_floor must be non-negative.")
1074
+ if args.text_sample_rows <= 0:
1075
+ parser.error("--text_sample_rows must be positive.")
1076
+
1077
+ # Ensure text column is always in the keep list
1078
+ if args.columns is not None and args.text_column not in args.columns:
1079
+ args.columns.append(args.text_column)
1080
+
1081
+ return args
1082
+
1083
+
1084
+ def main():
1085
+ args = parse_args()
1086
+ random.seed(args.seed)
1087
+ log.info(f"Starting corpus sampler with args: {json.dumps(vars(args), indent=2)}")
1088
+ sampler = CorpusSampler(args)
1089
+ sampler.run()
1090
+
1091
+
1092
+ if __name__ == "__main__":
1093
+ main()
lm_training_mixture/metadata.json ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sources": [
3
+ {
4
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/HuggingFaceFW/fineweb-edu/data",
5
+ "input_weight": 0.3684171745560573,
6
+ "text_field": "text",
7
+ "docs": 1842655,
8
+ "text_bytes": 9224926152,
9
+ "actual_byte_fraction": 0.36949816550749137
10
+ },
11
+ {
12
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/rus_Cyrl",
13
+ "input_weight": 0.1063567751918401,
14
+ "text_field": "text",
15
+ "docs": 531387,
16
+ "text_bytes": 4521169731,
17
+ "actual_byte_fraction": 0.18109238968707772
18
+ },
19
+ {
20
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/spa_Latn",
21
+ "input_weight": 0.024462900390522208,
22
+ "text_field": "text",
23
+ "docs": 122231,
24
+ "text_bytes": 422520665,
25
+ "actual_byte_fraction": 0.01692377890446936
26
+ },
27
+ {
28
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/deu_Latn",
29
+ "input_weight": 0.02375764465637204,
30
+ "text_field": "text",
31
+ "docs": 118340,
32
+ "text_bytes": 352848302,
33
+ "actual_byte_fraction": 0.014133099619791223
34
+ },
35
+ {
36
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/fra_Latn",
37
+ "input_weight": 0.020599783160177264,
38
+ "text_field": "text",
39
+ "docs": 103496,
40
+ "text_bytes": 363817121,
41
+ "actual_byte_fraction": 0.01457244823153106
42
+ },
43
+ {
44
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/cmn_Hani",
45
+ "input_weight": 0.019147166871927666,
46
+ "text_field": "text",
47
+ "docs": 95805,
48
+ "text_bytes": 326062469,
49
+ "actual_byte_fraction": 0.013060211231091846
50
+ },
51
+ {
52
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/jpn_Jpan",
53
+ "input_weight": 0.01265249839475374,
54
+ "text_field": "text",
55
+ "docs": 63316,
56
+ "text_bytes": 203932098,
57
+ "actual_byte_fraction": 0.008168361985505676
58
+ },
59
+ {
60
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ita_Latn",
61
+ "input_weight": 0.011947242660603574,
62
+ "text_field": "text",
63
+ "docs": 59676,
64
+ "text_bytes": 165025109,
65
+ "actual_byte_fraction": 0.006609968907442567
66
+ },
67
+ {
68
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/por_Latn",
69
+ "input_weight": 0.011905137840654311,
70
+ "text_field": "text",
71
+ "docs": 59460,
72
+ "text_bytes": 188799748,
73
+ "actual_byte_fraction": 0.007562245961085789
74
+ },
75
+ {
76
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/tur_Latn",
77
+ "input_weight": 0.009410427258660436,
78
+ "text_field": "text",
79
+ "docs": 47074,
80
+ "text_bytes": 152005957,
81
+ "actual_byte_fraction": 0.006088495596849155
82
+ },
83
+ {
84
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ind_Latn",
85
+ "input_weight": 0.009126219724002906,
86
+ "text_field": "text",
87
+ "docs": 45970,
88
+ "text_bytes": 236317338,
89
+ "actual_byte_fraction": 0.009465530827006428
90
+ },
91
+ {
92
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/pol_Latn",
93
+ "input_weight": 0.008799907369396112,
94
+ "text_field": "text",
95
+ "docs": 43902,
96
+ "text_bytes": 106893993,
97
+ "actual_byte_fraction": 0.00428156645012356
98
+ },
99
+ {
100
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ukr_Cyrl",
101
+ "input_weight": 0.006778876011831456,
102
+ "text_field": "text",
103
+ "docs": 34088,
104
+ "text_bytes": 210911553,
105
+ "actual_byte_fraction": 0.00844791932572167
106
+ },
107
+ {
108
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/nld_Latn",
109
+ "input_weight": 0.006494668477173925,
110
+ "text_field": "text",
111
+ "docs": 32404,
112
+ "text_bytes": 70708339,
113
+ "actual_byte_fraction": 0.0028321746013020882
114
+ },
115
+ {
116
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ron_Latn",
117
+ "input_weight": 0.005789412743023758,
118
+ "text_field": "text",
119
+ "docs": 29203,
120
+ "text_bytes": 97479339,
121
+ "actual_byte_fraction": 0.0039044688642384333
122
+ },
123
+ {
124
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/arb_Arab",
125
+ "input_weight": 0.005410469363480385,
126
+ "text_field": "text",
127
+ "docs": 27292,
128
+ "text_bytes": 168441711,
129
+ "actual_byte_fraction": 0.006746818585203459
130
+ },
131
+ {
132
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/hun_Latn",
133
+ "input_weight": 0.005084157008873592,
134
+ "text_field": "text",
135
+ "docs": 25066,
136
+ "text_bytes": 98950889,
137
+ "actual_byte_fraction": 0.003963410802254345
138
+ },
139
+ {
140
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/vie_Latn",
141
+ "input_weight": 0.004326270249786845,
142
+ "text_field": "text",
143
+ "docs": 21306,
144
+ "text_bytes": 108891716,
145
+ "actual_byte_fraction": 0.004361583891079668
146
+ },
147
+ {
148
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ces_Latn",
149
+ "input_weight": 0.004284165429837581,
150
+ "text_field": "text",
151
+ "docs": 21696,
152
+ "text_bytes": 77089494,
153
+ "actual_byte_fraction": 0.0030877674404716214
154
+ },
155
+ {
156
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ell_Grek",
157
+ "input_weight": 0.0035262786707508345,
158
+ "text_field": "text",
159
+ "docs": 17672,
160
+ "text_bytes": 108164216,
161
+ "actual_byte_fraction": 0.004332444371588943
162
+ },
163
+ {
164
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/fin_Latn",
165
+ "input_weight": 0.002347343712171451,
166
+ "text_field": "text",
167
+ "docs": 11721,
168
+ "text_bytes": 34189230,
169
+ "actual_byte_fraction": 0.0013694264384300613
170
+ },
171
+ {
172
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/tha_Thai",
173
+ "input_weight": 0.0023052388922221874,
174
+ "text_field": "text",
175
+ "docs": 11639,
176
+ "text_bytes": 86947590,
177
+ "actual_byte_fraction": 0.003482626795156756
178
+ },
179
+ {
180
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/slk_Latn",
181
+ "input_weight": 0.001978926537615394,
182
+ "text_field": "text",
183
+ "docs": 10015,
184
+ "text_bytes": 27627893,
185
+ "actual_byte_fraction": 0.0011066165313555415
186
+ },
187
+ {
188
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/bul_Cyrl",
189
+ "input_weight": 0.001926295512678814,
190
+ "text_field": "text",
191
+ "docs": 9513,
192
+ "text_bytes": 51667330,
193
+ "actual_byte_fraction": 0.002069499889441519
194
+ },
195
+ {
196
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/hrv_Latn",
197
+ "input_weight": 0.001694719002957864,
198
+ "text_field": "text",
199
+ "docs": 8395,
200
+ "text_bytes": 26289008,
201
+ "actual_byte_fraction": 0.0010529884000107458
202
+ },
203
+ {
204
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/kor_Hang",
205
+ "input_weight": 0.0016420879780212842,
206
+ "text_field": "text",
207
+ "docs": 8263,
208
+ "text_bytes": 29412658,
209
+ "actual_byte_fraction": 0.0011781040839381714
210
+ },
211
+ {
212
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/cat_Latn",
213
+ "input_weight": 0.0010315680887569606,
214
+ "text_field": "text",
215
+ "docs": 5087,
216
+ "text_bytes": 13853762,
217
+ "actual_byte_fraction": 0.0005549030485482628
218
+ },
219
+ {
220
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/hin_Deva",
221
+ "input_weight": 0.000989463268807697,
222
+ "text_field": "text",
223
+ "docs": 4928,
224
+ "text_bytes": 32306762,
225
+ "actual_byte_fraction": 0.0012940254583934075
226
+ },
227
+ {
228
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/heb_Hebr",
229
+ "input_weight": 0.0009368322438711172,
230
+ "text_field": "text",
231
+ "docs": 4665,
232
+ "text_bytes": 25031907,
233
+ "actual_byte_fraction": 0.0010026360713628977
234
+ },
235
+ {
236
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/ben_Beng",
237
+ "input_weight": 0.0007052557341501669,
238
+ "text_field": "text",
239
+ "docs": 3525,
240
+ "text_bytes": 23728899,
241
+ "actual_byte_fraction": 0.0009504449689401207
242
+ },
243
+ {
244
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/fineweb-2_0_1-quality_33-filterrobots/data/output/tam_Taml",
245
+ "input_weight": 0.0003789433795433733,
246
+ "text_field": "text",
247
+ "docs": 1831,
248
+ "text_bytes": 17154744,
249
+ "actual_byte_fraction": 0.0006871216455620517
250
+ },
251
+ {
252
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/HuggingFaceTB/finemath/finemath-4plus",
253
+ "input_weight": 0.15789307480973885,
254
+ "text_field": "text",
255
+ "docs": 789531,
256
+ "text_bytes": 4009353346,
257
+ "actual_byte_fraction": 0.1605919312315729
258
+ },
259
+ {
260
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/starcoderdata/thresholds/python/threshold_0",
261
+ "input_weight": 0.10526204987315925,
262
+ "text_field": "content",
263
+ "docs": 525657,
264
+ "text_bytes": 2494231654,
265
+ "actual_byte_fraction": 0.09990475862009003
266
+ },
267
+ {
268
+ "path": "/capstor/store/cscs/swissai/infra01/datasets/swiss-ai/starcoderdata/thresholds/javascript/threshold_0",
269
+ "input_weight": 0.052631024936579625,
270
+ "text_field": "content",
271
+ "docs": 263191,
272
+ "text_bytes": 889343870,
273
+ "actual_byte_fraction": 0.03562206602587152
274
+ }
275
+ ],
276
+ "total_docs": 5000000,
277
+ "total_text_bytes": 24966094593,
278
+ "num_files": 101,
279
+ "val_docs": 0,
280
+ "seed": 42
281
+ }
lm_training_mixture/shard_00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ccd7aecc4adfd282af5d45787d2f3642869ea6a4470b8b163f3b0b8b441fde94
3
+ size 152011673
lm_training_mixture/shard_00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecbefdf9bb57463be0aec4963fa7f32f3c405687728f10a0bffc93827d7b01a9
3
+ size 138965606
lm_training_mixture/shard_00009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37ed8cd92147bd45eac9c775d2c74862ff295d2a5d170741ea3d0568b36b00e3
3
+ size 136520242
lm_training_mixture/shard_00010.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:213e40fec64b6899710ca3bd5ef351bf0ac76e1923a72e304afcbcecb343fb10
3
+ size 140025291
lm_training_mixture/shard_00012.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:900ec90d7ef59c7cc2b040264b29f009eac453ad7144b0732c4c96698de7ca59
3
+ size 144248910
lm_training_mixture/shard_00017.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43801d3fbe14a73978573ba8401688b005ad2a17c6375dbf34bd061b49e0f676
3
+ size 139064361
lm_training_mixture/shard_00021.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e66b96bff9cb1b00d25f0c63af02de58041483a25fbbd20c4b87941f67165d4
3
+ size 133646959
lm_training_mixture/shard_00025.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:601e290d5f0b6bbef46b4c2c07c9317847c4ccc67185783826ecbe3bf2567c7d
3
+ size 138287714
lm_training_mixture/shard_00026.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0bfe57c4b7b3dd7a1f8b96080031c5855dc54a6c8bf14ef3b6d35489b6e4eda1
3
+ size 137064752
lm_training_mixture/shard_00030.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efbc75216cbd8aad290a80376cf963885017eddbf7b852da5d8ffd0760f45029
3
+ size 133470609
lm_training_mixture/shard_00035.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fefce2a9f73f496e593b1637947a4bbf698c6b4c01351ca57e482a6072d1d7c3
3
+ size 137222001
lm_training_mixture/shard_00038.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01c93ebff77be206a6488d4375169b86611792c8eb914698d8bb3e3985ad66f3
3
+ size 135105363
lm_training_mixture/shard_00040.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e47f4772d02bc0756009b5fff9eea1c1ea02ca368f13069f048249f1ad1e98ef
3
+ size 140572123
lm_training_mixture/shard_00044.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cd742494db3cb581b8ca622a5030f4db3336cf212e23000dabf040866730778
3
+ size 130788725
lm_training_mixture/shard_00047.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04c0c936a24b17b61569f592fbd2cfef981a548d3dd8c78abd4355b93128c05a
3
+ size 137283847
lm_training_mixture/shard_00048.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c3d70d07af75d5e8959bfd4e39928ff01d4f18b11d43ef0283aadc391c40d7d
3
+ size 131850439
lm_training_mixture/shard_00049.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fef2899812adf7e7eaae835b981136c7a895b8e0afc109dea23199098ec2f22
3
+ size 132599697
lm_training_mixture/shard_00051.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfb4cafedb2bec28a299622886b0b264de0b1434b4395e4b102f2ac01120b75a
3
+ size 130511072
lm_training_mixture/shard_00056.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af9a097672bfcd00be2018e1e6d3ac6a28603082d168347eb69d58545aeac350
3
+ size 136139259
lm_training_mixture/shard_00067.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b626d3cc6457f4ade69be71f559be3ba885efae86249b62e1f2b5fac96ca2c00
3
+ size 130751461
lm_training_mixture/shard_00070.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfeb22bd2d5536cd6ce5e85b0d461bbe33811b320b7c1d7f3e495ce49471b642
3
+ size 134843880
lm_training_mixture/shard_00073.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48b60431081f1882af875442a29c4b79d7e26694fd511b2967ff9ae37580c23f
3
+ size 130071106
lm_training_mixture/shard_00074.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a40daaa6893b33c79d5f5474bd64afc4f2fa181d40f3ef08dd6d74a805370ddb
3
+ size 127995791
lm_training_mixture/shard_00079.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3dbf7b6f9a8fe4369b8576ba9a2826872bf0a480b1c671d0aeebed3f98d00c3d
3
+ size 136702887
lm_training_mixture/shard_00081.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c27f9e24c241fa9ace7b984cf8918a14765cfb88bf8bb8aa7342fbd16965be3
3
+ size 134665924
lm_training_mixture/shard_00084.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8e715f95bf36614182ea184cde8e522cd268a0ddd7c45b99f8be78417a4664a
3
+ size 134349657
lm_training_mixture/shard_00091.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56f48200ead2d9af3510ec73573bf04e1fca115e2575cd227984ed7cd80ce9e0
3
+ size 139139102
lm_training_mixture/shard_00096.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:daa2dc56047c2e544ed5e6ed704c130756fed255d16d9f707135aa297e0cef36
3
+ size 131130968
tokenizer_training_pool/fineweb2/mic_Latn.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7a3d1cbc8c3e05ed8d91de85fee74bc0424786d88114cb7525c17d5c3d98747
3
+ size 124041
tokenizer_training_pool/sampling_stats.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_training_pool/starcoder/assembly.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a141bea23af3dc706a0e6c5e1420d344bee2f27015ea8743b761ebe52d46e76
3
+ size 2607332
tokenizer_training_pool/starcoder/c-sharp.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69186b6a63916b3e874596a981d7059a50c7494c13a1e6cee6866a7dbaced347
3
+ size 7101294
tokenizer_training_pool/starcoder/c.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03e598ba7a0f0d71484f4eb0deefd4096aab7eeab83bf78a1e9260f05a0de8fa
3
+ size 7404176
tokenizer_training_pool/starcoder/dart.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1df9564e6ce5fc892b6bd0938b6f3c701e1ba045ccaa0be09c11c3194c063a98
3
+ size 2898493
tokenizer_training_pool/starcoder/haskell.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94e5210c1f9e9df71dd09f5e160c121500aac7f5acc13964f0ea0dcc8e37cca3
3
+ size 3028346
tokenizer_training_pool/starcoder/java.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:442c3aa28caa3de78ba90b86eb4a706abe68ee28d65f6a0e4a32177733758595
3
+ size 9047512
tokenizer_training_pool/starcoder/lua.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a701443d4c1f16ab7c89667529c53e107235d35b54585533628dc87ab73c831d
3
+ size 2953550
tokenizer_training_pool/starcoder/mathematica.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95d0d6affbd7056b0c78b4140e03431e7427f1d62d52d8a6e61bd7d87154272c
3
+ size 4705533
tokenizer_training_pool/starcoder/protocol-buffer.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b28fbaf0cc8bde26f79de584041b21e87f19da994935e173dccf5ce7f92163a2
3
+ size 1204120
tokenizer_training_pool/starcoder/python.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e10d833ce5a28d90b4985b6b7c2280bd3e97025755397c54ca3641230228c510
3
+ size 8508523
tokenizer_training_pool/starcoder/scala.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b7e00d65beba8814ce75b27330d734f6871ee90e249e7f82abcd918113b66dc
3
+ size 3501519
tokenizer_training_pool/starcoder/stan.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c924a1004a2629e89a35722d22c3cae32e9752da28ecb6a9c8ebbd7c060c2279
3
+ size 459452
tokenizer_training_pool/starcoder/tcl.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f96ac3e7d1a2ccb180d2b0d479c413b0af9b95178d68cd7ee1ae2c0d960a71c
3
+ size 1411873
tokenizer_training_pool/tokenizer_dataset_sampler.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ tokenizer_sampler.py
4
+
5
+ Creates a tokenizer training dataset by sampling from multiple corpus sources
6
+ (both monolingual and multilingual). Each source is sampled independently with
7
+ its own temperature parameter and size target.
8
+
9
+ Language proportions are determined from **UTF-8 text byte sizes** (measured
10
+ from the text column) rather than on-disk parquet byte sizes, ensuring
11
+ consistent cross-lingual sampling regardless of compression ratios or
12
+ metadata overhead.
13
+
14
+ Config file structure (JSON):
15
+ {
16
+ "sources": [
17
+ {
18
+ "name": "fineweb2",
19
+ "path": "/path/to/fineweb2_sample",
20
+ "is_monolingual": false,
21
+ "target_size_gb": 5.0,
22
+ "sampling_temp": 5.0,
23
+ "min_samples_per_language": 1000,
24
+ "text_column": "text"
25
+ },
26
+ {
27
+ "name": "finemath",
28
+ "path": "/path/to/finemath_sample",
29
+ "is_monolingual": true,
30
+ "target_size_gb": 2.0,
31
+ "min_samples_per_language": 500,
32
+ "text_column": "text"
33
+ }
34
+ ],
35
+ "output_dir": "/path/to/tokenizer_corpus",
36
+ "seed": 42
37
+ }
38
+
39
+ Output structure:
40
+ output_dir/
41
+ <source_name>/
42
+ <lang_code>.parquet (for multilingual sources)
43
+ data.parquet (for monolingual sources)
44
+ ...
45
+ sampling_stats.json
46
+
47
+ For monolingual sources, the source name itself serves as the "language"
48
+ identifier in the output structure.
49
+ """
50
+
51
+ import json
52
+ import math
53
+ import random
54
+ import logging
55
+ from pathlib import Path
56
+ from typing import Dict, List, Optional, Tuple
57
+
58
+ import pyarrow as pa
59
+ import pyarrow.compute as pc
60
+ import pyarrow.parquet as pq
61
+ from tqdm import tqdm
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Logging
65
+ # ---------------------------------------------------------------------------
66
+
67
+ logging.basicConfig(
68
+ level=logging.INFO,
69
+ format="%(asctime)s - %(levelname)s - %(message)s",
70
+ )
71
+ log = logging.getLogger(__name__)
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Defaults
75
+ # ---------------------------------------------------------------------------
76
+
77
+ DEFAULT_TEMP = 3.0
78
+ DEFAULT_CAP = 0.5
79
+ DEFAULT_MIN_SAMPLES = 1000
80
+ DEFAULT_SEED = 42
81
+ DEFAULT_TEXT_COLUMN = "text"
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Helper functions
85
+ # ---------------------------------------------------------------------------
86
+
87
+ def validate_parquet_files(files: List[Path]) -> List[Path]:
88
+ """
89
+ Return only the files that can be opened as valid parquet files.
90
+ Corrupt or invalid files are logged as warnings and excluded.
91
+ """
92
+ valid = []
93
+ for f in files:
94
+ try:
95
+ pq.ParquetFile(f)
96
+ valid.append(f)
97
+ except Exception as e:
98
+ log.warning(f"Skipping corrupt/invalid parquet file '{f}': {e}")
99
+ return valid
100
+
101
+
102
+ def total_parquet_bytes(files: List[Path]) -> int:
103
+ """Return the sum of on-disk sizes (bytes) for a list of parquet files."""
104
+ return sum(f.stat().st_size for f in files)
105
+
106
+
107
+ def count_rows(files: List[Path]) -> int:
108
+ """Count total rows across a list of parquet files without loading data."""
109
+ total = 0
110
+ for f in files:
111
+ pf = pq.ParquetFile(f)
112
+ total += pf.metadata.num_rows
113
+ return total
114
+
115
+
116
+ def _measure_text_bytes_in_table(table: pa.Table, text_column: str) -> int:
117
+ """Sum UTF-8 byte lengths of the text column in an Arrow table."""
118
+ col = table.column(text_column)
119
+ # Cast to binary to get raw UTF-8 byte lengths (not character counts)
120
+ byte_lengths = pc.binary_length(col.cast(pa.large_binary()))
121
+ return pc.sum(byte_lengths, skip_nulls=True).as_py() or 0
122
+
123
+
124
+ def measure_text_bytes(
125
+ files: List[Path],
126
+ text_column: str,
127
+ ) -> Tuple[int, float]:
128
+ """
129
+ Measure total UTF-8 text bytes across all files by reading the text column.
130
+
131
+ Returns (total_text_bytes, avg_text_bytes_per_row).
132
+ """
133
+ total_text_bytes = 0
134
+ total_rows = 0
135
+ for f in files:
136
+ table = pq.read_table(f, columns=[text_column])
137
+ total_text_bytes += _measure_text_bytes_in_table(table, text_column)
138
+ total_rows += len(table)
139
+
140
+ avg = total_text_bytes / total_rows if total_rows > 0 else 0.0
141
+ return total_text_bytes, avg
142
+
143
+
144
+ def _calculate_proportions(
145
+ original_sizes: Dict[str, float],
146
+ temperature: float,
147
+ cap: float = DEFAULT_CAP,
148
+ ) -> Dict[str, float]:
149
+ """
150
+ Compute per-language sampling proportions with temperature scaling and
151
+ a per-language cap.
152
+ """
153
+ if not original_sizes:
154
+ return {}
155
+
156
+ # --- 1. Temperature scaling ---
157
+ if temperature == 1.0:
158
+ powered = dict(original_sizes)
159
+ else:
160
+ log.debug(f"Applying temperature {temperature} to size-based proportions.")
161
+ powered = {lg: size ** (1.0 / temperature) for lg, size in original_sizes.items()}
162
+
163
+ total_powered = sum(powered.values())
164
+ if total_powered == 0:
165
+ return {}
166
+
167
+ proportions: Dict[str, float] = {
168
+ lg: p / total_powered for lg, p in powered.items()
169
+ }
170
+
171
+ # --- 2. Cap ---
172
+ capping_needed = any(p > cap for p in proportions.values())
173
+ if capping_needed:
174
+ for lg, prop in proportions.items():
175
+ if prop > cap:
176
+ log.warning(
177
+ f"[{lg}] proportion {prop*100:.1f}% exceeds cap. "
178
+ f"Capping at {cap*100:.0f}%."
179
+ )
180
+ proportions[lg] = cap
181
+
182
+ capped_total = sum(p for p in proportions.values() if p == cap)
183
+ remaining = 1.0 - capped_total
184
+ uncapped_powered_total = sum(
185
+ powered[lg] for lg, p in proportions.items() if p < cap
186
+ )
187
+ if uncapped_powered_total > 0:
188
+ for lg in proportions:
189
+ if proportions[lg] < cap:
190
+ proportions[lg] = (powered[lg] / uncapped_powered_total) * remaining
191
+ elif remaining > 0:
192
+ log.warning("All languages are at the cap. Distribution may not sum to 1.")
193
+
194
+ # --- 3. Re-normalise ---
195
+ total = sum(proportions.values())
196
+ if not math.isclose(total, 1.0, rel_tol=1e-5):
197
+ log.debug(f"Proportions sum to {total:.6f}; re-normalising.")
198
+ proportions = {lg: p / total for lg, p in proportions.items()}
199
+
200
+ return proportions
201
+
202
+
203
+ def cast_to_large_string(schema: pa.Schema) -> pa.Schema:
204
+ """Cast all string columns (including inside structs) to large_string."""
205
+ new_fields = []
206
+ for field in schema:
207
+ if pa.types.is_string(field.type):
208
+ new_fields.append(pa.field(field.name, pa.large_string()))
209
+ elif pa.types.is_struct(field.type):
210
+ subfields = []
211
+ for i in range(field.type.num_fields):
212
+ sf = field.type.field(i)
213
+ if pa.types.is_string(sf.type):
214
+ subfields.append(pa.field(sf.name, pa.large_string()))
215
+ else:
216
+ subfields.append(sf)
217
+ new_fields.append(pa.field(field.name, pa.struct(subfields)))
218
+ else:
219
+ new_fields.append(field)
220
+ return pa.schema(new_fields)
221
+
222
+
223
+ def sample_rows(
224
+ parquet_files: List[Path],
225
+ target_rows: int,
226
+ output_path: Path,
227
+ seed: int,
228
+ ) -> int:
229
+ """
230
+ Sample target_rows from parquet_files and write to output_path.
231
+ Returns the actual number of rows written.
232
+ """
233
+ total_rows = count_rows(parquet_files)
234
+ actual_target = min(target_rows, total_rows)
235
+
236
+ if actual_target <= 0:
237
+ log.warning(f"target_rows={target_rows}, total_rows={total_rows}. Nothing to write.")
238
+ return 0
239
+
240
+ # Build sorted index set
241
+ rng = random.Random(seed)
242
+ selected = sorted(rng.sample(range(total_rows), actual_target))
243
+
244
+ # Materialise selected rows
245
+ collected_batches: List[pa.Table] = []
246
+ file_row_counts = [pq.ParquetFile(f).metadata.num_rows for f in parquet_files]
247
+ global_idx = 0
248
+ large_schema = None # Will be set on first batch
249
+
250
+ for file_path, file_row_count in zip(parquet_files, file_row_counts):
251
+ file_start = global_idx
252
+ file_end = global_idx + file_row_count
253
+
254
+ local_indices = [
255
+ gi - file_start
256
+ for gi in selected
257
+ if file_start <= gi < file_end
258
+ ]
259
+
260
+ if local_indices:
261
+ pf = pq.ParquetFile(file_path)
262
+
263
+ # Build large_string schema once, handling structs
264
+ if large_schema is None:
265
+ large_schema = cast_to_large_string(pf.schema_arrow)
266
+
267
+ row_offset = 0
268
+ for rg in range(pf.metadata.num_row_groups):
269
+ rg_rows = pf.metadata.row_group(rg).num_rows
270
+ rg_needed = [
271
+ li - row_offset
272
+ for li in local_indices
273
+ if row_offset <= li < row_offset + rg_rows
274
+ ]
275
+ if rg_needed:
276
+ batch = pf.read_row_group(rg)
277
+ # Cast to large_string BEFORE take to avoid overflow
278
+ batch = batch.cast(large_schema)
279
+ filtered = batch.take(pa.array(rg_needed))
280
+ collected_batches.append(filtered)
281
+ row_offset += rg_rows
282
+
283
+ global_idx = file_end
284
+
285
+ if not collected_batches:
286
+ log.warning(f"No rows collected despite target={actual_target}.")
287
+ return 0
288
+
289
+ output_path.parent.mkdir(parents=True, exist_ok=True)
290
+ table = pa.concat_tables(collected_batches)
291
+ pq.write_table(table, output_path, compression="snappy")
292
+
293
+ return len(table)
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # Source discovery
298
+ # ---------------------------------------------------------------------------
299
+
300
+ def discover_source(source_path: Path, is_monolingual: bool) -> Dict[str, List[Path]]:
301
+ """
302
+ Discover parquet files in a source directory.
303
+
304
+ For monolingual sources: returns {"monolingual": [list of parquet files]}
305
+ For multilingual sources: returns {lang_code: [list of parquet files], ...}
306
+ """
307
+ if is_monolingual:
308
+ parquets = validate_parquet_files(sorted(source_path.glob("*.parquet")))
309
+ if not parquets:
310
+ log.warning(f"No valid parquet files found in monolingual source '{source_path}'")
311
+ return {}
312
+ return {"monolingual": parquets}
313
+ else:
314
+ # Multilingual: expect subdirectories named by language code
315
+ langs: Dict[str, List[Path]] = {}
316
+ for subdir in sorted(source_path.iterdir()):
317
+ if not subdir.is_dir():
318
+ continue
319
+ parquets = validate_parquet_files(sorted(subdir.glob("*.parquet")))
320
+ if parquets:
321
+ langs[subdir.name] = parquets
322
+ else:
323
+ log.debug(f"Skipping '{subdir.name}': no valid parquet files found.")
324
+ return langs
325
+
326
+
327
+ # ---------------------------------------------------------------------------
328
+ # Main sampler
329
+ # ---------------------------------------------------------------------------
330
+
331
+ class TokenizerSampler:
332
+ def __init__(self, config_path: Path):
333
+ self.config_path = config_path
334
+ with open(config_path, 'r') as f:
335
+ self.config = json.load(f)
336
+
337
+ self.output_dir = Path(self.config['output_dir'])
338
+ self.seed = self.config.get('seed', DEFAULT_SEED)
339
+ random.seed(self.seed)
340
+
341
+ self.sources = self.config['sources']
342
+
343
+ def run(self):
344
+ log.info(f"Starting tokenizer sampler with config: {self.config_path}")
345
+
346
+ manifest = {
347
+ "config": self.config,
348
+ "sources": {}
349
+ }
350
+
351
+ for source_config in self.sources:
352
+ source_name = source_config['name']
353
+ log.info(f"\n{'='*60}")
354
+ log.info(f"Processing source: {source_name}")
355
+ log.info(f"{'='*60}")
356
+
357
+ source_manifest = self._process_source(source_config)
358
+ manifest["sources"][source_name] = source_manifest
359
+
360
+ # Save manifest
361
+ manifest_path = self.output_dir / "sampling_stats.json"
362
+ with open(manifest_path, 'w', encoding='utf-8') as f:
363
+ json.dump(manifest, f, indent=2)
364
+
365
+ log.info(f"\n{'='*60}")
366
+ log.info(f"Tokenizer sampling complete!")
367
+ log.info(f"Manifest: {manifest_path}")
368
+ log.info(f"{'='*60}")
369
+
370
+ def _process_source(self, source_config: dict) -> dict:
371
+ """Process a single source and return its manifest."""
372
+ source_name = source_config['name']
373
+ source_path = Path(source_config['path'])
374
+ is_monolingual = source_config['is_monolingual']
375
+ target_size_gb = source_config['target_size_gb']
376
+ target_bytes = int(target_size_gb * (1024 ** 3))
377
+ sampling_temp = source_config.get('sampling_temp', DEFAULT_TEMP)
378
+ min_samples = source_config.get('min_samples_per_language', DEFAULT_MIN_SAMPLES)
379
+ text_column = source_config.get('text_column', DEFAULT_TEXT_COLUMN)
380
+
381
+ # Discover files
382
+ lang_files = discover_source(source_path, is_monolingual)
383
+ if not lang_files:
384
+ log.error(f"[{source_name}] No valid files found. Skipping.")
385
+ return {"status": "skipped", "reason": "no valid files"}
386
+
387
+ log.info(f"[{source_name}] Found {len(lang_files)} language(s): {sorted(lang_files.keys())}")
388
+
389
+ # Measure text byte sizes (input is already a sample, so full read is fine)
390
+ log.info(f"[{source_name}] Measuring UTF-8 text bytes (column: '{text_column}')…")
391
+ lang_text_sizes: Dict[str, int] = {}
392
+ lang_text_bpr: Dict[str, float] = {}
393
+ lang_row_counts: Dict[str, int] = {}
394
+
395
+ for lang, files in tqdm(lang_files.items(), desc=f"Measuring {source_name}"):
396
+ lang_row_counts[lang] = count_rows(files)
397
+ text_bytes, text_bpr = measure_text_bytes(files, text_column)
398
+ lang_text_sizes[lang] = text_bytes
399
+ lang_text_bpr[lang] = text_bpr
400
+ log.info(
401
+ f" [{lang}] {lang_row_counts[lang]:,} rows, "
402
+ f"{text_bytes / 1e6:.1f} MB text "
403
+ f"(~{text_bpr:.0f} text bytes/row)"
404
+ )
405
+
406
+ total_input_text_bytes = sum(lang_text_sizes.values())
407
+ log.info(
408
+ f"[{source_name}] Total: {total_input_text_bytes / 1e9:.3f} GB text"
409
+ )
410
+
411
+ # Calculate proportions
412
+ if is_monolingual:
413
+ # Monolingual: single "language", no temperature needed
414
+ proportions = {"monolingual": 1.0}
415
+ else:
416
+ # Multilingual: apply temperature to text byte sizes
417
+ proportions = _calculate_proportions(
418
+ lang_text_sizes,
419
+ sampling_temp,
420
+ cap=DEFAULT_CAP,
421
+ )
422
+ log.info(
423
+ f"[{source_name}] Language proportions (T={sampling_temp}, text-byte-based):\n" +
424
+ "\n".join(f" {lg}: {p*100:.2f}%" for lg, p in sorted(proportions.items()))
425
+ )
426
+
427
+ # Calculate target rows per language with redistribution
428
+ # Languages that can't fill their budget have their surplus
429
+ # redistributed to languages with remaining capacity.
430
+ MAX_REDIST_ITERS = 20
431
+
432
+ frozen: Dict[str, int] = {}
433
+ active_proportions = dict(proportions)
434
+ remaining_budget = float(target_bytes)
435
+
436
+ for iteration in range(MAX_REDIST_ITERS):
437
+ newly_frozen = {}
438
+
439
+ for lang, prop in list(active_proportions.items()):
440
+ lang_text_budget = remaining_budget * prop
441
+ bpr = lang_text_bpr[lang]
442
+ if bpr > 0:
443
+ estimated_rows = int(lang_text_budget / bpr)
444
+ else:
445
+ estimated_rows = 0
446
+
447
+ floored_rows = max(estimated_rows, min_samples)
448
+ available = lang_row_counts[lang]
449
+
450
+ if floored_rows >= available:
451
+ newly_frozen[lang] = available
452
+
453
+ if not newly_frozen:
454
+ break
455
+
456
+ for lang, rows in newly_frozen.items():
457
+ frozen[lang] = rows
458
+ remaining_budget -= rows * lang_text_bpr[lang]
459
+ del active_proportions[lang]
460
+
461
+ active_total = sum(active_proportions.values())
462
+ if active_total > 0:
463
+ active_proportions = {
464
+ lg: p / active_total for lg, p in active_proportions.items()
465
+ }
466
+ else:
467
+ break
468
+
469
+ log.info(
470
+ f" [{source_name}] Redistribution iter {iteration}: froze "
471
+ f"{len(newly_frozen)} language(s), "
472
+ f"{len(active_proportions)} still active, "
473
+ f"~{remaining_budget / 1e9:.2f} GB budget remaining."
474
+ )
475
+
476
+ target_rows: Dict[str, int] = dict(frozen)
477
+ for lang, prop in active_proportions.items():
478
+ lang_text_budget = remaining_budget * prop
479
+ bpr = lang_text_bpr[lang]
480
+ if bpr > 0:
481
+ estimated_rows = int(lang_text_budget / bpr)
482
+ else:
483
+ estimated_rows = 0
484
+ floored_rows = max(estimated_rows, min_samples)
485
+ capped_rows = min(floored_rows, lang_row_counts[lang])
486
+ target_rows[lang] = capped_rows
487
+
488
+ total_target_text = sum(
489
+ target_rows[lg] * lang_text_bpr[lg] for lg in target_rows
490
+ )
491
+ log.info(
492
+ f"[{source_name}] Allocation complete: "
493
+ f"~{total_target_text / 1e9:.2f} GB text across "
494
+ f"{sum(target_rows.values()):,} rows."
495
+ )
496
+
497
+ log.info(
498
+ f"[{source_name}] Target rows:\n" +
499
+ "\n".join(f" {lg}: {n:,}" for lg, n in sorted(target_rows.items()))
500
+ )
501
+
502
+ # Sample and write
503
+ source_output_dir = self.output_dir / source_name
504
+ source_output_dir.mkdir(parents=True, exist_ok=True)
505
+
506
+ lang_manifest = {}
507
+
508
+ for lang, n_rows in tqdm(target_rows.items(), desc=f"Sampling {source_name}"):
509
+ if is_monolingual:
510
+ out_file = source_output_dir / "data.parquet"
511
+ else:
512
+ out_file = source_output_dir / f"{lang}.parquet"
513
+
514
+ if out_file.exists():
515
+ log.info(f" [{lang}] Output exists, skipping.")
516
+ try:
517
+ existing_rows = count_rows([out_file])
518
+ except Exception as e:
519
+ log.warning(f" [{lang}] Could not count rows in existing file: {e}")
520
+ existing_rows = None
521
+
522
+ lang_manifest[lang] = {
523
+ "status": "skipped",
524
+ "rows_written": existing_rows,
525
+ "rows_available": lang_row_counts[lang],
526
+ "output": str(out_file)
527
+ }
528
+ continue
529
+
530
+ # Derive a per-language seed to avoid identical index sets
531
+ lang_seed = self.seed + hash(lang) % (2**31)
532
+
533
+ written = sample_rows(
534
+ parquet_files=lang_files[lang],
535
+ target_rows=n_rows,
536
+ output_path=out_file,
537
+ seed=lang_seed,
538
+ )
539
+
540
+ lang_manifest[lang] = {
541
+ "status": "ok",
542
+ "rows_written": written,
543
+ "rows_available": lang_row_counts[lang],
544
+ "text_bytes": lang_text_sizes[lang],
545
+ "text_bytes_per_row": lang_text_bpr[lang],
546
+ "output": str(out_file),
547
+ }
548
+ log.info(f" [{lang}] Wrote {written:,} rows → {out_file.name}")
549
+
550
+ return {
551
+ "status": "ok",
552
+ "total_input_text_gb": total_input_text_bytes / 1e9,
553
+ "target_text_gb": target_size_gb,
554
+ "languages": lang_manifest,
555
+ }
556
+
557
+
558
+ # ---------------------------------------------------------------------------
559
+ # CLI
560
+ # ---------------------------------------------------------------------------
561
+
562
+ def main():
563
+ import argparse
564
+
565
+ parser = argparse.ArgumentParser(
566
+ description=(
567
+ "Sample a tokenizer training dataset from multiple corpus sources. "
568
+ "Language proportions are determined from UTF-8 text byte sizes."
569
+ ),
570
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
571
+ )
572
+
573
+ parser.add_argument(
574
+ "config",
575
+ type=str,
576
+ help="Path to JSON configuration file.",
577
+ )
578
+
579
+ args = parser.parse_args()
580
+
581
+ config_path = Path(args.config)
582
+ if not config_path.exists():
583
+ log.error(f"Config file not found: {config_path}")
584
+ return
585
+
586
+ sampler = TokenizerSampler(config_path)
587
+ sampler.run()
588
+
589
+
590
+ if __name__ == "__main__":
591
+ main()