You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Append to the cache of a dataset without shape without copying it - #8785
For a dataset without a shape, _insert_into_data_dict appended each result to the cache with np.append, which copies all data collected so far. The time of add_result therefore grew with the length of the run, and a run of N results copied O(N²) data. This applies to DataSet and DataSetInMem alike, since both fill the cache.
Measured with two array parameters of 16384 values and one setpoint array per result (a scope recording), median time of add_result:
Result
DataSetInMem before
DataSet before
DataSetInMem after
DataSet after
0
4.4 ms
4.4 ms
0.3 ms
0.8 ms
400
70 ms
76 ms
0.3 ms
0.4 ms
750
128 ms
120 ms
0.3 ms
0.4 ms
On a Red Pitaya scope, a recording of 1000 captures went from 7.4 captures/s on average (54 ms per capture at the start, 186 ms after 800) to a constant 19 captures/s, limited by the instrument read.
The cache now stores such arrays as views of the beginning of a larger buffer and appends into its spare rows; a full buffer is replaced by one with 1.5 times the rows required, so the copies amount to a few times the data in total. The arrays returned by cache.data() have the values, dtype and shape np.append gave them.
Appends that np.append would promote to another dtype or another shape after the first axis, and arrays of objects, still go through np.append.
Only the array _append_rows returned last for a buffer is extended in place: a module-level map from the id of each buffer to a weak reference to that array (removed by weakref.finalize when the buffer is collected) identifies it. Any other array is copied, whatever its base, layout or dtype: arrays passed to add_result, which may themselves be views of a larger array, other views of a buffer (transposed, reinterpreted, strided), and an array that two caches share, once the first of them has appended.
The shaped path is unchanged.
The cache takes up to 1.5 times the memory of its data.
Tests:
test_cache_append_without_shape_does_not_copy_collected_data (DataSet and DataSetInMem): 100 appends copy the data at most 12 times; it fails without the change (99 copies).
test_cache_append_without_shape_promotes_dtype_and_keeps_input_arrays: an integer column followed by floats becomes float64 as with np.append, and an array whose views were passed as values is left unchanged (add_result copies the values, so the check of _append_rows is tested on its own below).
test_append_rows_does_not_write_to_arrays_it_did_not_allocate: _append_rows with the first rows of an array it did not allocate, with spare rows behind them, leaves that array unchanged and returns the result of np.append.
test_append_rows_extends_only_the_array_it_returned_last (transposed, reinterpreted and strided view of a buffer, each with the buffer's first address and as many rows as are filled): the result equals that of np.append; all three fail with the earlier comparison of layouts.
test_append_rows_extends_a_shared_array_only_once: of two appends to the same array, only the first uses the spare rows behind it; the second copies, and the shared array is unchanged.
The existing tests in tests/dataset/test_data_set_cache.py, which compare the cache with the database for many layouts, pass.
Without a shape, _insert_into_data_dict appended each result with np.append,
which copies all data collected so far, so the time of add_result grew with
the length of the run. With two arrays of 16384 values per result, add_result
took 4 ms at the start and 128 ms after 750 results, for DataSet and
DataSetInMem alike.
The cache now stores such arrays as views of the beginning of a larger
buffer and appends into its spare rows; a full buffer is replaced by one of
1.5 times the rows required. Appends that np.append would promote to another
dtype or shape, and arrays of objects, still go through np.append. Arrays
passed to add_result are never written to.
Our lab's bench software is built on QCoDeS. It records oscilloscope traces (a Red Pitaya scope, 2 × 16384 samples per capture) as runs. Each capture is one add_result on a Measurement: the capture number, the time since the first capture, the time axis and both traces as paramtype="array". A recording is either a set number of captures or runs until the operator stops it, which can mean thousands of captures. It is stored either as a DataSetInMem, exported to NetCDF at the end, or crash-safe as a DataSet.
Long recordings got slower and slower: 47 ms per capture at the start, 265 ms after 1300 captures. We traced that to the np.append in _insert_into_data_dict.
We looked at declaring a shape with Measurement.set_shapes(), which avoids the copy, but it doesn't fit this case:
A recording that runs until stopped has no number of captures to declare.
A DataSetInMem that stops before its shape is filled cannot be exported. export() raises ValueError: Dependency 'x' does not define an axis of length 10: found 4 unique values, so an aborted in-memory recording would lose its data.
A shape preallocates, and fills with NaN, the full size of the run at the start.
So unshaped runs are the normal case for this kind of acquisition. Until a release contains this change, we install the same append as a replacement for _insert_into_data_dict in our own code. We would much rather drop that.
A related observation, outside this PR: in the crash-safe DataSet, the cache keeps a second copy of everything already written to the database. With this change it no longer costs time, but it still grows with the run, about 1 GB after 1300 captures of two traces. For these runs we read the data back from the database or the exported NetCDF, and nothing reads the cache. (In a DataSetInMem the cache is the data, of course.) Would an opt-in setting to not keep a cache for a DataSet be welcome as a separate PR?
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The fixed 16-row minimum exceeds the stated 1.5× memory bound and can cause allocation failures, while the ownership regression test does not actually exercise caller-buffer protection.
✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.31%. Comparing base (29fe8a6) to head (ccda459). ⚠️ Report is 93 commits behind head on main.
The minimum was a deliberate trade of memory for speed: spare rows at the start of a run in exchange for fewer buffer replacements. We now measured whether the trade pays off, and decided against it. The floor is therefore dropped and a const. x1.5 buffer size is used.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
DataSaver.add_result copies each value with np.array, so the test through
Measurement never passes a view of the caller's array to the cache and
holds with or without the ownership check of _append_rows.
The new test calls _append_rows with the first rows of an array that it
did not allocate, with spare rows behind them, and asserts that the whole
array is unchanged. It fails if the check on _buffer_rows is removed.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The append fast path can silently change stored values when reusing incompatible buffer views and raise an uncaught UnicodeDecodeError instead of reaching the object-array fallback.
Catch fast-path assignment errors to allow fallback
src/qcodes/dataset/data_set_cache.py:483
Appending np.array([b'\xff']) after np.array(['a']) passes the fast-path dtype check but raises UnicodeDecodeError during assignment. Because _append_rows is outside the try, this supported array-parameter input now fails instead of reaching the existing object-array fallback. Move the fast-path call inside the same try.
The check before writing into spare rows compared the base, the number of
filled rows, the shape after the first axis and the first address. A
transposed or dtype-reinterpreted view of a buffer, or one with a step
along the first axis, can match all of these while having another layout;
the append then returned the buffer's rows in the buffer's layout and
silently changed the values stored before. Such a view reaches the cache
through add_data, which stores an array passed to an empty cache as it is.
_append_rows now keeps a weak reference to the array it returned last for
each buffer and extends only that array in place; any other array is
copied, whatever its base, layout or dtype. This replaces the row count
and the comparisons of address and shape. Of an array that two caches
share, only the first to append uses the spare rows.
The test of views fails without the change for all three views.
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
For a dataset without a shape,
_insert_into_data_dictappended each result to the cache withnp.append, which copies all data collected so far. The time ofadd_resulttherefore grew with the length of the run, and a run of N results copied O(N²) data. This applies toDataSetandDataSetInMemalike, since both fill the cache.Measured with two array parameters of 16384 values and one setpoint array per result (a scope recording), median time of
add_result:DataSetInMembeforeDataSetbeforeDataSetInMemafterDataSetafterOn a Red Pitaya scope, a recording of 1000 captures went from 7.4 captures/s on average (54 ms per capture at the start, 186 ms after 800) to a constant 19 captures/s, limited by the instrument read.
The cache now stores such arrays as views of the beginning of a larger buffer and appends into its spare rows; a full buffer is replaced by one with 1.5 times the rows required, so the copies amount to a few times the data in total. The arrays returned by
cache.data()have the values, dtype and shapenp.appendgave them.np.appendwould promote to another dtype or another shape after the first axis, and arrays of objects, still go throughnp.append._append_rowsreturned last for a buffer is extended in place: a module-level map from the id of each buffer to a weak reference to that array (removed byweakref.finalizewhen the buffer is collected) identifies it. Any other array is copied, whatever its base, layout or dtype: arrays passed toadd_result, which may themselves be views of a larger array, other views of a buffer (transposed, reinterpreted, strided), and an array that two caches share, once the first of them has appended.Tests:
test_cache_append_without_shape_does_not_copy_collected_data(DataSetandDataSetInMem): 100 appends copy the data at most 12 times; it fails without the change (99 copies).test_cache_append_without_shape_promotes_dtype_and_keeps_input_arrays: an integer column followed by floats becomes float64 as withnp.append, and an array whose views were passed as values is left unchanged (add_resultcopies the values, so the check of_append_rowsis tested on its own below).test_append_rows_does_not_write_to_arrays_it_did_not_allocate:_append_rowswith the first rows of an array it did not allocate, with spare rows behind them, leaves that array unchanged and returns the result ofnp.append.test_append_rows_extends_only_the_array_it_returned_last(transposed, reinterpreted and strided view of a buffer, each with the buffer's first address and as many rows as are filled): the result equals that ofnp.append; all three fail with the earlier comparison of layouts.test_append_rows_extends_a_shared_array_only_once: of two appends to the same array, only the first uses the spare rows behind it; the second copies, and the shared array is unchanged.tests/dataset/test_data_set_cache.py, which compare the cache with the database for many layouts, pass.