batchscope 0.1.0__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.
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anish Pentyala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,299 @@
1
+ Metadata-Version: 2.4
2
+ Name: batchscope
3
+ Version: 0.1.0
4
+ Summary: Inspect exact finite sample coverage under explicitly declared loading plans
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # batchscope
12
+
13
+ Inspect a finite data-loading plan before starting a training or evaluation run.
14
+ Supply an ordered list of unique sample IDs, explicit partition rules, batch size
15
+ and tail policies. See which identities would repeat or disappear under that
16
+ model, and how many local batches each rank would produce.
17
+
18
+ This is an experimental tool. It has no observed users. It does not
19
+ inspect or run a real DataLoader, read sample contents, launch training, or prove
20
+ that a configured training job follows this plan.
21
+
22
+ ## A small but consequential tail
23
+
24
+ Five samples split across two ranks need six sampler slots when padding is on.
25
+ Then a loader that drops incomplete local batches can remove two occurrences,
26
+ including the extra padding. Counting padding alone misses the final coverage.
27
+
28
+ ```sh
29
+ python -m pip install .
30
+ batchscope examples/padded.json
31
+ ```
32
+
33
+ That example emits six occurrences of five identities, so it exits 1 with
34
+ `COVERAGE_CHANGED`. Change `loader_drop_last` to `true` and it emits four
35
+ identities once, omitting the fifth. This is invented input, not a measured job.
36
+
37
+ ## Explicit models
38
+
39
+ | mode | ownership before batching | tail policy |
40
+ | --- | --- | --- |
41
+ | `distributed_map` | pad/truncate the supplied global order to a rank multiple, then stride by rank | loader tail is per rank; workers do not repartition sampler indices |
42
+ | `iterable_strided` | rank-major combined consumer index `rank * workers + worker`, stride by `ranks * workers` | one tail per rank/worker |
43
+ | `iterable_replicated` | every rank/worker sees the entire ordered universe | one tail per rank/worker |
44
+
45
+ `workers` means the number of independently iterated sources per rank. Use 1 for
46
+ single-process iterable loading. It is not a literal translation of PyTorch's
47
+ `num_workers=0`. Map-style worker count does not multiply or repartition samples.
48
+
49
+ These are declared mathematical models. The map model follows the documented
50
+ unshuffled `DistributedSampler` padding/truncation rule and ordinary local
51
+ batching. The iterable rules describe two explicitly chosen source strategies,
52
+ not arbitrary PyTorch iterable datasets. A different worker ordering or nested
53
+ sharding can produce different identities. Supply the actual intended order.
54
+
55
+ No RNG or shuffle emulation, custom sampler, dynamic filtering, resampling,
56
+ variable batch sizes, accumulation, retries, early exit, persistent-worker state,
57
+ resume state, sample packing, or automatic framework-config parsing. Do not use
58
+ these counts as evidence of optimizer updates or synchronized collective calls.
59
+
60
+ ## Input
61
+
62
+ ```json
63
+ {
64
+ "ids": ["a", "b", "c", "d", "e"],
65
+ "mode": "distributed_map",
66
+ "ranks": 2,
67
+ "workers": 1,
68
+ "batch_size": 2,
69
+ "sampler_drop_last": false,
70
+ "loader_drop_last": false
71
+ }
72
+ ```
73
+
74
+ All fields shown are required for `distributed_map`. The other modes require all
75
+ except `sampler_drop_last`, which is rejected rather than silently ignored.
76
+ IDs are nonempty unique strings. Distinct IDs can contain identical sample
77
+ contents; this tool cannot detect that. No whitespace or Unicode normalization.
78
+ Unknown fields, duplicate JSON members, NaN/Infinity, invalid UTF-8, nonregular
79
+ input files and plans over 8 MiB are rejected. Limits: 100,000 IDs, 1,024 combined
80
+ consumers, 1,000,000 assigned occurrences. These are admission limits, not a hard
81
+ RAM/time guarantee. A regular file on a slow filesystem can still block.
82
+
83
+ ## Selected identity witnesses
84
+
85
+ Add optional `"trace_ids": ["a", "e"]` to the input to locate selected IDs within
86
+ this finite model. Select at most 64 distinct IDs from the declared universe.
87
+ The report adds `traces`, in selection order. Each trace contains the ID,
88
+ `sampler_removed` (0 or 1), and a rank/worker-ordered `consumers` list containing
89
+ only consumers assigned that ID. Each consumer has `assigned`, `emitted`, and
90
+ `loader_dropped` occurrence counts. Map-style consumers have `worker: null`;
91
+ map workers do not define independent sample ownership here.
92
+
93
+ For the example above, tracing `a` shows one assigned occurrence on each rank.
94
+ With `loader_drop_last: true`, rank 0 retains its occurrence and rank 1 drops its
95
+ occurrence. An ID removed by global sampler truncation has `sampler_removed: 1`
96
+ and an empty consumer list. An empty selection emits `traces: []`; omitting
97
+ `trace_ids` preserves the original report shape. Traces describe declared
98
+ ownership and tail arithmetic, not arrival order, observed consumption, or
99
+ whether identical contents occur under other IDs. Reports still disclose IDs.
100
+
101
+ ## Audit explicit observed receipts
102
+
103
+ ```sh
104
+ batchscope --receipts plan.json receipts.json
105
+ ```
106
+
107
+ Receipts are a JSON array of individual retained occurrences, for example
108
+ `[{"id": "a", "rank": 0, "worker": null}]`. Each object requires exactly these
109
+ three fields. Record at the boundary you intend to audit, and supply a complete
110
+ list for the declared finite run. Nothing here records or authenticates events.
111
+ Repeated entries are separate occurrences, not deduplicated records. Unknown
112
+ nonempty IDs are reported as unexpected evidence, not silently discarded.
113
+ Rank must exist in the plan. Iterable worker must exist too. Map worker must be
114
+ `null`, because this model does not predict map-worker identity ownership.
115
+
116
+ The `batchscope-receipts-v1` report compares occurrence counts per exact
117
+ `(id, rank, worker)` key. It reports every differing key, missing and extra
118
+ occurrences separately, and the number of unknown-ID occurrences (a subset of
119
+ extras). A consumer swap therefore produces a missing and an extra occurrence
120
+ even when global totals match. Known rows follow plan ID order and then consumer
121
+ order; unknown IDs follow first-observed ID order. Arrival order is not checked.
122
+ The full baseline coverage status and warnings remain visible as separate fields.
123
+
124
+ Exit 0 means `MATCHED_RECEIPTS`, exit 1 means `RECEIPT_MISMATCH`, and exit 2 means
125
+ invalid input or failed output delivery. Matching receipts does **not** mean
126
+ exactly-once coverage: they can match a plan that deliberately duplicates or
127
+ omits IDs, or an empty plan. It also cannot establish receipt completeness,
128
+ provenance, real consumption, sample contents, batch boundaries, execution order,
129
+ optimizer updates or synchronized collective calls. An incomplete receipt export
130
+ will look like missing occurrences. Use the retained evidence and its collection
131
+ boundary to interpret a mismatch, not as a diagnosis of its cause.
132
+
133
+ The receipt file uses the same strict JSON and 8 MiB file limits as a plan, and
134
+ at most 1,000,000 occurrence objects. IDs use the plan's 256-character limit.
135
+ Receipts may disclose sensitive IDs. The API is `audit_receipts(plan, receipts)`;
136
+ inputs are not mutated. Single-plan and comparison outputs are unchanged.
137
+
138
+ ## Check order within each modeled consumer
139
+
140
+ ```sh
141
+ batchscope --ordered-receipts plan.json receipts.json
142
+ ```
143
+
144
+ This opt-in mode uses the same strict receipt contract and count differences as
145
+ `--receipts`, then also checks the order of IDs within each modeled consumer.
146
+ The API is `audit_receipts(plan, receipts, check_order=True)`. The default API
147
+ and `--receipts` reports retain their original shape and count-only semantics.
148
+
149
+ Input array order must reflect the collection boundary's order for each consumer.
150
+ Events from different consumers may interleave freely. Map consumers are ranks
151
+ with `worker: null`; iterable consumers are rank/worker pairs. This does not
152
+ compare a global arrival order, infer PyTorch's worker scheduling, or reconstruct
153
+ batches. Do not use this option on an unordered log export or a loader configured
154
+ to return items in a different order from the declared model.
155
+
156
+ The report uses `batchscope-ordered-receipts-v1`. `order_differences` lists each
157
+ mismatched consumer in rank/worker order, its expected and observed lengths, and
158
+ its first differing zero-based local index with `expected_id` and `observed_id`.
159
+ A missing suffix has `observed_id: null`; an extra suffix has `expected_id: null`.
160
+ Only the first local divergence is reported. These are positional witnesses,
161
+ not an edit script, causal diagnosis, or alignment after an insertion/deletion.
162
+ Repeated occurrences of the same ID are indistinguishable. It cannot detect a
163
+ swap between equal IDs or different sample contents carrying the same ID.
164
+
165
+ Exit 0 is `MATCHED_ORDERED_RECEIPTS`; exit 1 is `ORDERED_RECEIPT_MISMATCH`; exit 2
166
+ is invalid input or failed delivery. As with count-only audits, a match may agree
167
+ with a duplicating, incomplete or empty plan. The evidence remains conditional
168
+ on complete, correctly labeled receipts, not authenticated runtime consumption,
169
+ exactly-once coverage, batch boundaries or training behavior.
170
+
171
+ ## Compare two explicit plans
172
+
173
+ ```sh
174
+ batchscope --compare before.json after.json
175
+ ```
176
+
177
+ Both inputs use the same validation and file limits as a single plan. They must
178
+ declare the same unique ID universe, but may reorder it or change any explicit
179
+ loading rule. No union, intersection, coercion or implicit ID alignment is used.
180
+ Rows align by exact ID and are reported in the before plan's order.
181
+
182
+ The `batchscope-comparison-v1` report contains before/after coverage statuses,
183
+ aggregate before/after counts and signed deltas (after minus before), per-rank
184
+ batch counts, and every ID whose assigned/emitted/loader-dropped/sampler-removed
185
+ accounting changes. Added or removed ranks use `null` for the absent side and
186
+ its delta, rather than pretending an absent rank had zero batches. Separate
187
+ `emitted_gain_occurrences` and `emitted_loss_occurrences` prevent equal aggregate
188
+ counts from concealing identity swaps. Changing input order can change which
189
+ IDs survive tails even when emitted totals and batch counts stay the same.
190
+
191
+ Comparison exits 0 for `SAME_ACCOUNTING`, 1 for `CHANGED_ACCOUNTING`, and 2 for
192
+ invalid inputs or failed output delivery. A model change, consumer-count change
193
+ or warning change counts as changed accounting too. `input_order_changed`
194
+ reports reordering separately; unchanged accounting is **not** a claim of equal
195
+ order, per-consumer identity ownership, statistical equivalence, synchronization
196
+ or actual consumption. In particular, two identically incomplete/duplicating
197
+ plans can return `SAME_ACCOUNTING`; inspect both embedded coverage statuses.
198
+ Optional trace selections do not affect comparison. Full single-plan reports
199
+ remain available separately; this comparison does not embed their trace rows.
200
+
201
+ Python API: `from batchscope import compare_plans`, then
202
+ `compare_plans(before_dict, after_dict)`. Inputs are not modified. All counts and
203
+ IDs describe declared finite models only. Comparisons are source-only and are
204
+ not part of any published package release.
205
+
206
+ ## Report and exits
207
+
208
+ Every declared ID has assigned, emitted and loader-dropped multiplicities, plus
209
+ whether global sampler truncation removed it. Each consumer reports counts,
210
+ batches and final batch size; per-rank batches sum that rank's worker batches.
211
+
212
+ - 0: `EXACTLY_ONCE` under the supplied finite model.
213
+ - 1: `COVERAGE_CHANGED` or `EMPTY_UNIVERSE`. Review the counts.
214
+ - 2: invalid input, usage or output delivery failure. No usable complete report.
215
+
216
+ The full report must be written and flushed before exit 0 or 1. A broken output
217
+ may retain a JSON prefix, so use a report only with successful delivery and its
218
+ expected exit status. Redirecting stdout is not an atomic output transaction. A short `write` return
219
+ or a failed flush is an output failure too, even if no exception was raised by
220
+ `write`. The callable `batchscope.__main__.main()` returns 2 without replacing
221
+ or closing caller-owned stdout. The module and installed console use a separate
222
+ process entrypoint to prevent a failed buffered stdout from being retried during
223
+ interpreter shutdown. Help output follows the same complete-delivery contract.
224
+ These process controls are tested on Linux CPython; no Windows claim is made.
225
+
226
+ `UNEQUAL_RANK_BATCH_COUNTS` is a planning warning, not proof of a DDP hang.
227
+ Actual synchronization, masking and join handling are outside this tool.
228
+ `EXACTLY_ONCE` does not establish randomness, class balance, content uniqueness,
229
+ annotation quality, statistical comparability, or actual sample consumption.
230
+ Reports contain the supplied IDs. Review before sharing them.
231
+
232
+ ## Why another tool?
233
+
234
+ [TrainParity](https://github.com/intelland/TrainParity) checks observed stable-ID
235
+ trajectories against a declared coverage policy and also tests actual training
236
+ parity. Use it to audit observed runs. This tool instead computes a prospective
237
+ finite plan without executing training code or importing a framework.
238
+
239
+ [PyTorch documents](https://docs.pytorch.org/docs/main/utils/data.html) sampler
240
+ padding/truncation and independent iterable-worker tails. Its `len(dataloader)`
241
+ estimate may miss fragmented tails. This tool does not fix those semantics; it
242
+ makes a limited, explicit plan inspectable with identity-level accounting.
243
+
244
+ [WebDataset](https://webdataset.github.io/webdataset/webdataset/) offers actual
245
+ sharding, batching and epoch controls. This tool does not emulate its
246
+ pipeline or resampling rules.
247
+
248
+ ## Development
249
+
250
+ Python 3.10+, standard-library runtime. `python -m unittest discover -s tests -v`.
251
+ The tests include an independent event-by-event reference over 9,360 small plans,
252
+ regular input/output failures, empty sources, Unicode IDs and invalid inputs.
253
+ The [first hosted run](https://github.com/anishpentyala/batchscope/actions/runs/45344164628)
254
+ passed the standard-library and installed-wheel checks on Python 3.10, 3.13 and
255
+ 3.15. Its Python 3.13 CPU job also passed three real PyTorch 2.15.0+cpu tests:
256
+ unshuffled map sampling with local batch tails, two-worker map loading, and the
257
+ explicit strided/replicated iterable sources with zero or two DataLoader workers.
258
+ Those controls compare emitted identity multiplicities and local batch counts,
259
+ not arrival order, optimizer updates or arbitrary pipelines. NumPy was not
260
+ installed in that CPU job; PyTorch warned about its unavailable NumPy bridge,
261
+ which these tests do not use. Other framework versions, GPUs and custom loading
262
+ strategies remain unvalidated. Implementation and tests were produced on Anish's behalf; no claim of his
263
+ personal code review or use is made.
264
+
265
+ ## Audit explicit batch boundaries
266
+
267
+ ```sh
268
+ batchscope --batch-receipts plan.json batches.json
269
+ ```
270
+
271
+ A batch file is a JSON array of objects with exactly `rank`, `worker` and `ids`,
272
+ for example `[{"rank": 0, "worker": null, "ids": ["a", "b"]}]`.
273
+ Each `ids` is a nonempty list of retained occurrences. Repeated IDs remain
274
+ separate occurrences. Rank/worker rules are the same as receipts above. Empty
275
+ batches are rejected; an empty top-level array represents no retained batches.
276
+ At most1,000,000 batches and1,000,000 total occurrences are admitted, subject to
277
+ the same8MiB CLI input limit. Unknown nonempty IDs remain mismatch evidence.
278
+
279
+ The API is `audit_batches(plan, batches)`. This opt-in mode compares exact
280
+ local batch ID lists against consecutive `batch_size` chunks of each modeled
281
+ consumer's emitted sequence, including a permitted short final batch. Input
282
+ array order must preserve each consumer's local batch order. Different consumers
283
+ may interleave freely. For iterable models, consumers are rank/worker pairs,
284
+ not reconstructed rank-level loader batches. Map workers remain `null`.
285
+
286
+ The `batchscope-batch-receipts-v1` report embeds the full `ordered_receipts`
287
+ report, including planned coverage status, count and local order differences.
288
+ `boundary_differences` gives each mismatched consumer's expected/observed batch
289
+ counts and its first differing zero-based local batch index with full
290
+ `expected_ids`/`observed_ids`. Missing and extra batches use `null` on the absent
291
+ side. Only the first local difference is retained, not a sequence alignment or
292
+ causal diagnosis. Reports disclose IDs. Existing receipt modes are unchanged.
293
+
294
+ Thus `[a,b],[c]` differs from `[a],[b,c]` even though flattened ID order and counts
295
+ agree. Exit0 is `MATCHED_BATCH_RECEIPTS`, exit1 is `BATCH_RECEIPT_MISMATCH`, and
296
+ exit2 is invalid input or failed delivery. A match can agree with an empty,
297
+ omitting or duplicating plan. This does not authenticate collection completeness,
298
+ prove runtime consumption or contents, infer cross-consumer order, or establish
299
+ optimizer updates, synchronized collectives or exactly-once coverage.
@@ -0,0 +1,289 @@
1
+ # batchscope
2
+
3
+ Inspect a finite data-loading plan before starting a training or evaluation run.
4
+ Supply an ordered list of unique sample IDs, explicit partition rules, batch size
5
+ and tail policies. See which identities would repeat or disappear under that
6
+ model, and how many local batches each rank would produce.
7
+
8
+ This is an experimental tool. It has no observed users. It does not
9
+ inspect or run a real DataLoader, read sample contents, launch training, or prove
10
+ that a configured training job follows this plan.
11
+
12
+ ## A small but consequential tail
13
+
14
+ Five samples split across two ranks need six sampler slots when padding is on.
15
+ Then a loader that drops incomplete local batches can remove two occurrences,
16
+ including the extra padding. Counting padding alone misses the final coverage.
17
+
18
+ ```sh
19
+ python -m pip install .
20
+ batchscope examples/padded.json
21
+ ```
22
+
23
+ That example emits six occurrences of five identities, so it exits 1 with
24
+ `COVERAGE_CHANGED`. Change `loader_drop_last` to `true` and it emits four
25
+ identities once, omitting the fifth. This is invented input, not a measured job.
26
+
27
+ ## Explicit models
28
+
29
+ | mode | ownership before batching | tail policy |
30
+ | --- | --- | --- |
31
+ | `distributed_map` | pad/truncate the supplied global order to a rank multiple, then stride by rank | loader tail is per rank; workers do not repartition sampler indices |
32
+ | `iterable_strided` | rank-major combined consumer index `rank * workers + worker`, stride by `ranks * workers` | one tail per rank/worker |
33
+ | `iterable_replicated` | every rank/worker sees the entire ordered universe | one tail per rank/worker |
34
+
35
+ `workers` means the number of independently iterated sources per rank. Use 1 for
36
+ single-process iterable loading. It is not a literal translation of PyTorch's
37
+ `num_workers=0`. Map-style worker count does not multiply or repartition samples.
38
+
39
+ These are declared mathematical models. The map model follows the documented
40
+ unshuffled `DistributedSampler` padding/truncation rule and ordinary local
41
+ batching. The iterable rules describe two explicitly chosen source strategies,
42
+ not arbitrary PyTorch iterable datasets. A different worker ordering or nested
43
+ sharding can produce different identities. Supply the actual intended order.
44
+
45
+ No RNG or shuffle emulation, custom sampler, dynamic filtering, resampling,
46
+ variable batch sizes, accumulation, retries, early exit, persistent-worker state,
47
+ resume state, sample packing, or automatic framework-config parsing. Do not use
48
+ these counts as evidence of optimizer updates or synchronized collective calls.
49
+
50
+ ## Input
51
+
52
+ ```json
53
+ {
54
+ "ids": ["a", "b", "c", "d", "e"],
55
+ "mode": "distributed_map",
56
+ "ranks": 2,
57
+ "workers": 1,
58
+ "batch_size": 2,
59
+ "sampler_drop_last": false,
60
+ "loader_drop_last": false
61
+ }
62
+ ```
63
+
64
+ All fields shown are required for `distributed_map`. The other modes require all
65
+ except `sampler_drop_last`, which is rejected rather than silently ignored.
66
+ IDs are nonempty unique strings. Distinct IDs can contain identical sample
67
+ contents; this tool cannot detect that. No whitespace or Unicode normalization.
68
+ Unknown fields, duplicate JSON members, NaN/Infinity, invalid UTF-8, nonregular
69
+ input files and plans over 8 MiB are rejected. Limits: 100,000 IDs, 1,024 combined
70
+ consumers, 1,000,000 assigned occurrences. These are admission limits, not a hard
71
+ RAM/time guarantee. A regular file on a slow filesystem can still block.
72
+
73
+ ## Selected identity witnesses
74
+
75
+ Add optional `"trace_ids": ["a", "e"]` to the input to locate selected IDs within
76
+ this finite model. Select at most 64 distinct IDs from the declared universe.
77
+ The report adds `traces`, in selection order. Each trace contains the ID,
78
+ `sampler_removed` (0 or 1), and a rank/worker-ordered `consumers` list containing
79
+ only consumers assigned that ID. Each consumer has `assigned`, `emitted`, and
80
+ `loader_dropped` occurrence counts. Map-style consumers have `worker: null`;
81
+ map workers do not define independent sample ownership here.
82
+
83
+ For the example above, tracing `a` shows one assigned occurrence on each rank.
84
+ With `loader_drop_last: true`, rank 0 retains its occurrence and rank 1 drops its
85
+ occurrence. An ID removed by global sampler truncation has `sampler_removed: 1`
86
+ and an empty consumer list. An empty selection emits `traces: []`; omitting
87
+ `trace_ids` preserves the original report shape. Traces describe declared
88
+ ownership and tail arithmetic, not arrival order, observed consumption, or
89
+ whether identical contents occur under other IDs. Reports still disclose IDs.
90
+
91
+ ## Audit explicit observed receipts
92
+
93
+ ```sh
94
+ batchscope --receipts plan.json receipts.json
95
+ ```
96
+
97
+ Receipts are a JSON array of individual retained occurrences, for example
98
+ `[{"id": "a", "rank": 0, "worker": null}]`. Each object requires exactly these
99
+ three fields. Record at the boundary you intend to audit, and supply a complete
100
+ list for the declared finite run. Nothing here records or authenticates events.
101
+ Repeated entries are separate occurrences, not deduplicated records. Unknown
102
+ nonempty IDs are reported as unexpected evidence, not silently discarded.
103
+ Rank must exist in the plan. Iterable worker must exist too. Map worker must be
104
+ `null`, because this model does not predict map-worker identity ownership.
105
+
106
+ The `batchscope-receipts-v1` report compares occurrence counts per exact
107
+ `(id, rank, worker)` key. It reports every differing key, missing and extra
108
+ occurrences separately, and the number of unknown-ID occurrences (a subset of
109
+ extras). A consumer swap therefore produces a missing and an extra occurrence
110
+ even when global totals match. Known rows follow plan ID order and then consumer
111
+ order; unknown IDs follow first-observed ID order. Arrival order is not checked.
112
+ The full baseline coverage status and warnings remain visible as separate fields.
113
+
114
+ Exit 0 means `MATCHED_RECEIPTS`, exit 1 means `RECEIPT_MISMATCH`, and exit 2 means
115
+ invalid input or failed output delivery. Matching receipts does **not** mean
116
+ exactly-once coverage: they can match a plan that deliberately duplicates or
117
+ omits IDs, or an empty plan. It also cannot establish receipt completeness,
118
+ provenance, real consumption, sample contents, batch boundaries, execution order,
119
+ optimizer updates or synchronized collective calls. An incomplete receipt export
120
+ will look like missing occurrences. Use the retained evidence and its collection
121
+ boundary to interpret a mismatch, not as a diagnosis of its cause.
122
+
123
+ The receipt file uses the same strict JSON and 8 MiB file limits as a plan, and
124
+ at most 1,000,000 occurrence objects. IDs use the plan's 256-character limit.
125
+ Receipts may disclose sensitive IDs. The API is `audit_receipts(plan, receipts)`;
126
+ inputs are not mutated. Single-plan and comparison outputs are unchanged.
127
+
128
+ ## Check order within each modeled consumer
129
+
130
+ ```sh
131
+ batchscope --ordered-receipts plan.json receipts.json
132
+ ```
133
+
134
+ This opt-in mode uses the same strict receipt contract and count differences as
135
+ `--receipts`, then also checks the order of IDs within each modeled consumer.
136
+ The API is `audit_receipts(plan, receipts, check_order=True)`. The default API
137
+ and `--receipts` reports retain their original shape and count-only semantics.
138
+
139
+ Input array order must reflect the collection boundary's order for each consumer.
140
+ Events from different consumers may interleave freely. Map consumers are ranks
141
+ with `worker: null`; iterable consumers are rank/worker pairs. This does not
142
+ compare a global arrival order, infer PyTorch's worker scheduling, or reconstruct
143
+ batches. Do not use this option on an unordered log export or a loader configured
144
+ to return items in a different order from the declared model.
145
+
146
+ The report uses `batchscope-ordered-receipts-v1`. `order_differences` lists each
147
+ mismatched consumer in rank/worker order, its expected and observed lengths, and
148
+ its first differing zero-based local index with `expected_id` and `observed_id`.
149
+ A missing suffix has `observed_id: null`; an extra suffix has `expected_id: null`.
150
+ Only the first local divergence is reported. These are positional witnesses,
151
+ not an edit script, causal diagnosis, or alignment after an insertion/deletion.
152
+ Repeated occurrences of the same ID are indistinguishable. It cannot detect a
153
+ swap between equal IDs or different sample contents carrying the same ID.
154
+
155
+ Exit 0 is `MATCHED_ORDERED_RECEIPTS`; exit 1 is `ORDERED_RECEIPT_MISMATCH`; exit 2
156
+ is invalid input or failed delivery. As with count-only audits, a match may agree
157
+ with a duplicating, incomplete or empty plan. The evidence remains conditional
158
+ on complete, correctly labeled receipts, not authenticated runtime consumption,
159
+ exactly-once coverage, batch boundaries or training behavior.
160
+
161
+ ## Compare two explicit plans
162
+
163
+ ```sh
164
+ batchscope --compare before.json after.json
165
+ ```
166
+
167
+ Both inputs use the same validation and file limits as a single plan. They must
168
+ declare the same unique ID universe, but may reorder it or change any explicit
169
+ loading rule. No union, intersection, coercion or implicit ID alignment is used.
170
+ Rows align by exact ID and are reported in the before plan's order.
171
+
172
+ The `batchscope-comparison-v1` report contains before/after coverage statuses,
173
+ aggregate before/after counts and signed deltas (after minus before), per-rank
174
+ batch counts, and every ID whose assigned/emitted/loader-dropped/sampler-removed
175
+ accounting changes. Added or removed ranks use `null` for the absent side and
176
+ its delta, rather than pretending an absent rank had zero batches. Separate
177
+ `emitted_gain_occurrences` and `emitted_loss_occurrences` prevent equal aggregate
178
+ counts from concealing identity swaps. Changing input order can change which
179
+ IDs survive tails even when emitted totals and batch counts stay the same.
180
+
181
+ Comparison exits 0 for `SAME_ACCOUNTING`, 1 for `CHANGED_ACCOUNTING`, and 2 for
182
+ invalid inputs or failed output delivery. A model change, consumer-count change
183
+ or warning change counts as changed accounting too. `input_order_changed`
184
+ reports reordering separately; unchanged accounting is **not** a claim of equal
185
+ order, per-consumer identity ownership, statistical equivalence, synchronization
186
+ or actual consumption. In particular, two identically incomplete/duplicating
187
+ plans can return `SAME_ACCOUNTING`; inspect both embedded coverage statuses.
188
+ Optional trace selections do not affect comparison. Full single-plan reports
189
+ remain available separately; this comparison does not embed their trace rows.
190
+
191
+ Python API: `from batchscope import compare_plans`, then
192
+ `compare_plans(before_dict, after_dict)`. Inputs are not modified. All counts and
193
+ IDs describe declared finite models only. Comparisons are source-only and are
194
+ not part of any published package release.
195
+
196
+ ## Report and exits
197
+
198
+ Every declared ID has assigned, emitted and loader-dropped multiplicities, plus
199
+ whether global sampler truncation removed it. Each consumer reports counts,
200
+ batches and final batch size; per-rank batches sum that rank's worker batches.
201
+
202
+ - 0: `EXACTLY_ONCE` under the supplied finite model.
203
+ - 1: `COVERAGE_CHANGED` or `EMPTY_UNIVERSE`. Review the counts.
204
+ - 2: invalid input, usage or output delivery failure. No usable complete report.
205
+
206
+ The full report must be written and flushed before exit 0 or 1. A broken output
207
+ may retain a JSON prefix, so use a report only with successful delivery and its
208
+ expected exit status. Redirecting stdout is not an atomic output transaction. A short `write` return
209
+ or a failed flush is an output failure too, even if no exception was raised by
210
+ `write`. The callable `batchscope.__main__.main()` returns 2 without replacing
211
+ or closing caller-owned stdout. The module and installed console use a separate
212
+ process entrypoint to prevent a failed buffered stdout from being retried during
213
+ interpreter shutdown. Help output follows the same complete-delivery contract.
214
+ These process controls are tested on Linux CPython; no Windows claim is made.
215
+
216
+ `UNEQUAL_RANK_BATCH_COUNTS` is a planning warning, not proof of a DDP hang.
217
+ Actual synchronization, masking and join handling are outside this tool.
218
+ `EXACTLY_ONCE` does not establish randomness, class balance, content uniqueness,
219
+ annotation quality, statistical comparability, or actual sample consumption.
220
+ Reports contain the supplied IDs. Review before sharing them.
221
+
222
+ ## Why another tool?
223
+
224
+ [TrainParity](https://github.com/intelland/TrainParity) checks observed stable-ID
225
+ trajectories against a declared coverage policy and also tests actual training
226
+ parity. Use it to audit observed runs. This tool instead computes a prospective
227
+ finite plan without executing training code or importing a framework.
228
+
229
+ [PyTorch documents](https://docs.pytorch.org/docs/main/utils/data.html) sampler
230
+ padding/truncation and independent iterable-worker tails. Its `len(dataloader)`
231
+ estimate may miss fragmented tails. This tool does not fix those semantics; it
232
+ makes a limited, explicit plan inspectable with identity-level accounting.
233
+
234
+ [WebDataset](https://webdataset.github.io/webdataset/webdataset/) offers actual
235
+ sharding, batching and epoch controls. This tool does not emulate its
236
+ pipeline or resampling rules.
237
+
238
+ ## Development
239
+
240
+ Python 3.10+, standard-library runtime. `python -m unittest discover -s tests -v`.
241
+ The tests include an independent event-by-event reference over 9,360 small plans,
242
+ regular input/output failures, empty sources, Unicode IDs and invalid inputs.
243
+ The [first hosted run](https://github.com/anishpentyala/batchscope/actions/runs/45344164628)
244
+ passed the standard-library and installed-wheel checks on Python 3.10, 3.13 and
245
+ 3.15. Its Python 3.13 CPU job also passed three real PyTorch 2.15.0+cpu tests:
246
+ unshuffled map sampling with local batch tails, two-worker map loading, and the
247
+ explicit strided/replicated iterable sources with zero or two DataLoader workers.
248
+ Those controls compare emitted identity multiplicities and local batch counts,
249
+ not arrival order, optimizer updates or arbitrary pipelines. NumPy was not
250
+ installed in that CPU job; PyTorch warned about its unavailable NumPy bridge,
251
+ which these tests do not use. Other framework versions, GPUs and custom loading
252
+ strategies remain unvalidated. Implementation and tests were produced on Anish's behalf; no claim of his
253
+ personal code review or use is made.
254
+
255
+ ## Audit explicit batch boundaries
256
+
257
+ ```sh
258
+ batchscope --batch-receipts plan.json batches.json
259
+ ```
260
+
261
+ A batch file is a JSON array of objects with exactly `rank`, `worker` and `ids`,
262
+ for example `[{"rank": 0, "worker": null, "ids": ["a", "b"]}]`.
263
+ Each `ids` is a nonempty list of retained occurrences. Repeated IDs remain
264
+ separate occurrences. Rank/worker rules are the same as receipts above. Empty
265
+ batches are rejected; an empty top-level array represents no retained batches.
266
+ At most1,000,000 batches and1,000,000 total occurrences are admitted, subject to
267
+ the same8MiB CLI input limit. Unknown nonempty IDs remain mismatch evidence.
268
+
269
+ The API is `audit_batches(plan, batches)`. This opt-in mode compares exact
270
+ local batch ID lists against consecutive `batch_size` chunks of each modeled
271
+ consumer's emitted sequence, including a permitted short final batch. Input
272
+ array order must preserve each consumer's local batch order. Different consumers
273
+ may interleave freely. For iterable models, consumers are rank/worker pairs,
274
+ not reconstructed rank-level loader batches. Map workers remain `null`.
275
+
276
+ The `batchscope-batch-receipts-v1` report embeds the full `ordered_receipts`
277
+ report, including planned coverage status, count and local order differences.
278
+ `boundary_differences` gives each mismatched consumer's expected/observed batch
279
+ counts and its first differing zero-based local batch index with full
280
+ `expected_ids`/`observed_ids`. Missing and extra batches use `null` on the absent
281
+ side. Only the first local difference is retained, not a sequence alignment or
282
+ causal diagnosis. Reports disclose IDs. Existing receipt modes are unchanged.
283
+
284
+ Thus `[a,b],[c]` differs from `[a],[b,c]` even though flattened ID order and counts
285
+ agree. Exit0 is `MATCHED_BATCH_RECEIPTS`, exit1 is `BATCH_RECEIPT_MISMATCH`, and
286
+ exit2 is invalid input or failed delivery. A match can agree with an empty,
287
+ omitting or duplicating plan. This does not authenticate collection completeness,
288
+ prove runtime consumption or contents, infer cross-consumer order, or establish
289
+ optimizer updates, synchronized collectives or exactly-once coverage.
@@ -0,0 +1,9 @@
1
+ from .core import InvalidPlan, analyze
2
+
3
+ __all__ = ['InvalidPlan', 'analyze', 'compare_plans', 'audit_receipts', 'audit_batches']
4
+
5
+ from .compare import compare_plans
6
+
7
+ from .receipts import audit_receipts
8
+
9
+ from .batches import audit_batches