batchscope 0.1.0__py3-none-any.whl

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.
batchscope/__init__.py ADDED
@@ -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
batchscope/__main__.py ADDED
@@ -0,0 +1,95 @@
1
+ import json
2
+ import os
3
+ import stat
4
+ import sys
5
+ from .core import InvalidPlan, analyze
6
+
7
+ MAX_BYTES = 8 * 1024 * 1024
8
+
9
+
10
+ def pairs(items):
11
+ result = {}
12
+ for k, v in items:
13
+ if k in result:
14
+ raise InvalidPlan('repeated JSON object member')
15
+ result[k] = v
16
+ return result
17
+
18
+
19
+ def constant(_):
20
+ raise InvalidPlan('non-JSON numeric constant')
21
+
22
+
23
+ def deliver(text):
24
+ """One complete write plus flush, never treating a short write as delivery."""
25
+ written = sys.stdout.write(text)
26
+ if written != len(text):
27
+ raise OSError('short output write')
28
+ sys.stdout.flush()
29
+
30
+
31
+ def read_plan(path):
32
+ fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NONBLOCK', 0))
33
+ with os.fdopen(fd, 'rb') as stream:
34
+ if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
35
+ raise InvalidPlan('plan input must be a regular file')
36
+ raw = stream.read(MAX_BYTES + 1)
37
+ if len(raw) > MAX_BYTES:
38
+ raise InvalidPlan('plan exceeds 8 MiB')
39
+ return json.loads(raw.decode('utf-8'), object_pairs_hook=pairs, parse_constant=constant)
40
+
41
+
42
+ def _run():
43
+ try:
44
+ valid = len(sys.argv) == 2 or (len(sys.argv) == 4 and sys.argv[1] in ('--compare', '--receipts', '--ordered-receipts', '--batch-receipts'))
45
+ if not valid or sys.argv[1] in ('-h', '--help'):
46
+ deliver('Usage: python -m batchscope PLAN.json\n python -m batchscope --compare BEFORE.json AFTER.json\n python -m batchscope --receipts PLAN.json RECEIPTS.json\n python -m batchscope --ordered-receipts PLAN.json RECEIPTS.json\n python -m batchscope --batch-receipts PLAN.json BATCHES.json\n')
47
+ return (0 if len(sys.argv) == 2 else 2), False
48
+ if len(sys.argv) == 4 and sys.argv[1] == '--batch-receipts':
49
+ from .batches import audit_batches
50
+ result = audit_batches(read_plan(sys.argv[2]), read_plan(sys.argv[3]))
51
+ elif len(sys.argv) == 4 and sys.argv[1] in ('--receipts', '--ordered-receipts'):
52
+ from .receipts import audit_receipts
53
+ result = audit_receipts(read_plan(sys.argv[2]), read_plan(sys.argv[3]),
54
+ check_order=sys.argv[1] == '--ordered-receipts')
55
+ elif len(sys.argv) == 4 and sys.argv[1] == '--compare':
56
+ from .compare import compare_plans
57
+ result = compare_plans(read_plan(sys.argv[2]), read_plan(sys.argv[3]))
58
+ else:
59
+ result = analyze(read_plan(sys.argv[1]))
60
+ output = json.dumps(result, ensure_ascii=True, sort_keys=True, indent=2, allow_nan=False) + '\n'
61
+ deliver(output)
62
+ return (0 if result['status'] in ('EXACTLY_ONCE', 'SAME_ACCOUNTING', 'MATCHED_RECEIPTS', 'MATCHED_ORDERED_RECEIPTS', 'MATCHED_BATCH_RECEIPTS') else 1), False
63
+ except (InvalidPlan, ValueError, OSError, RecursionError) as exc:
64
+ try:
65
+ sys.stderr.write('batchscope: invalid input or output failure: ' + str(exc) + '\n')
66
+ sys.stderr.flush()
67
+ except (OSError, ValueError):
68
+ pass
69
+ return 2, True
70
+
71
+
72
+ def main():
73
+ """Return status without replacing or closing caller-owned streams."""
74
+ return _run()[0]
75
+
76
+
77
+ def entrypoint():
78
+ """Prevent a process-level retry of a failed buffered stdout at shutdown."""
79
+ code, failed = _run()
80
+ if failed:
81
+ try:
82
+ fd = sys.stdout.fileno()
83
+ sink = os.open(os.devnull, os.O_WRONLY)
84
+ try:
85
+ os.dup2(sink, fd)
86
+ finally:
87
+ if sink != fd:
88
+ os.close(sink)
89
+ except (OSError, ValueError, AttributeError):
90
+ sys.stdout = open(os.devnull, 'w')
91
+ return code
92
+
93
+
94
+ if __name__ == '__main__':
95
+ raise SystemExit(entrypoint())
batchscope/batches.py ADDED
@@ -0,0 +1,66 @@
1
+ """Compare explicit local batch boundaries with a declared finite plan."""
2
+ from .core import InvalidPlan, MAX_ASSIGNMENTS, _analyze, integer
3
+ from .receipts import audit_receipts
4
+
5
+
6
+ def audit_batches(plan, batches):
7
+ """Audit supplied complete batches in each consumer's local order.
8
+
9
+ Cross-consumer interleaving is ignored. Batches must be nonempty. Flattened
10
+ ordered receipt evidence is retained separately, not confused with boundary
11
+ agreement or proof of actual training behavior.
12
+ """
13
+ sequences = {}
14
+ _analyze(plan, emission_sequences=sequences)
15
+ if type(batches) is not list or len(batches) > MAX_ASSIGNMENTS:
16
+ raise InvalidPlan(f'batches must be an array of at most {MAX_ASSIGNMENTS} batches')
17
+ observed = {consumer: [] for consumer in sequences}
18
+ receipts = []
19
+ for batch in batches:
20
+ if type(batch) is not dict or set(batch) != {'ids', 'rank', 'worker'}:
21
+ raise InvalidPlan('each batch must contain exactly ids, rank, worker')
22
+ rank = integer(batch['rank'], 'batch rank', 0, plan['ranks'] - 1)
23
+ worker = batch['worker']
24
+ if plan['mode'] == 'distributed_map':
25
+ if worker is not None:
26
+ raise InvalidPlan('map batches require worker: null')
27
+ else:
28
+ integer(worker, 'batch worker', 0, plan['workers'] - 1)
29
+ ids = batch['ids']
30
+ if type(ids) is not list or not ids:
31
+ raise InvalidPlan('batch ids must be a nonempty array')
32
+ if len(receipts) + len(ids) > MAX_ASSIGNMENTS:
33
+ raise InvalidPlan(f'batches exceed {MAX_ASSIGNMENTS} total occurrences')
34
+ for identity in ids:
35
+ if type(identity) is not str or not identity or len(identity) > 256:
36
+ raise InvalidPlan('batch ID must be a nonempty string of at most 256 characters')
37
+ receipts.append({'id': identity, 'rank': rank, 'worker': worker})
38
+ observed[rank, worker].append(ids)
39
+ ordered = audit_receipts(plan, receipts, check_order=True)
40
+ differences = []
41
+ expected_total = 0
42
+ size = plan['batch_size']
43
+ for (rank, worker), sequence in sequences.items():
44
+ expected = [sequence[i:i + size] for i in range(0, len(sequence), size)]
45
+ got = observed[rank, worker]
46
+ expected_total += len(expected)
47
+ first = next((i for i in range(max(len(expected), len(got)))
48
+ if (expected[i] if i < len(expected) else None) !=
49
+ (got[i] if i < len(got) else None)), None)
50
+ if first is not None:
51
+ differences.append({'rank': rank, 'worker': worker,
52
+ 'expected_batches': len(expected), 'observed_batches': len(got),
53
+ 'first_difference': {
54
+ 'index': first,
55
+ 'expected_ids': expected[first] if first < len(expected) else None,
56
+ 'observed_ids': list(got[first]) if first < len(got) else None}})
57
+ return {
58
+ 'schema': 'batchscope-batch-receipts-v1',
59
+ 'status': ('MATCHED_BATCH_RECEIPTS' if not differences and
60
+ ordered['status'] == 'MATCHED_ORDERED_RECEIPTS' else 'BATCH_RECEIPT_MISMATCH'),
61
+ 'expected_batches': expected_total, 'observed_batches': len(batches),
62
+ 'boundary_differences': differences, 'ordered_receipts': ordered,
63
+ 'scope': 'Conditional on complete supplied nonempty batches in each modeled consumer order. '
64
+ 'No global order, provenance, runtime consumption, contents, optimizer updates, '
65
+ 'synchronized collectives or exactly-once guarantee.',
66
+ }
batchscope/compare.py ADDED
@@ -0,0 +1,55 @@
1
+ """Identity-preserving differences between two declared finite loading plans."""
2
+ from .core import InvalidPlan, analyze
3
+
4
+
5
+ def compare_plans(before, after):
6
+ """Compare counts on an identical ID universe; order may deliberately change.
7
+
8
+ Positive deltas are after minus before. No arrival ordering, optimizer or
9
+ real-run equivalence is implied, even when all accounting is unchanged.
10
+ """
11
+ left, right = analyze(before), analyze(after)
12
+ if set(before['ids']) != set(after['ids']):
13
+ raise InvalidPlan('comparison requires the same declared ID universe')
14
+ right_ids = {row['id']: row for row in right['ids']}
15
+ rows = []
16
+ for old in left['ids']:
17
+ new = right_ids[old['id']]
18
+ deltas = {key: new[key] - old[key]
19
+ for key in ('assigned', 'emitted', 'loader_dropped', 'sampler_removed')}
20
+ if any(deltas.values()):
21
+ rows.append({'id': old['id'], 'before': dict(old), 'after': dict(new),
22
+ 'delta': deltas})
23
+ ranks = []
24
+ for rank in range(max(len(left['rank_batches']), len(right['rank_batches']))):
25
+ old = left['rank_batches'][rank] if rank < len(left['rank_batches']) else None
26
+ new = right['rank_batches'][rank] if rank < len(right['rank_batches']) else None
27
+ ranks.append({'rank': rank, 'before': old, 'after': new,
28
+ 'delta': None if old is None or new is None else new - old})
29
+ totals = {key: {'before': left[key], 'after': right[key],
30
+ 'delta': right[key] - left[key]}
31
+ for key in ('assigned_occurrences', 'emitted_occurrences', 'distinct_emitted',
32
+ 'missing_count', 'repeated_id_count', 'repeat_occurrences',
33
+ 'sampler_removed_count', 'sampler_padding_count',
34
+ 'loader_dropped_occurrences')}
35
+ old_consumers = {(c['rank'], c['worker']): c for c in left['consumers']}
36
+ new_consumers = {(c['rank'], c['worker']): c for c in right['consumers']}
37
+ # Different models cannot be called equivalent merely because their totals agree.
38
+ changed = (bool(rows) or left['model'] != right['model']
39
+ or old_consumers != new_consumers or left['warnings'] != right['warnings']
40
+ or any(value['delta'] for value in totals.values()))
41
+ return {'schema': 'batchscope-comparison-v1',
42
+ 'status': 'CHANGED_ACCOUNTING' if changed else 'SAME_ACCOUNTING',
43
+ 'universe_size': left['universe_size'],
44
+ 'input_order_changed': before['ids'] != after['ids'],
45
+ 'before': {'model': left['model'], 'status': left['status'],
46
+ 'warnings': left['warnings']},
47
+ 'after': {'model': right['model'], 'status': right['status'],
48
+ 'warnings': right['warnings']},
49
+ 'totals': totals, 'rank_batches': ranks,
50
+ 'changed_id_count': len(rows), 'ids': rows,
51
+ 'emitted_gain_occurrences': sum(max(0, row['delta']['emitted']) for row in rows),
52
+ 'emitted_loss_occurrences': sum(max(0, -row['delta']['emitted']) for row in rows),
53
+ 'consumer_counts_changed': old_consumers != new_consumers,
54
+ 'scope': ('declared finite accounting only; same accounting does not establish '
55
+ 'same ordering, consumer identity ownership, synchronization or real consumption')}
batchscope/core.py ADDED
@@ -0,0 +1,151 @@
1
+ """Finite, explicitly ordered loading plans, not live loader inspection."""
2
+ from collections import Counter
3
+
4
+ MAX_IDS = 100_000
5
+ MAX_CONSUMERS = 1024
6
+ MAX_ASSIGNMENTS = 1_000_000
7
+ MAX_TRACE_IDS = 64
8
+
9
+
10
+ class InvalidPlan(ValueError):
11
+ pass
12
+
13
+
14
+ def integer(value, name, minimum, maximum):
15
+ if type(value) is not int or not minimum <= value <= maximum:
16
+ raise InvalidPlan(f'{name} must be an integer in [{minimum}, {maximum}]')
17
+ return value
18
+
19
+
20
+ def analyze(plan):
21
+ return _analyze(plan)
22
+
23
+
24
+ def _analyze(plan, emission_counts=None, emission_sequences=None):
25
+ if type(plan) is not dict:
26
+ raise InvalidPlan('plan must be an object')
27
+ required = {'ids', 'mode', 'ranks', 'workers', 'batch_size', 'loader_drop_last'}
28
+ allowed = required | {'sampler_drop_last', 'trace_ids'}
29
+ if set(plan) - allowed or required - set(plan):
30
+ raise InvalidPlan('unknown or missing plan fields')
31
+ ids = plan['ids']
32
+ if type(ids) is not list or len(ids) > MAX_IDS:
33
+ raise InvalidPlan(f'ids must be an array of at most {MAX_IDS} values')
34
+ if any(type(x) is not str or not x or len(x) > 256 for x in ids):
35
+ raise InvalidPlan('each ID must be a nonempty string of at most 256 characters')
36
+ if len(set(ids)) != len(ids):
37
+ raise InvalidPlan('IDs must be unique in the declared universe')
38
+ trace_ids = plan.get('trace_ids', [])
39
+ if type(trace_ids) is not list or len(trace_ids) > MAX_TRACE_IDS:
40
+ raise InvalidPlan(f'trace_ids must be an array of at most {MAX_TRACE_IDS} IDs')
41
+ universe = set(ids)
42
+ if any(type(x) is not str or x not in universe for x in trace_ids):
43
+ raise InvalidPlan('trace_ids must contain only declared IDs')
44
+ if len(set(trace_ids)) != len(trace_ids):
45
+ raise InvalidPlan('trace_ids must be unique')
46
+ trace_rows = {x: [] for x in trace_ids}
47
+ mode = plan['mode']
48
+ if type(mode) is not str or mode not in ('distributed_map', 'iterable_strided', 'iterable_replicated'):
49
+ raise InvalidPlan('unsupported mode')
50
+ ranks = integer(plan['ranks'], 'ranks', 1, MAX_CONSUMERS)
51
+ workers = integer(plan['workers'], 'workers', 1, MAX_CONSUMERS)
52
+ if ranks * workers > MAX_CONSUMERS:
53
+ raise InvalidPlan(f'at most {MAX_CONSUMERS} rank/worker consumers')
54
+ batch = integer(plan['batch_size'], 'batch_size', 1, MAX_ASSIGNMENTS)
55
+ drop = plan['loader_drop_last']
56
+ if type(drop) is not bool:
57
+ raise InvalidPlan('loader_drop_last must be boolean')
58
+ if mode == 'distributed_map':
59
+ if type(plan.get('sampler_drop_last')) is not bool:
60
+ raise InvalidPlan('distributed_map requires boolean sampler_drop_last')
61
+ elif 'sampler_drop_last' in plan:
62
+ raise InvalidPlan('sampler_drop_last is only valid for distributed_map')
63
+ n = len(ids)
64
+ if mode == 'iterable_replicated':
65
+ size = n * ranks * workers
66
+ elif mode == 'distributed_map' and not plan['sampler_drop_last']:
67
+ size = ((n + ranks - 1) // ranks) * ranks
68
+ else:
69
+ size = n
70
+ if size > MAX_ASSIGNMENTS:
71
+ raise InvalidPlan(f'plan exceeds {MAX_ASSIGNMENTS} assigned occurrences')
72
+ sampler_removed = []
73
+ padding = []
74
+ consumers = []
75
+ assigned = Counter()
76
+ emitted = Counter()
77
+ discarded = Counter()
78
+ rank_steps = [0] * ranks
79
+ if mode == 'distributed_map':
80
+ if plan['sampler_drop_last']:
81
+ total = (n // ranks) * ranks
82
+ scheduled = list(ids[:total])
83
+ sampler_removed = list(ids[total:])
84
+ else:
85
+ total = ((n + ranks - 1) // ranks) * ranks
86
+ padding = [ids[i % n] for i in range(total - n)] if n else []
87
+ scheduled = ids + padding
88
+ groups = [(rank, None, scheduled[rank::ranks]) for rank in range(ranks)]
89
+ else:
90
+ groups = []
91
+ for rank in range(ranks):
92
+ for worker in range(workers):
93
+ offset = rank * workers + worker
94
+ group = ids[offset::ranks * workers] if mode == 'iterable_strided' else list(ids)
95
+ groups.append((rank, worker, group))
96
+ for rank, worker, group in groups:
97
+ keep = len(group) - len(group) % batch if drop else len(group)
98
+ active, tail = group[:keep], group[keep:]
99
+ steps = (keep + batch - 1) // batch
100
+ rank_steps[rank] += steps
101
+ if emission_sequences is not None:
102
+ emission_sequences[rank, worker] = active
103
+ if emission_counts is not None:
104
+ emission_counts.update((identity, rank, worker) for identity in active)
105
+ assigned.update(group)
106
+ emitted.update(active)
107
+ discarded.update(tail)
108
+ if trace_ids:
109
+ local_assigned = Counter(x for x in group if x in trace_rows)
110
+ local_emitted = Counter(x for x in active if x in trace_rows)
111
+ for x, count in local_assigned.items():
112
+ trace_rows[x].append({'rank': rank, 'worker': worker,
113
+ 'assigned': count, 'emitted': local_emitted[x],
114
+ 'loader_dropped': count - local_emitted[x]})
115
+ consumers.append({'rank': rank, 'worker': worker, 'assigned': len(group),
116
+ 'emitted': keep, 'dropped_tail': len(tail), 'batches': steps,
117
+ 'last_batch_size': (keep - (steps - 1) * batch) if steps else 0})
118
+ removed_set = set(sampler_removed)
119
+ rows = [{'id': x, 'assigned': assigned[x], 'emitted': emitted[x],
120
+ 'loader_dropped': discarded[x], 'sampler_removed': int(x in removed_set)}
121
+ for x in ids]
122
+ missing = [x for x in rows if x['emitted'] == 0]
123
+ repeated = [x for x in rows if x['emitted'] > 1]
124
+ exact = not missing and not repeated
125
+ warnings = []
126
+ if not ids:
127
+ warnings.append('EMPTY_UNIVERSE')
128
+ if len(set(rank_steps)) > 1:
129
+ warnings.append('UNEQUAL_RANK_BATCH_COUNTS')
130
+ if mode == 'distributed_map' and workers > 1:
131
+ warnings.append('MAP_WORKERS_DO_NOT_REPARTITION_SAMPLER')
132
+ expected_assigned = size - len(sampler_removed) if mode == 'distributed_map' and plan['sampler_drop_last'] else size
133
+ assert sum(assigned.values()) == expected_assigned
134
+ assert all(x['assigned'] == x['emitted'] + x['loader_dropped'] for x in rows)
135
+ report = {'schema': 'batchscope-report-v1', 'model': mode,
136
+ 'status': 'EMPTY_UNIVERSE' if not ids else ('EXACTLY_ONCE' if exact else 'COVERAGE_CHANGED'),
137
+ 'universe_size': n, 'assigned_occurrences': sum(assigned.values()),
138
+ 'emitted_occurrences': sum(emitted.values()),
139
+ 'distinct_emitted': len(emitted),
140
+ 'missing_count': len(missing), 'repeated_id_count': len(repeated),
141
+ 'repeat_occurrences': sum(x['emitted'] - 1 for x in repeated),
142
+ 'sampler_removed_count': len(sampler_removed), 'sampler_padding_count': len(padding),
143
+ 'loader_dropped_occurrences': sum(discarded.values()),
144
+ 'rank_batches': rank_steps, 'warnings': warnings,
145
+ 'consumers': consumers, 'ids': rows}
146
+
147
+ if 'trace_ids' in plan:
148
+ report['traces'] = [
149
+ {'id': x, 'sampler_removed': int(x in removed_set),
150
+ 'consumers': trace_rows[x]} for x in trace_ids]
151
+ return report
batchscope/receipts.py ADDED
@@ -0,0 +1,99 @@
1
+ """Compare caller-supplied ID receipts with a declared finite plan."""
2
+ from collections import Counter
3
+ from .core import InvalidPlan, MAX_ASSIGNMENTS, _analyze, integer
4
+
5
+
6
+ def audit_receipts(plan, receipts, *, check_order=False):
7
+ """Audit an explicit complete receipt list, not the runtime or its provenance.
8
+
9
+ Each occurrence has exactly id, rank, worker. Map workers are null because
10
+ this model does not determine which map worker fetched a sample.
11
+ """
12
+ if type(check_order) is not bool:
13
+ raise InvalidPlan('check_order must be boolean')
14
+ expected = Counter()
15
+ sequences = {} if check_order else None
16
+ baseline = _analyze(plan, expected, sequences)
17
+ positions = {}
18
+ first_mismatch = {}
19
+ if type(receipts) is not list or len(receipts) > MAX_ASSIGNMENTS:
20
+ raise InvalidPlan(f'receipts must be an array of at most {MAX_ASSIGNMENTS} occurrences')
21
+ observed = Counter()
22
+ universe = set(plan['ids'])
23
+ map_mode = plan['mode'] == 'distributed_map'
24
+ for event in receipts:
25
+ if type(event) is not dict or set(event) != {'id', 'rank', 'worker'}:
26
+ raise InvalidPlan('each receipt must contain exactly id, rank, worker')
27
+ identity = event['id']
28
+ if type(identity) is not str or not identity or len(identity) > 256:
29
+ raise InvalidPlan('receipt ID must be a nonempty string of at most 256 characters')
30
+ rank = integer(event['rank'], 'receipt rank', 0, plan['ranks'] - 1)
31
+ worker = event['worker']
32
+ if map_mode:
33
+ if worker is not None:
34
+ raise InvalidPlan('map receipts require worker: null')
35
+ else:
36
+ integer(worker, 'receipt worker', 0, plan['workers'] - 1)
37
+ observed[identity, rank, worker] += 1
38
+ if check_order:
39
+ consumer = rank, worker
40
+ position = positions.get(consumer, 0)
41
+ sequence = sequences[consumer]
42
+ want = sequence[position] if position < len(sequence) else None
43
+ if want != identity and consumer not in first_mismatch:
44
+ first_mismatch[consumer] = {'index': position, 'expected_id': want,
45
+ 'observed_id': identity}
46
+ positions[consumer] = position + 1
47
+ # Preserve plan ID order, then unknown IDs in first-observed order. Consumer
48
+ # sort is explicit so input arrival order never determines report order.
49
+ identities = list(plan['ids']) + list(dict.fromkeys(
50
+ event['id'] for event in receipts if event['id'] not in universe))
51
+ by_id = {}
52
+ for key in expected.keys() | observed.keys():
53
+ by_id.setdefault(key[0], []).append(key)
54
+ rows = []
55
+ missing = extra = unknown = 0
56
+ for identity in identities:
57
+ for key in sorted(by_id.get(identity, []), key=lambda k: (k[1], -1 if k[2] is None else k[2])):
58
+ want, got = expected[key], observed[key]
59
+ missing += max(0, want - got)
60
+ extra += max(0, got - want)
61
+ if identity not in universe:
62
+ unknown += got
63
+ if want != got:
64
+ rows.append({'id': identity, 'rank': key[1], 'worker': key[2],
65
+ 'known_id': identity in universe,
66
+ 'expected': want, 'observed': got, 'delta': got - want})
67
+ report = {'schema': 'batchscope-receipts-v1',
68
+ 'status': 'MATCHED_RECEIPTS' if not rows else 'RECEIPT_MISMATCH',
69
+ 'model': plan['mode'], 'planned_coverage_status': baseline['status'],
70
+ 'planned_warnings': baseline['warnings'],
71
+ 'expected_occurrences': sum(expected.values()),
72
+ 'observed_occurrences': len(receipts),
73
+ 'missing_occurrences': missing, 'extra_occurrences': extra,
74
+ 'unknown_id_occurrences': unknown, 'differences': rows,
75
+ 'scope': 'Conditional on the supplied complete receipts and declared plan. '
76
+ 'No provenance, runtime, order, batch-boundary, content, or exactly-once guarantee.'}
77
+
78
+ if check_order:
79
+ differences = []
80
+ for (rank, worker), sequence in sequences.items():
81
+ consumer = rank, worker
82
+ count = positions.get(consumer, 0)
83
+ mismatch = first_mismatch.get(consumer)
84
+ if mismatch is None and count < len(sequence):
85
+ mismatch = {'index': count, 'expected_id': sequence[count],
86
+ 'observed_id': None}
87
+ if mismatch is not None:
88
+ differences.append({'rank': rank, 'worker': worker,
89
+ 'expected_length': len(sequence),
90
+ 'observed_length': count,
91
+ 'first_difference': mismatch})
92
+ report['schema'] = 'batchscope-ordered-receipts-v1'
93
+ report['status'] = ('MATCHED_ORDERED_RECEIPTS' if not rows and not differences
94
+ else 'ORDERED_RECEIPT_MISMATCH')
95
+ report['order_differences'] = differences
96
+ report['scope'] = ('Conditional on complete supplied receipts in each modeled consumer order. '
97
+ 'No cross-consumer order, provenance, runtime, batch-boundary, content, '
98
+ 'or exactly-once guarantee.')
99
+ return report
@@ -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,12 @@
1
+ batchscope/__init__.py,sha256=fNgYX3ssFqu_7biI8Qhi_pp-6FfY5na2amp5Y2KzOX0,239
2
+ batchscope/__main__.py,sha256=4teds8Eyidl5AmAPY0dQOiQyJheSVSBYQLQRKv8092o,3716
3
+ batchscope/batches.py,sha256=Bd9540Kt9z6U_xdLjn-zKYZLZww5vzSJDZMsLzTc06U,3668
4
+ batchscope/compare.py,sha256=auQ5WE1cu95aZoa4GZTcl-Y-xHmz_iCpAHFbYnnSR8Q,3383
5
+ batchscope/core.py,sha256=MkaIv0hviCRugPcRjBRNSYFypFombysbo6aclAwOftM,7207
6
+ batchscope/receipts.py,sha256=6YfgGjM04ABtyVVvoDXK7cCTCO6l8Ix33qZdXKc3bas,5284
7
+ batchscope-0.1.0.dist-info/licenses/LICENSE,sha256=F2GlKPTe0yGnT_KChkQ7ctLZOPQuC09NR4sR-ic1AUs,1071
8
+ batchscope-0.1.0.dist-info/METADATA,sha256=-gr0hOc6VE2vtlDtkA_NR2pzwxh3dU14ZDQz0EflNnY,16500
9
+ batchscope-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ batchscope-0.1.0.dist-info/entry_points.txt,sha256=KgVxm3_UJcsr_JXTjvVmA4T4HGnObJ1N8Bpix93r5DU,62
11
+ batchscope-0.1.0.dist-info/top_level.txt,sha256=494-3mMhOLQE1G_g86LJ7Nsl-C5ruPs8Hq1WCBsnL_k,11
12
+ batchscope-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ batchscope = batchscope.__main__:entrypoint
@@ -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 @@
1
+ batchscope