Repository navigation
[refactor, perf] Simplify SimpleStorage result mapping - #244
ji-huazhong merged 3 commits into
Conversation
Signed-off-by: ji-huazhong <hzji210@gmail.com>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
0oshowero0
left a comment
There was a problem hiding this comment.
Clean refactor overall — _ReadRow makes get_data much easier to follow, and direct batch-position indexing in _build_update_field_schema is a nice local speedup. Left one fail-fast guard suggestion and a few optional cleanup/test notes inline.
| ordered = shapes[field_name] | ||
| if repeated_positions is not None: | ||
| ordered = [ordered[pos] for pos in repeated_positions] | ||
| is_nested = len(set(ordered)) > 1 |
There was a problem hiding this comment.
Pre-allocating [None] * len(global_indexes) silently loses the previous fail-fast KeyError if any routed storage unit omits a field (or returns an empty stored_shapes dict via reply.meta.get("stored_shapes", {})).
With the current code, unfilled slots stay None, causing len(set(ordered)) > 1 to treat None as a shape and publish is_nested=True, per_sample_shapes=[..., None, ...] to the controller instead of failing fast.
Checking that every position was populated before computing is_nested restores the fail-fast invariant at negligible cost (and narrows tuple | None to tuple):
ordered = shapes[field_name]
if None in ordered:
raise ValueError(f"Missing stored shape for field {field_name!r}")
if repeated_positions is not None:
ordered = [ordered[pos] for pos in repeated_positions]| requests = [] | ||
| for fields, rows in rows_by_fields.items(): | ||
| routing = self._group_by_hash([row.global_index for row in rows]) | ||
| for su_id, group in routing.items(): | ||
| requests.append((su_id, fields, [rows[p] for p in group.batch_positions])) | ||
|
|
||
| tasks = [ | ||
| self._get_from_single_storage_unit( | ||
| group.global_indexes, | ||
| [row.global_index for row in rows], | ||
| list(fields), | ||
| target_storage_unit=su_id, | ||
| data_parser=data_parser, | ||
| parser_args=None if parser_args is None else [args_by_fields[fields][p] for p in group.batch_positions], | ||
| parser_args=None if parser_args is None else [row.parser_arg for row in rows], | ||
| ) | ||
| for su_id, fields, group in requests | ||
| for su_id, fields, rows in requests | ||
| ] |
There was a problem hiding this comment.
Minor cleanup: _group_by_hash already computes group.global_indexes, which gets discarded when building requests and immediately rebuilt via [row.global_index for row in rows] when building tasks.
Building tasks directly in the routing loop lets us reuse group.global_indexes and keep only (fields, unit_rows) for result assembly, avoiding the redundant list comprehension and carrying one fewer element in requests:
requests = []
tasks = []
for fields, rows in rows_by_fields.items():
routing = self._group_by_hash([row.global_index for row in rows])
for su_id, group in routing.items():
unit_rows = [rows[p] for p in group.batch_positions]
requests.append((fields, unit_rows))
tasks.append(
self._get_from_single_storage_unit(
group.global_indexes,
list(fields),
target_storage_unit=su_id,
data_parser=data_parser,
parser_args=None if parser_args is None else [row.parser_arg for row in unit_rows],
)
)(Then result assembly below can unpack for (fields, rows), (_, su_data) in zip(requests, results, strict=True):.)
| for i, row in enumerate(rows): | ||
| value = su_data[field][i] | ||
| for pos in destinations[fields][row]: | ||
| for pos in row.output_positions: | ||
| ordered_data[field][pos] = value |
There was a problem hiding this comment.
Optional nit: using zip(..., strict=True) here is slightly cleaner and also catches any unexpected length mismatch between rows and su_data[field]:
for row, value in zip(rows, su_data[field], strict=True):
for pos in row.output_positions:
ordered_data[field][pos] = value| values = [torch.tensor([20]), torch.tensor([30, 31]), torch.tensor([40, 41, 42])] | ||
| scores = torch.tensor([[20, 21], [30, 31], [40, 41]]) | ||
|
|
||
| updated = client.update( | ||
| metadata, | ||
| TensorDict( | ||
| {"tokens": torch.nested.as_nested_tensor(values, layout=torch.jagged), "score": scores}, batch_size=3 | ||
| ), | ||
| lambda old, new: new, | ||
| plan, | ||
| ) | ||
|
|
||
| assert updated.field_schema["tokens"]["per_sample_shapes"] == [(3,), (2,), (3,)] | ||
| assert updated.field_schema["tokens"]["shape"] is None |
There was a problem hiding this comment.
Optional test suggestion: here tokens has shapes [(1,), (2,), (3,)] -> [(3,), (2,), (3,)], which stays is_nested=True both before and after remapping repeated_positions.
It would be nice to also cover the case where an earlier occurrence of a repeated row has a different shape, while the last write makes the stored column uniform (e.g., [(1,), (2,), (2,)] -> [(2,), (2,), (2,)] yielding is_nested=False, shape=(2,)), which specifically exercises applying repeated_positions before computing is_nested.
| tq.kv_batch_put( | ||
| keys, PARTITION, fields=TensorDict({"response": torch.arange(len(keys)).unsqueeze(1)}, batch_size=len(keys)) | ||
| ) | ||
| tq.kv_put("own", PARTITION, fields={"prompt": _prompt(20), "response": torch.tensor([len(keys)])}) |
There was a problem hiding this comment.
Optional test suggestion: because each response tensor currently has length 1 while lengths are in {1, 2, 3}, slicing value[:length] always returns the entire tensor regardless of which parser_arg an own row receives (and "own" itself only appears once in order).
Making response length >= 3 (e.g., matching _prompt's 3-element layout) and asserting the sliced response values would verify per-occurrence parser_args alignment on repeated own rows (such as key index 4 appearing with lengths 1 and 3) as well.
Signed-off-by: ji-huazhong <hzji210@gmail.com>
Signed-off-by: ji-huazhong <hzji210@gmail.com>
Problem
SimpleStorage GET keeps source rows, parser arguments, and output destinations in separate dictionaries. After grouping by storage unit, result assembly follows another position lookup through those dictionaries. Keeping these structures aligned makes reordered requests, repeated keys, and linked fields harder to trace.
UPDATE already knows each unit's positions in the original batch, but builds a global-index dictionary for every field and then reconstructs the requested shape order. This adds temporary allocations and repeated lookups.
Implementation
_ReadMapping. Build read tasks while routing, reusing each unit's indexes, and carry the mappings through to result assembly.Tests
Extend existing real-storage tests to cover mixed own and linked fields, reordered and repeated GET keys with per-key parser arguments, and reordered multi-field updates across storage units. Both own and linked values have enough elements to make incorrectly aligned slicing arguments observable.
Add one native metadata-update regression that checks both the returned schema and stored values when a row occurs more than once. It covers both a column that remains ragged and one that becomes uniform after the final write. This covers different behavior from the existing KV tests that reject duplicate update keys.
Remove two private-helper tests for shape ordering and uniform-column schemas: their assertions are now covered through real updates and returned metadata. The number of test functions decreases by one.
python -m compileall -q transfer_queue tutorial tests: passed.The full local suite reports 1004 passed, 16 skipped, 1 failed, and 6 setup errors. The remaining failures match the previously recorded order-sensitive
test_opt_out_keeps_the_process_alive_for_inspectionfailure and six Yuanrong fixture setup errors without the optionaldatasystemSDK. The worker-exit test previously passed in isolation. All modified tests pass in the full suite and the focused runs above.Performance
Compared with main at
5f9fb8b, local CPU measurements of UPDATE schema assembly for 4,096 samples across four units gave:Times are medians of seven alternating blocks of 100 calls per implementation; allocation peaks were measured separately with
tracemalloc.A separate 12-block alternating comparison of complete requests through two local SimpleStorage units over real ZMQ used 4,096 samples, eight fields, and three calls per block. Median GET latency was 520.55 -> 555.61 ms (+6.7%); UPDATE was 185.61 -> 175.66 ms (-5.4%). These results support a local schema-assembly improvement; they do not establish a training-throughput gain.