chugr 0.2.0.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. chugr-0.2.0.dev0/LICENSE +201 -0
  2. chugr-0.2.0.dev0/PKG-INFO +436 -0
  3. chugr-0.2.0.dev0/README.md +399 -0
  4. chugr-0.2.0.dev0/pyproject.toml +68 -0
  5. chugr-0.2.0.dev0/src/chugr/__init__.py +46 -0
  6. chugr-0.2.0.dev0/src/chugr/app/test.py +105 -0
  7. chugr-0.2.0.dev0/src/chugr/common/__init__.py +9 -0
  8. chugr-0.2.0.dev0/src/chugr/common/cli.py +234 -0
  9. chugr-0.2.0.dev0/src/chugr/common/collate.py +104 -0
  10. chugr-0.2.0.dev0/src/chugr/common/config.py +335 -0
  11. chugr-0.2.0.dev0/src/chugr/common/random.py +76 -0
  12. chugr-0.2.0.dev0/src/chugr/common/serialize.py +150 -0
  13. chugr-0.2.0.dev0/src/chugr/common/task_config.py +24 -0
  14. chugr-0.2.0.dev0/src/chugr/common/types.py +122 -0
  15. chugr-0.2.0.dev0/src/chugr/common/urls.py +88 -0
  16. chugr-0.2.0.dev0/src/chugr/doc/__init__.py +17 -0
  17. chugr-0.2.0.dev0/src/chugr/doc/constants.py +15 -0
  18. chugr-0.2.0.dev0/src/chugr/doc/doc_processor.py +248 -0
  19. chugr-0.2.0.dev0/src/chugr/doc/doc_read_processor.py +249 -0
  20. chugr-0.2.0.dev0/src/chugr/doc/doc_vqa_processor.py +113 -0
  21. chugr-0.2.0.dev0/src/chugr/doc/synth_text.py +212 -0
  22. chugr-0.2.0.dev0/src/chugr/hfds/__init__.py +2 -0
  23. chugr-0.2.0.dev0/src/chugr/hfds/collate.py +83 -0
  24. chugr-0.2.0.dev0/src/chugr/hfds/loader.py +385 -0
  25. chugr-0.2.0.dev0/src/chugr/hfds/wrappers.py +108 -0
  26. chugr-0.2.0.dev0/src/chugr/image/__init__.py +4 -0
  27. chugr-0.2.0.dev0/src/chugr/image/build_transforms_doc.py +427 -0
  28. chugr-0.2.0.dev0/src/chugr/image/build_transforms_image.py +203 -0
  29. chugr-0.2.0.dev0/src/chugr/image/transforms_alb.py +112 -0
  30. chugr-0.2.0.dev0/src/chugr/image/transforms_factory.py +58 -0
  31. chugr-0.2.0.dev0/src/chugr/image/transforms_torch.py +137 -0
  32. chugr-0.2.0.dev0/src/chugr/loader.py +249 -0
  33. chugr-0.2.0.dev0/src/chugr/naflex.py +357 -0
  34. chugr-0.2.0.dev0/src/chugr/task_pipeline/__init__.py +7 -0
  35. chugr-0.2.0.dev0/src/chugr/task_pipeline/pipeline_doc_read.py +66 -0
  36. chugr-0.2.0.dev0/src/chugr/task_pipeline/pipeline_doc_vqa.py +124 -0
  37. chugr-0.2.0.dev0/src/chugr/task_pipeline/pipeline_factory.py +32 -0
  38. chugr-0.2.0.dev0/src/chugr/task_pipeline/pipeline_gtparse.py +93 -0
  39. chugr-0.2.0.dev0/src/chugr/task_pipeline/pipeline_image_text.py +90 -0
  40. chugr-0.2.0.dev0/src/chugr/task_pipeline/pipeline_manual.py +27 -0
  41. chugr-0.2.0.dev0/src/chugr/text/__init__.py +1 -0
  42. chugr-0.2.0.dev0/src/chugr/text/tokenization.py +222 -0
  43. chugr-0.2.0.dev0/src/chugr/version.py +1 -0
  44. chugr-0.2.0.dev0/src/chugr/wds/__init__.py +7 -0
  45. chugr-0.2.0.dev0/src/chugr/wds/dataset_info.py +65 -0
  46. chugr-0.2.0.dev0/src/chugr/wds/decode.py +319 -0
  47. chugr-0.2.0.dev0/src/chugr/wds/filters.py +142 -0
  48. chugr-0.2.0.dev0/src/chugr/wds/helpers.py +68 -0
  49. chugr-0.2.0.dev0/src/chugr/wds/loader.py +187 -0
  50. chugr-0.2.0.dev0/src/chugr/wds/pipeline.py +182 -0
  51. chugr-0.2.0.dev0/src/chugr/wds/shardlists.py +134 -0
  52. chugr-0.2.0.dev0/src/chugr/wds/tariterators.py +70 -0
  53. chugr-0.2.0.dev0/tests/test_common.py +124 -0
  54. chugr-0.2.0.dev0/tests/test_hfds.py +42 -0
  55. chugr-0.2.0.dev0/tests/test_naflex.py +228 -0
  56. chugr-0.2.0.dev0/tests/test_synth.py +61 -0
  57. chugr-0.2.0.dev0/tests/test_transforms.py +32 -0
  58. chugr-0.2.0.dev0/tests/test_wds_loader.py +73 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Hugging Face Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,436 @@
1
+ Metadata-Version: 2.4
2
+ Name: chugr
3
+ Version: 0.2.0.dev0
4
+ Summary: Data pipelines for document and image-text training: webdataset and Hugging Face datasets, PDF decoding, NaFlex batching
5
+ Keywords: webdataset,datasets,data-loading,documents,pdf,pytorch
6
+ Author-Email: Ross Wightman <rwightman@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Education
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Project-URL: homepage, https://github.com/rwightman/chugr
18
+ Project-URL: repository, https://github.com/rwightman/chugr
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: webdataset
21
+ Requires-Dist: braceexpand
22
+ Requires-Dist: datasets
23
+ Requires-Dist: timm
24
+ Requires-Dist: torch
25
+ Requires-Dist: torchvision
26
+ Requires-Dist: numpy
27
+ Requires-Dist: pillow
28
+ Requires-Dist: pyyaml
29
+ Requires-Dist: pypdfium2
30
+ Provides-Extra: alb
31
+ Requires-Dist: albumentations; extra == "alb"
32
+ Requires-Dist: opencv-python-headless; extra == "alb"
33
+ Provides-Extra: text
34
+ Requires-Dist: transformers; extra == "text"
35
+ Requires-Dist: fonttools; extra == "text"
36
+ Description-Content-Type: text/markdown
37
+
38
+ # Chugging Data (`chugr`)
39
+
40
+ Data pipelines for training multi-modal models on documents and image + text pairs, built on
41
+ [`webdataset`](https://github.com/webdataset/webdataset) and Hugging Face [`datasets`](https://github.com/huggingface/datasets).
42
+
43
+ * `webdataset` tar shards for scalable (streamed, sharded) pretraining, Hugging Face `datasets` (map-style or streaming)
44
+ for exploration, validation and fine-tuning, behind one config driven `create_loader()`
45
+ * On the fly PDF decoding and rendering, so large collections of native `.pdf` files can be streamed w/o pre-rendering
46
+ pages to `.png` / `.tiff`. The PDF decoder works at the webdataset level and can be plugged into other pipelines
47
+ * Document image transforms (incl. an `albumentations` port of the `nougat` augmentations) and NaFlex (native aspect,
48
+ variable resolution) patch sequence transforms
49
+ * NaFlex batching: per batch sequence lengths sized to a token budget, w/ a rank-identical schedule. This padded,
50
+ per sample scheme is the focus for variable aspect / size images, not NaViT style multi-image sequence packing
51
+ * Task pipelines for document reading (OCR targets), document VQA and image-text, w/ tokenization and prompt handling
52
+ * Interval based training: fixed sample counts per interval, the same number of batches on every rank, shard lists that
53
+ repeat (reshuffled per pass) or are resampled, distributed eval w/o padded or repeated samples
54
+
55
+ `chugr` is the continuation of the original `chug` library (huggingface/chug), renamed and revived. It provides the
56
+ data pipelines for [`pixr`](https://github.com/rwightman/pixr).
57
+
58
+ ## Installation
59
+
60
+ ```bash
61
+ pip install --pre chugr
62
+ # optional extras: albumentations based transforms (doc_nougat), HF tokenizers by name + synthetic text font checks
63
+ pip install --pre "chugr[alb,text]"
64
+ ```
65
+
66
+ PDF rendering uses [pypdfium2](https://github.com/pypdfium2-team/pypdfium2) by default.
67
+ [fitz / PyMuPDF](https://github.com/pymupdf/PyMuPDF) can be used instead if your use case is okay with its AGPL-3.0
68
+ license, it must be installed separately and enabled w/ `CHUGR_USE_AGPL_PYMUPDF=1`.
69
+
70
+ ## Status
71
+
72
+ Alpha. Major features work and have been used for document reading pretraining and DocVQA fine-tuning, expect breaking
73
+ changes. `pip install --pre chugr` installs the current dev version.
74
+
75
+ ### Changes since `chug`
76
+ * `simple_parsing` dependency replaced by a minimal `Serializable` mixin and nested dataclass CLI parser (`chugr.common.parse_args`)
77
+ * NaFlex (native aspect, variable resolution) document transforms (`doc_naflex`) producing patch sequences + coords, padded by `chugr.common.collate`
78
+ * Fixes for `doc_basic` / `doc_better` train transforms, albumentations 2.x support for `doc_nougat`
79
+ * HF datasets loader: shuffled & sharded `IntervalSampler` for training (w/ intervals shorter than an epoch), split slicing (`train[:1000]`)
80
+ * `python -m chugr.app.test` to benchmark loaders and dump (reassembled) samples
81
+ * NaFlex batching (`chugr.naflex`, adapted from OpenCLIP's streaming NaFlex loader): a rank-identical schedule of
82
+ `(seq_len, batch_size)` per batch drawn from `naflex_seq_lens` / `naflex_seq_len_probs` and sized to a token budget
83
+ (`naflex_max_tokens`, w/ optional per row `naflex_text_tokens` cost), samples are resized to each batch's patch
84
+ budget. `length_bucketing` pool sorts samples by target text length. `mean_batch_size` is exposed on the loader for
85
+ loss scaling.
86
+ * Webdataset shard lists repeat (reshuffled per pass) instead of requiring `resampled`, so fixed sample count
87
+ intervals and NaFlex batching work w/o sampling shards w/ replacement
88
+ * NaFlex batching for HF datasets. Map-style (`format hfds`, `NaFlexMapDataset` adapted from OpenCLIP's
89
+ `NaFlexMapDatasetWrapper`): the same schedule over rank sharded shuffled indices that continue through the dataset
90
+ across intervals, failed samples are replaced. Streaming (`hfids`): `NaFlexBatcher` over the repeating stream.
91
+ * Streaming HF datasets yield a fixed number of train batches per worker (the stream wraps around), so every rank
92
+ sees the same number of batches per interval, as the webdataset loader. `num_workers` is limited to the number of
93
+ data shards (files) per rank. The dataset epoch (shard / shuffle seed) is set from the main process only.
94
+ * Ranks are split w/ the explicit `DistributedCfg` rank / world size (no reliance on `RANK` / `WORLD_SIZE` env vars
95
+ in dataloader workers), per rank seeds are spaced by a large stride (`chugr.common.rank_seed`) so runs w/ nearby
96
+ seeds don't share streams.
97
+ * Eval splits are exact: map-style HF datasets are split across ranks w/o padding or repeated samples (uneven per rank
98
+ counts), uncapped streaming eval reads every sample once.
99
+ * Webdataset eval: `num_samples` below the dataset size caps the eval set to exactly the first `num_samples` samples
100
+ for any number of ranks / workers (every worker reads that head of the stream, keep it small). W/o a cap all
101
+ samples are used, split by shard if there are at least `ranks * workers` shards, otherwise by sample.
102
+ * Text preprocessing w/ a `prompt_end_token`: an over-long prompt (question) is shortened so the prompt end token
103
+ and target (answer) still fit in `max_length`.
104
+
105
+ ## Roadmap
106
+
107
+ ### Nearish
108
+ * Cleanup and refinement, codebase will change
109
+ * Documentation & unit-tests
110
+ * Support reading of info .json/.yaml files for automatic shard info resolution for webdatasets (like timm)
111
+
112
+ ### Mediumish
113
+ * Option to output bbox annotations for lines (or word + word output) for tasks that leverage layout
114
+ * Unified preprocessor functions for combined image + text tokenization (img+text token interleaving, etc.)
115
+
116
+ ### Longish
117
+ * Increase range of task pipelines for other tasks, modelling needs
118
+ * Support additional modalities & targets (video, audio, detection/dense pixel targets, image/video/audio targets)
119
+ * Explore alternatives to .tar shards (array_record, arrow, etc)
120
+
121
+ ## Design
122
+
123
+ ### Submodule Hierarchy
124
+
125
+ The library has been designed so that functions, classes at different levels can be used independently.
126
+
127
+ If one wants to build a loader & pipeline with JSON/YAML serializable configs, use the top-level `chugr.create_loader()` in `chugr/loader.py`. Depending on dataset sources, one can easily switch this between webdataset, HF datasets (in the future, other sources).
128
+
129
+ Bypassing the highest level, one can also call `build_pipeline_*` methods in `task_pipeline` and then call `create_loader_wds` with a full array of args for `wds` only use cases.
130
+
131
+ If one doesn't want to use `chugr` loaders and pipelines at all, `image`, `text`, and `wds` (especially decoder) functionality may be useful in other projects.
132
+
133
+ #### Library modules (highest to lowest level)
134
+
135
+ The dependencies of modules within the library are intended to follow the hierarchy below. e.g. doc depends on wds, but wds should never depend on doc.
136
+
137
+ ```
138
+ app
139
+ |
140
+ loader (chugr/loader.py)
141
+ |
142
+ task_pipeline
143
+ |
144
+ doc
145
+ |
146
+ wds, hfds, image, text
147
+ |
148
+ common
149
+ ```
150
+
151
+ ### Submodules
152
+
153
+ #### `common`
154
+
155
+ Configs, structures (dataclasses) for general use across the library
156
+
157
+ #### `wds`
158
+
159
+ Webdataset (`wds` for short) specific code. Extensions and alterations of webdataset functionality to fit covered use case and improve robustness.
160
+
161
+ All data pipelines in `chugr` currently leverage `wds` pipelines, even when not using `wds` datasets.
162
+
163
+ Document oriented decoding (pdf decoder) is present in `chugr/wds/decode.py`, it can be used with any webdataset pipeline as a decoder. e.g. `wds.decode(chugr.wds.DecodeDoc('pill'), 'pill')`
164
+
165
+ #### `hfds`
166
+
167
+ Hugging Face `datasets` support. A minimal wrapper that allows `datasets` to be used with chugr processing pipelines.
168
+
169
+ The processing pipelines remain webdataset based when using `datasets`, they are invoked by a custom collate class.
170
+
171
+ #### `image`
172
+
173
+ Image processing, `torchvision` and `albumentations` based transform building code. A mix of generic image (imagenet, simclr) transforms and document specific transforms, including an implementation of `albumentations` based `nougat` transforms.
174
+
175
+ #### `text`
176
+
177
+ Text processing, tokenization code.
178
+
179
+ #### `doc`
180
+
181
+ Document processing code. Currently focused on processors that apply image/pdf decoders and process document OCR or VQA annotations.
182
+
183
+ #### `task_pipeline`
184
+
185
+ Task specific pipelines, where dataset formats meet modelling needs.
186
+
187
+ Inputs to task pipelines are sample dictionaries based on the dataset form, they are decoded and then processed into outputs that match model input requirements.
188
+
189
+ Task specific pipelines that handle the data <--> model input interface are inserted into an encompassing data pipeline which handles shard lists, shuffle, wrapping, distributed worker, splitting, batching, etc.
190
+
191
+ #### `naflex`
192
+
193
+ NaFlex (variable sequence length) batching helpers: `NaFlexBatchScheduler` (rank-identical seq len / batch size
194
+ schedule from a token budget), `NaFlexBatcher` (per seq len processors + batching of a sample stream),
195
+ `NaFlexMapDataset` (the same over a map-style dataset), `LengthBucketer`.
196
+
197
+ #### `chugr.loader`
198
+
199
+ This lone top-level file includes the main factory methods for creating loaders w/ associated pipelines from config dataclasses.
200
+
201
+ #### `app`
202
+
203
+ Most applications using `chugr` will exist outside of the lib in training libraries, etc. Some builtin utility / exploration apps will be included here.
204
+
205
+ ## Datasets
206
+
207
+ Datasets that work well with this library can be found on the Hugging Face Hub under the `pixparse` organization (https://huggingface.co/pixparse).
208
+
209
+ We'll add links to other noteworthy datasets that can be used as we become aware of them.
210
+
211
+
212
+ ## Usage / Examples
213
+
214
+ ### Document Reading, Training w/ IDL
215
+ ```python
216
+ import chugr
217
+ img_cfg = chugr.ImageInputCfg(size=(1024, 768), transform_type='doc_better')
218
+ img_fn = chugr.create_image_preprocessor(input_cfg=img_cfg, is_training=True)
219
+ txt_fn = chugr.create_text_preprocessor(
220
+ 'naver-clova-ix/donut-base',
221
+ prompt_end_token='<s_idl>',
222
+ task_start_token='<s_idl>', # NOTE needs to be added to tokenizer
223
+ )
224
+
225
+ task_cfg = chugr.DataTaskDocReadCfg(
226
+ image_process_fn=img_fn,
227
+ text_process_fn=txt_fn,
228
+ page_sampling='random',
229
+ error_handler='dump_and_reraise',
230
+ )
231
+ data_cfg = chugr.DataCfg(
232
+ source='pipe:curl -s -f -L https://huggingface.co/datasets/pixparse/idl-wds/resolve/main/idl-train-0{0000..2999}.tar',
233
+ batch_size=8,
234
+ num_samples=3144726,
235
+ format='wds',
236
+ )
237
+ lb = chugr.create_loader(
238
+ data_cfg,
239
+ task_cfg,
240
+ is_training=True,
241
+ )
242
+ ii = iter(lb)
243
+ sample = next(ii)
244
+ ```
245
+
246
+ ### Document Reading, Exploring IDL
247
+ ```python
248
+ import chugr
249
+ task_cfg = chugr.DataTaskDocReadCfg(page_sampling='all')
250
+ data_cfg = chugr.DataCfg(
251
+ source='pixparse/idl-wds',
252
+ split='train',
253
+ batch_size=None,
254
+ format='hfids',
255
+ num_workers=0,
256
+ )
257
+ lb = chugr.create_loader(
258
+ data_cfg,
259
+ task_cfg,
260
+ )
261
+ ii = iter(lb)
262
+ sample = next(ii)
263
+ ```
264
+
265
+ ### Document Reading, Training with PDFA
266
+
267
+ ```python
268
+ import chugr
269
+ img_cfg = chugr.ImageInputCfg(size=(1024, 768), transform_type='doc_nougat')
270
+ img_fn = chugr.create_image_preprocessor(input_cfg=img_cfg, is_training=True)
271
+ txt_fn = chugr.create_text_preprocessor(
272
+ 'naver-clova-ix/donut-base',
273
+ prompt_end_token='<s_pdfa>',
274
+ task_start_token='<s_pdfa>', # NOTE needs to be added to tokenizer
275
+ )
276
+
277
+ task_cfg = chugr.DataTaskDocReadCfg(
278
+ image_process_fn=img_fn,
279
+ text_process_fn=txt_fn,
280
+ page_sampling='random',
281
+ )
282
+ data_cfg = chugr.DataCfg(
283
+ source='pipe:curl -s -f -L https://huggingface.co/datasets/pixparse/pdfa-english-train/resolve/main/pdfa-eng-train-{000000..005000}.tar',
284
+ batch_size=8,
285
+ num_samples=1000000, # FIXME replace with actual
286
+ format='wds',
287
+ )
288
+ lb = chugr.create_loader(
289
+ data_cfg,
290
+ task_cfg,
291
+ is_training=True,
292
+ )
293
+ ii = iter(lb)
294
+ sample = next(ii)
295
+ ```
296
+
297
+ ### Document Reading, Exploring PDFA
298
+
299
+ ```python
300
+ import chugr
301
+
302
+ task_cfg = chugr.DataTaskDocReadCfg(
303
+ page_sampling='all',
304
+ )
305
+ data_cfg = chugr.DataCfg(
306
+ source='pixparse/pdfa-eng-wds',
307
+ split='train',
308
+ batch_size=None,
309
+ format='hfids',
310
+ num_workers=0,
311
+ )
312
+ lb = chugr.create_loader(
313
+ data_cfg,
314
+ task_cfg,
315
+ )
316
+ ii = iter(lb)
317
+ sample = next(ii)
318
+ ```
319
+
320
+
321
+ ### NaFlex (variable resolution) document input
322
+
323
+ ```python
324
+ import chugr
325
+ from PIL import Image
326
+
327
+ # pages keep their aspect ratio, resized to fit a patch budget (max_seq_len patches of patch_size x patch_size)
328
+ img_cfg = chugr.ImageInputCfg(transform_type='doc_naflex', patch_size=16, max_seq_len=1024)
329
+ img_fn = chugr.create_image_preprocessor(input_cfg=img_cfg, is_training=True)
330
+ out = img_fn(Image.new('L', (850, 1100), 255))
331
+ # {'patches': [N, 256], 'patch_coord': [N, 2] (y, x), 'patch_valid': [N] bool}, N <= max_seq_len
332
+ ```
333
+
334
+ For batches w/ a sequence length (patch budget) drawn per batch and the batch size set by a token budget, set
335
+ `naflex_seq_lens`, `naflex_seq_len_probs` and `naflex_max_tokens` in `DataCfg` (webdataset, map-style or streaming
336
+ HF datasets).
337
+
338
+ ### Image + Text
339
+
340
+ #### Training
341
+
342
+ ```python
343
+ import chugr
344
+ import transformers
345
+ from functools import partial
346
+ img_cfg = chugr.ImageInputCfg(size=(512, 512), transform_type='image_timm')
347
+ img_fn = chugr.create_image_preprocessor(input_cfg=img_cfg, is_training=True)
348
+ tokenizer = transformers.AutoTokenizer.from_pretrained('laion/CLIP-ViT-H-14-laion2B-s32B-b79K')
349
+ txt_fn = partial(chugr.tokenize, max_length=1000, tokenizer=tokenizer)
350
+ task_cfg = chugr.DataTaskImageTextCfg(
351
+ image_process_fn=img_fn,
352
+ text_process_fn=txt_fn,
353
+ )
354
+ data_cfg = chugr.DataCfg(
355
+ source='pipe:curl -s -f -L https://huggingface.co/datasets/pixparse/cc12m-wds/resolve/main/cc12m-train-{0000..2175}.tar',
356
+ batch_size=8,
357
+ num_samples=10968539,
358
+ format='wds',
359
+ )
360
+ lb = chugr.create_loader(
361
+ data_cfg,
362
+ task_cfg,
363
+ is_training=True,
364
+ )
365
+ ii = iter(lb)
366
+ sample = next(ii)
367
+ ```
368
+
369
+ ### Document VQA
370
+
371
+ #### Training, Fine-tuning
372
+ ```python
373
+ import chugr
374
+ img_cfg = chugr.ImageInputCfg(size=(1024, 768), transform_type='doc_basic')
375
+ img_fn = chugr.create_image_preprocessor(img_cfg, is_training=True)
376
+ txt_fn = chugr.create_text_preprocessor(
377
+ 'naver-clova-ix/donut-base-finetuned-docvqa',
378
+ prompt_end_token='<s_answer>',
379
+ task_start_token='<s_docvqa>',
380
+ )
381
+
382
+ task_cfg = chugr.DataTaskDocVqaCfg(
383
+ image_process_fn=img_fn,
384
+ text_process_fn=txt_fn,
385
+ )
386
+ data_cfg = chugr.DataCfg(
387
+ source='pipe:curl -s -f -L https://huggingface.co/datasets/pixparse/docvqa-wds/resolve/main/docvqa-train-{000..383}.tar',
388
+ batch_size=8,
389
+ format='wds',
390
+ num_samples=39463,
391
+ )
392
+ lb = chugr.create_loader(
393
+ data_cfg,
394
+ task_cfg,
395
+ is_training=True,
396
+ )
397
+ ii = iter(lb)
398
+ sample = next(ii)
399
+ ```
400
+
401
+ #### Exploration
402
+
403
+ ```python
404
+ import chugr
405
+ task_cfg = chugr.DataTaskDocVqaCfg(
406
+ question_prefix='Question: ',
407
+ question_suffix='',
408
+ answer_prefix='Answer: ',
409
+ answer_suffix=''
410
+ )
411
+ data_cfg = chugr.DataCfg(
412
+ source='pixparse/docvqa-single-page-questions',
413
+ split='validation',
414
+ batch_size=None,
415
+ format='hfids',
416
+ num_workers=0,
417
+ )
418
+ lb = chugr.create_loader(
419
+ data_cfg,
420
+ task_cfg
421
+ )
422
+ ii = iter(lb)
423
+ sample = next(ii)
424
+ ```
425
+
426
+ ## Acknowledgement
427
+
428
+ `chugr` evolved from the `webdataset` datapipeline used successfully in the [OpenCLIP](https://github.com/mlfoundations/open_clip) project. Thanks to all the contributors in that project. Future work will likely involve closing the loop and leveraging `chugr` in OpenCLIP for increased capability.
429
+
430
+ The image/document augmentations in `chugr` rely on a number of external influences. Our document oriented `doc_better` torchvision augmentations are influenced by `nougat`, and the `doc_nougat` is a direct adaptation of the [`albumentations`](https://albumentations.ai/) + `cv2` document pipeline in [`nougat`](https://github.com/facebookresearch/nougat). Several image augmentations leverage existing work in the `timm` library.
431
+
432
+ Also, big thanks to the maintainers of [`webdataset`](https://github.com/webdataset/webdataset) and Hugging Face [`datasets`](https://github.com/huggingface/datasets).
433
+
434
+ ## License
435
+
436
+ Apache 2.0, see [LICENSE](LICENSE). The optional PyMuPDF backend is AGPL-3.0 licensed (see above).