Read twins: count the copies in a reach of unnamed memory alone compares

A command buffer whose functions reach memory through loaded addresses
(reaches_unnamed) compares every copied host buffer at its commit, also
those no use of it names. Step 3 of the read twins would let such a
command buffer's resident set list each buffer's read twin in its place
where no function may store through an address (writes_unnamed false)
and every use was noted, so its copy in could skip those copies. This
counts what that would spare, before building it.

CopiesReached::reached_unnamed keeps the uses' keys beside "all", so
the copy in tells the copies only the unnamed reach took. WorkCounts
gains copied_unnamed_reach_copy_ins and _bytes_compared (any such reach)
and copied_unnamed_reach_twin_copy_ins and _twin_bytes_compared (reads
only, every use noted, the copy unnamed and twinned). A copy is twinned
from its read twin's making until its buffer lies elsewhere
(HostCell::replace).

Tests: copied::a_reach_of_unnamed_memory_counts_the_copies_it_alone_compares
(the split on plain memory: named, unnamed, twinned, reads only or not,
unnoted) and, on a device,
read_twin_device::a_kernel_reaching_a_private_bit_buffer_unnamed_compares_its_copy_for_that_alone
(ob2_loaded_pointer: one unnamed copy in, no twinned one, pages kept).
This commit is contained in:
Anees Iqbal committed 2026-11-14 03:37:28 -08:00
1 parent fca34185af
commit 8f2804422f
8 files changed
+271 -5

No files matched your search

+14 -2
View File
@@ -646,9 +646,13 @@ impl HostCell {
lay
};
// Its read twins lie over the pages it lay in: taken now, outside the pages' lock, so the
// buffer is its copy alone from now on (`read_twin.rs`).
// buffer is its copy alone from now on (`read_twin.rs`), as the copy it lay in is.
let twin = lock(&self.read_twin).take();
if let (Some(_), Lying::In(pages)) = (&twin, &lay) {
pages.set_copy_twinned(false);
}
let twins = LeftTwins {
_buffer: lock(&self.read_twin).take(),
_buffer: twin,
_textures: lock(&self.twin_textures).drain(..).collect(),
};
(lay, twins)
@@ -1152,6 +1156,14 @@ impl HostPages {
self.import.set_copied(copied);
}
/// Whether a read twin reads them in place, where they lie in a copy of the caller's pages
/// (`copied.rs`'s `Copied::set_twinned`).
pub(super) fn set_copy_twinned(&self, twinned: bool) {
if let Some(copied) = self.import.copied.get() {
copied.set_twinned(twinned);
}
}
/// Keep the caller's log of the writes to them (`dirty_pages.rs`), given with their memory.
pub(super) fn keep_dirty(&self, dirty: Arc<DirtySource>) {
let _kept = self.dirty.set(dirty);
@@ -4124,9 +4124,17 @@ impl CommandBuffer {
let unreached = CopiesAgain::unreached(state.batches.all());
(state.reaches_unnamed, state.writes_unnamed, unreached)
};
match unnoted || reaches {
true => used.reached_all(),
false => self.dirty().copies_used(&mut used),
// A reach of memory no use names compares every copy, its uses' keys kept beside, so
// the copy in counts the copies that reach alone compares, and those a read twin
// reads in place where no function of the command buffer may store through an
// address (`CopiesReached::reached_unnamed`).
match (unnoted, reaches) {
(true, _) => used.reached_all(),
(false, true) => {
self.dirty().copies_used(&mut used);
used.reached_unnamed(!writes);
}
(false, false) => self.dirty().copies_used(&mut used),
}
match unnoted || writes {
true => written.reached_all(),
+54
View File
@@ -242,6 +242,10 @@ pub(crate) struct CopiedBuffers {
pub(crate) struct CopiesReached {
keys: KeyMap<ResourceKey, ()>,
all: bool,
/// Where every copy may have been reached through memory no use names alone
/// ([`reached_unnamed`](Self::reached_unnamed)): the keys stay those the uses named, and
/// whether no function of the command buffer may store through an address.
unnamed: Option<bool>,
}
impl CopiesReached {
@@ -250,6 +254,7 @@ impl CopiesReached {
CopiesReached {
keys: KeyMap::default(),
all: true,
unnamed: None,
}
}
@@ -263,9 +268,29 @@ impl CopiesReached {
/// Some command may have reached a copy no use of it names.
pub(crate) fn reached_all(&mut self) {
self.all = true;
self.unnamed = None;
self.keys.clear();
}
/// Some command may have reached a copy no use of it names through memory no use names (a
/// loaded address), where every use was noted: every copy may have been reached, and the keys
/// the uses named so far stay, so a copy in tells the copies that reach alone compares
/// (`WorkCounts::copied_unnamed_reach_copy_ins`). `reads_only`: no function of the command
/// buffer may store through an address (`State::writes_unnamed`).
pub(crate) fn reached_unnamed(&mut self, reads_only: bool) {
if !self.all {
self.unnamed = Some(reads_only);
}
self.all = true;
}
/// Where the copy whose uses take `keys` was reached through memory no use names alone
/// ([`reached_unnamed`](Self::reached_unnamed)): whether that reach only reads.
fn unnamed_alone(&self, keys: &[(ResourceKey, usize)]) -> Option<bool> {
let named = keys.iter().any(|(key, _)| self.keys.contains_key(key));
self.unnamed.filter(|_| !named)
}
/// Whether a command may have reached the copy whose uses take `keys`.
fn meets(&self, keys: &[(ResourceKey, usize)]) -> bool {
self.all || keys.iter().any(|(key, _)| self.keys.contains_key(key))
@@ -344,6 +369,10 @@ struct Entry {
/// a rebind. A key goes with the last pages that named it ([`Copied::unname`]), so the keys are
/// those of the buffers lying in the copy now, however many came and went.
keys: Vec<(ResourceKey, usize)>,
/// A read twin reads the copy's pages in place while its buffer lies in it (`read_twin.rs`,
/// [`Copied::set_twinned`]): counted where a command buffer's reach of memory no use names
/// alone compares the copy (`WorkCounts::copied_unnamed_reach_twin_copy_ins`).
twinned: bool,
}
/// A copy's logs of its pages, and its writer in them.
@@ -1107,6 +1136,15 @@ impl Copied {
}
}
/// Whether a read twin reads the copy's pages in place (`read_twin.rs`): from its making, until
/// its buffer lies elsewhere.
pub(crate) fn set_twinned(&self, twinned: bool) {
let mut entries = lock(&self.buffers.entries);
if let Some(entry) = entries.iter_mut().find(|entry| entry.id == self.id) {
entry.twinned = twinned;
}
}
/// Pages that named `key` ([`Copied::name`]) went: no command writes the copy through them
/// from now on, as every command buffer that used them completed, its batches' writes merged
/// back first (`command_buffer/completion.rs`). The key goes with the last such pages.
@@ -1244,6 +1282,7 @@ impl CopiedBuffers {
drops_writes,
log: None,
keys: Vec::new(),
twinned: false,
});
self.live.fetch_add(1, Ordering::Relaxed);
if let Some(log) = &self.log {
@@ -1297,6 +1336,11 @@ impl CopiedBuffers {
/// asked before the stamps: those committed command buffers wrote in place whose writes were
/// not reported as run yet (`DirtyShadows::in_flight`), which the program may know ran (a
/// host wait for an event they signal) before the logs hear it.
///
/// A copy only a reach of memory no use names took ([`CopiesReached::reached_unnamed`]) is
/// counted apart, and so is one of them a read twin reads in place where that reach only reads
/// (`WorkCounts::copied_unnamed_reach_copy_ins`, `copied_unnamed_reach_twin_copy_ins`): what a
/// resident set listing the twins in their buffers' place would leave uncompared.
pub(crate) fn copy_in(
&self,
counts: &Counters,
@@ -1331,6 +1375,9 @@ impl CopiedBuffers {
let (mut moved, mut skipped, mut unused, mut read) = (0u64, 0u64, 0u64, 0u64);
let (mut made, mut refused, mut started, mut read_back) = (0u64, 0u64, 0u64, 0u64);
let (mut copies, mut bytes_compared) = (0u64, 0u64);
// The copies a reach of memory no use names alone compared, and those of them a read twin
// reads in place where that reach only reads: copies and bytes.
let (mut unnamed, mut twinned) = ((0u64, 0u64), (0u64, 0u64));
for entry in lock(&self.entries).iter_mut() {
if !reaches(entry) {
unused += 1;
@@ -1388,6 +1435,12 @@ impl CopiedBuffers {
}
bytes_compared += compared;
skipped += length as u64 - compared;
if let Some(reads_only) = used.unnamed_alone(&entry.keys) {
unnamed = (unnamed.0 + 1, unnamed.1 + compared);
if reads_only && entry.twinned {
twinned = (twinned.0 + 1, twinned.1 + compared);
}
}
if let (Some(log), Some(plan)) = (&mut entry.log, plan) {
log.since = plan.stamps.clone();
log.merged = 0;
@@ -1413,6 +1466,7 @@ impl CopiedBuffers {
counts.copied_copy_in_skipped(skipped);
counts.copied_copy_ins_unused(unused);
counts.copied_copy_ins_compared(copies, bytes_compared);
counts.copied_unnamed_reach(unnamed, twinned);
counts.copied_bases(made, refused, read);
counts.copied_base_blocks_read_back(read_back);
counts.copied_compare_threads(started);
@@ -162,6 +162,9 @@ impl Device {
}
(shared.owners).read_twin(&twin, of, shared.counts.submissions_made());
cell.keep_read_twin(twin);
// Its copy is read in place through the twin, which a reach of memory no use names does
// not take (`WorkCounts::copied_unnamed_reach_twin_copy_ins`).
pages.set_copy_twinned(true);
shared.counts.read_twin_made();
}
}
@@ -1228,6 +1228,79 @@ fn a_merge_back_compares_only_the_copies_its_batches_wrote() {
drop((x, y));
}
/// A commit whose command buffer reached memory no use names (`CopiesReached::reached_unnamed`)
/// compares every copy, and counts apart the copies none of its uses named, and of them those a
/// read twin reads in place where no function of the command buffer may store through an
/// address: copies in, then bytes.
#[test]
fn a_reach_of_unnamed_memory_counts_the_copies_it_alone_compares() {
let length = 4096;
let buffers = Arc::new(CopiedBuffers::default());
let counts = Counters::default();
let mut pages = [vec![1_u8; length], vec![2_u8; length], vec![3_u8; length]];
let mut copies = [vec![0_u8; length], vec![0_u8; length], vec![0_u8; length]];
let made: Vec<Copied> = (0..3)
.map(|i| {
// SAFETY: the copies and the pages are the test's, of `length` bytes, live past the
// answers.
let added = unsafe {
add_reading(
&buffers,
at(&mut pages[i]),
at(&mut copies[i]),
length,
plain,
false,
)
};
added.unwrap()
})
.collect();
let keys = [ResourceKey::new(), ResourceKey::new(), ResourceKey::new()];
for (copied, key) in made.iter().zip(keys) {
copied.name(key);
}
// A read twin reads the second copy's pages in place.
made[1].set_twinned(true);
// The first copy named by a use, the others reached unnamed alone.
let reach = |reads_only: bool| {
let mut used = CopiesReached::default();
used.reached(keys[0]);
used.reached_unnamed(reads_only);
used
};
let unnamed = |counts: &Counters| {
let tallies = counts.copied_tallies();
[
tallies.unnamed_reach_copy_ins,
tallies.unnamed_reach_bytes,
tallies.unnamed_reach_twin_copy_ins,
tallies.unnamed_reach_twin_bytes,
]
};
let length = length as u64;
let none = CopiesReached::default();
commit(&buffers, &counts, &reach(true), &none);
assert_eq!(unnamed(&counts), [1, 2 * length, 1, length]);
// A reach by a function that may store through an address: no twin could serve it.
commit(&buffers, &counts, &reach(false), &CopiesReached::all());
assert_eq!(unnamed(&counts), [2, 4 * length, 1, length]);
// Its buffer lying elsewhere, the copy has no twin any more.
made[1].set_twinned(false);
commit(&buffers, &counts, &reach(true), &none);
assert_eq!(unnamed(&counts), [3, 6 * length, 1, length]);
// Every copy reached otherwise (uses unnoted), or named: nothing counted apart.
commit(&buffers, &counts, &CopiesReached::all(), &none);
let mut named = CopiesReached::default();
for key in keys {
named.reached(key);
}
named.reached_unnamed(true);
commit(&buffers, &counts, &named, &none);
assert_eq!(unnamed(&counts), [3, 6 * length, 1, length]);
drop(made);
}
/// A commit's copy in takes the CPU's writes into the copies its command buffer's commands use
/// alone (`CopiesReached`), every copy where one may reach memory no use names: a copy left alone
/// keeps what it agreed on, and the first commit that uses it takes every write since.
@@ -438,6 +438,66 @@ fn every_store_into_a_private_bit_buffer_leaves_its_pages() {
drop((buffer, source, state, queue));
}
/// A command buffer whose kernel reaches a buffer of bit 24 only through its address loaded from
/// memory compares the buffer's copy for that reach alone (`copied_unnamed_reach_copy_ins`, and
/// its bytes); a kernel may store through an address, so no read twin could serve
/// that reach (`copied_unnamed_reach_twin_copy_ins` unchanged), and its stores leave the pages.
#[test]
fn a_kernel_reaching_a_private_bit_buffer_unnamed_compares_its_copy_for_that_alone() {
let pages = Pages::new(SMALL, 53);
let Some(device) = device(None) else {
return;
};
let buffer = pages.private_bit_buffer(&device, None);
assert!(buffer.read_twin().is_some(), "a twin made");
// A command buffer's use of it: the device's live buffers list it, reached unnamed from here.
assert!(gpu_bytes(&device, &buffer, SMALL) == pages.bytes());
// A CPU write, so the copy in compares bytes whatever its pages' log reports.
pages.write(SMALL / 2, &[0x5a; 16]);
let kept = pages.bytes();
let function = super::encoder_holds::library(&device, "engine/ob2_loaded_pointer.ll")
.new_function_with_name("ob2_loaded_pointer")
.unwrap();
let state = device
.new_compute_pipeline_state_with_function(&function, &crate::PipelineOptions::default())
.unwrap();
let indices: Vec<u8> = (0..16u32).flat_map(u32::to_le_bytes).collect();
let out = own(&device, SMALL);
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&state).unwrap();
encoder.set_bytes(&indices, 0).unwrap();
encoder
.set_bytes(&buffer.gpu_address().0.to_le_bytes(), 1)
.unwrap();
encoder.set_buffer(Some(&out), 0, 2).unwrap();
encoder
.dispatch_threads(Size::new(8, 1, 1), Size::new(8, 1, 1))
.unwrap();
encoder.end_encoding().unwrap();
let before = device.work_counts();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
let after = device.work_counts();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let counted = [
after.copied_unnamed_reach_copy_ins - before.copied_unnamed_reach_copy_ins,
after.copied_unnamed_reach_bytes_compared - before.copied_unnamed_reach_bytes_compared,
after.copied_unnamed_reach_twin_copy_ins - before.copied_unnamed_reach_twin_copy_ins,
after.copied_unnamed_reach_twin_bytes_compared
- before.copied_unnamed_reach_twin_bytes_compared,
];
eprintln!(
"READ-TWIN: a kernel reaching a buffer of bit 24 unnamed: copies in for that reach alone \
[copy ins, bytes, twinned copy ins, twinned bytes] {counted:?}"
);
assert_eq!([counted[0], counted[2], counted[3]], [1, 0, 0]);
assert!((1..=SMALL as u64).contains(&counted[1]), "{counted:?}");
assert!(pages.bytes() == kept, "a kernel's stores leave the pages");
drop((buffer, out, state, queue));
}
#[test]
fn a_write_of_the_twin_itself_is_refused_and_would_reach_the_pages() {
let pages = Pages::new(SMALL, 7);
@@ -51,6 +51,10 @@ pub(crate) struct CopiedTallies {
pub(crate) base_blocks_read: u64,
pub(crate) base_blocks_read_back: u64,
pub(crate) compare_threads: u64,
pub(crate) unnamed_reach_copy_ins: u64,
pub(crate) unnamed_reach_bytes: u64,
pub(crate) unnamed_reach_twin_copy_ins: u64,
pub(crate) unnamed_reach_twin_bytes: u64,
}
/// A device's counters (`DeviceShared::counts`), each only ever added to.
@@ -484,6 +488,10 @@ pub(crate) struct Counters {
copied_compare_threads: AtomicU64,
copied_copy_ins_compared: AtomicU64,
copied_copy_in_bytes_compared: AtomicU64,
copied_unnamed_reach_copy_ins: AtomicU64,
copied_unnamed_reach_bytes_compared: AtomicU64,
copied_unnamed_reach_twin_copy_ins: AtomicU64,
copied_unnamed_reach_twin_bytes_compared: AtomicU64,
read_twins_made: AtomicU64,
read_twins_unimported: AtomicU64,
read_twins_uncontained: AtomicU64,
@@ -4445,6 +4453,10 @@ impl Counters {
base_blocks_read: load(&self.copied_base_blocks_read),
base_blocks_read_back: load(&self.copied_base_blocks_read_back),
compare_threads: load(&self.copied_compare_threads),
unnamed_reach_copy_ins: load(&self.copied_unnamed_reach_copy_ins),
unnamed_reach_bytes: load(&self.copied_unnamed_reach_bytes_compared),
unnamed_reach_twin_copy_ins: load(&self.copied_unnamed_reach_twin_copy_ins),
unnamed_reach_twin_bytes: load(&self.copied_unnamed_reach_twin_bytes_compared),
}
}
@@ -4478,6 +4490,21 @@ impl Counters {
(self.copied_copy_in_bytes_compared).fetch_add(bytes, Ordering::Relaxed);
}
/// A copy in compared `unnamed` (copies, bytes) that its command buffer's reach of memory no
/// use names alone took, and of them `twinned` that a read twin reads in place where that
/// reach only reads (`copied.rs`): each counts the copy in once where it compared any.
pub(crate) fn copied_unnamed_reach(&self, unnamed: (u64, u64), twinned: (u64, u64)) {
if unnamed.0 > 0 {
(self.copied_unnamed_reach_copy_ins).fetch_add(1, Ordering::Relaxed);
(self.copied_unnamed_reach_bytes_compared).fetch_add(unnamed.1, Ordering::Relaxed);
}
if twinned.0 > 0 {
(self.copied_unnamed_reach_twin_copy_ins).fetch_add(1, Ordering::Relaxed);
let bytes = &self.copied_unnamed_reach_twin_bytes_compared;
bytes.fetch_add(twinned.1, Ordering::Relaxed);
}
}
/// A read twin was made for a no-copy buffer whose GPU writes are dropped (`read_twin.rs`).
pub(crate) fn read_twin_made(&self) {
(self.read_twins_made).fetch_add(1, Ordering::Relaxed);
@@ -9116,6 +9143,22 @@ pub struct WorkCounts {
/// byte of a copy compared, but those its pages' log reported unwritten
/// (`copied_copy_in_bytes_skipped`).
pub copied_copy_in_bytes_compared: u64,
/// The copies in (at a commit, or again after an event wait) whose command buffer reached
/// memory no use names (a root table's loaded addresses) and compared a copied host buffer
/// no use of it named: one per copy in, whatever the copies it compared so.
pub copied_unnamed_reach_copy_ins: u64,
/// The bytes those copies in compared of the copies no use named
/// (`copied_unnamed_reach_copy_ins`): a part of `copied_copy_in_bytes_compared`.
pub copied_unnamed_reach_bytes_compared: u64,
/// Of `copied_unnamed_reach_copy_ins`, those whose command buffer had every use noted and no
/// function that may store through an address (`State::writes_unnamed`), and compared a copy
/// no use named of a no-copy buffer of Metal's private option bit 24 with a read twin
/// (`read_twin.rs`): those a resident set listing the twins in their buffers' place would
/// spare that copy.
pub copied_unnamed_reach_twin_copy_ins: u64,
/// The bytes those copies in compared of such twinned copies
/// (`copied_unnamed_reach_twin_copy_ins`): a part of `copied_unnamed_reach_bytes_compared`.
pub copied_unnamed_reach_twin_bytes_compared: u64,
/// The read twins made (`read_twin.rs`): of a no-copy buffer of Metal's private option bit
/// 24 where the system maps no read-only view of its pages, the runtime's own buffer over the
/// pages in place, which the commands that cannot write the buffer read instead of its copy.
@@ -11624,6 +11667,15 @@ impl Device {
copied_copy_ins_compared: counters.copied_copy_ins_compared.load(Ordering::Relaxed),
copied_copy_in_bytes_compared: (counters.copied_copy_in_bytes_compared)
.load(Ordering::Relaxed),
copied_unnamed_reach_copy_ins: (counters.copied_unnamed_reach_copy_ins)
.load(Ordering::Relaxed),
copied_unnamed_reach_bytes_compared: (counters.copied_unnamed_reach_bytes_compared)
.load(Ordering::Relaxed),
copied_unnamed_reach_twin_copy_ins: (counters.copied_unnamed_reach_twin_copy_ins)
.load(Ordering::Relaxed),
copied_unnamed_reach_twin_bytes_compared: (counters
.copied_unnamed_reach_twin_bytes_compared)
.load(Ordering::Relaxed),
read_twins_made: counters.read_twins_made.load(Ordering::Relaxed),
read_twins_unimported: counters.read_twins_unimported.load(Ordering::Relaxed),
read_twins_uncontained: counters.read_twins_uncontained.load(Ordering::Relaxed),
@@ -2813,6 +2813,10 @@ field metal2vulkan-runtime::WorkCounts.copied_rebind_images_made pub copied_rebi
field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_made pub copied_rebind_pages_made: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_moved pub copied_rebind_pages_moved: u64
field metal2vulkan-runtime::WorkCounts.copied_textures_in_place pub copied_textures_in_place: u64
field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_bytes_compared pub copied_unnamed_reach_bytes_compared: u64
field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_copy_ins pub copied_unnamed_reach_copy_ins: u64
field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_twin_bytes_compared pub copied_unnamed_reach_twin_bytes_compared: u64
field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_twin_copy_ins pub copied_unnamed_reach_twin_copy_ins: u64
field metal2vulkan-runtime::WorkCounts.copied_unwritable_pages pub copied_unwritable_pages: u64
field metal2vulkan-runtime::WorkCounts.copy_regions_split pub copy_regions_split: u64
field metal2vulkan-runtime::WorkCounts.copy_sites pub copy_sites: [CopySite; 32]
Can't render this file because it is too large.