mirror of
https://github.com/gorules/zen.git
synced 2026-11-29 08:06:51 +00:00
perf: learned row dedup for typed groups
Typed groups without list inputs (graph: 16+ local rows, not already on the long-program dedup; policy: root groups) learn per group whether to run the program on distinct input rows only: warm-up, a deferred probe of the coded run, then a measured trial against the plain run, repeated every 64 calls. Rows are keyed by exact value codes (table hints, Dict keys, numbers by mantissa and scale, text through Coder::keys, cached per call in the graph store). Graph outputs stay dict-coded (reps plus ids through widen/expand); policy spreads rep outputs back to rows (Outputs::spread) because its sinks take row-shaped outputs.
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
use super::list::Frame;
|
||||
use super::switch::{Cost, Path};
|
||||
use crate::compiled::leaf::{Bits, Leaf};
|
||||
use crate::compiled::shred::Listing;
|
||||
use crate::compiled::shred::{Coder, Listing};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use zen_expression::lane::{Column, Values};
|
||||
use zen_expression::typed::{Batch, Outputs, Program};
|
||||
|
||||
@@ -22,8 +24,29 @@ pub(crate) struct TypedCall<'l, 'a> {
|
||||
|
||||
pub(crate) struct Select;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
|
||||
enum Rows {
|
||||
#[default]
|
||||
Plain,
|
||||
Coded,
|
||||
Warm,
|
||||
Probe,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct Choice {
|
||||
rows: Rows,
|
||||
spent: Duration,
|
||||
}
|
||||
|
||||
pub(crate) struct Dedup {
|
||||
sparse: AtomicU32,
|
||||
calls: AtomicU32,
|
||||
plain: AtomicU64,
|
||||
part: AtomicU64,
|
||||
coded: AtomicU64,
|
||||
trial: AtomicBool,
|
||||
pending: AtomicBool,
|
||||
}
|
||||
|
||||
impl TypedCall<'_, '_> {
|
||||
@@ -59,9 +82,136 @@ impl Select {
|
||||
impl Dedup {
|
||||
const SPARSE: u32 = 16;
|
||||
const LONG: usize = 24;
|
||||
const PERIOD: u32 = 64;
|
||||
const MIN: usize = 16;
|
||||
const MARGIN: u64 = 4;
|
||||
const FAILED: u64 = u64::MAX - 1;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self { sparse: AtomicU32::new(0) }
|
||||
Self {
|
||||
sparse: AtomicU32::new(0),
|
||||
calls: AtomicU32::new(0),
|
||||
plain: AtomicU64::new(0),
|
||||
part: AtomicU64::new(u64::MAX),
|
||||
coded: AtomicU64::new(u64::MAX),
|
||||
trial: AtomicBool::new(false),
|
||||
pending: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn rows(&self) -> Rows {
|
||||
let call = self.calls.fetch_add(1, Ordering::Relaxed);
|
||||
let coded = self.coded.load(Ordering::Relaxed);
|
||||
match call % Self::PERIOD {
|
||||
0 if call == 0 => Rows::Warm,
|
||||
1 if call > 1 || coded != Self::FAILED => Rows::Probe,
|
||||
_ if coded < self.plain.load(Ordering::Relaxed) => Rows::Coded,
|
||||
_ => Rows::Plain,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn choose<C, T>(&self, cx: &mut C, local: usize, plain: impl FnOnce(&mut C) -> Option<T>, coded: impl FnOnce(&mut C) -> Option<T>) -> (Option<T>, Choice) {
|
||||
let rows = match local >= Self::MIN {
|
||||
true => self.rows(),
|
||||
false => Rows::Plain,
|
||||
};
|
||||
let choice = |rows: Rows, spent: Duration| Choice { rows, spent };
|
||||
match rows {
|
||||
Rows::Plain => (plain(cx), Choice::default()),
|
||||
Rows::Coded => match coded(cx) {
|
||||
Some(out) => (Some(out), choice(Rows::Coded, Duration::ZERO)),
|
||||
None => {
|
||||
self.coded.store(u64::MAX, Ordering::Relaxed);
|
||||
self.trial.store(false, Ordering::Relaxed);
|
||||
(plain(cx), Choice::default())
|
||||
}
|
||||
},
|
||||
Rows::Warm => {
|
||||
let out = plain(cx);
|
||||
let begin = Instant::now();
|
||||
if out.is_some() && coded(cx).is_none() {
|
||||
self.coded.store(Self::FAILED, Ordering::Relaxed);
|
||||
}
|
||||
(out, choice(Rows::Warm, begin.elapsed()))
|
||||
}
|
||||
Rows::Probe => {
|
||||
let begin = Instant::now();
|
||||
let out = plain(cx);
|
||||
if out.is_some() {
|
||||
self.part.store(Self::per(begin.elapsed(), local), Ordering::Relaxed);
|
||||
self.pending.store(true, Ordering::Relaxed);
|
||||
}
|
||||
(out, choice(Rows::Probe, Duration::ZERO))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn settle(&self, cost: &Cost, path: (Path, bool), choice: Choice, elapsed: Duration, local: usize) {
|
||||
let elapsed = elapsed.saturating_sub(choice.spent);
|
||||
let per = Self::per(elapsed, local);
|
||||
match choice.rows {
|
||||
Rows::Probe => self.plain.store(per, Ordering::Relaxed),
|
||||
Rows::Coded if self.trial.swap(false, Ordering::Relaxed) => {
|
||||
self.coded.store(per, Ordering::Relaxed);
|
||||
cost.typed(per.min(self.plain.load(Ordering::Relaxed)));
|
||||
return;
|
||||
}
|
||||
Rows::Coded => {
|
||||
self.coded.fetch_min(per, Ordering::Relaxed);
|
||||
}
|
||||
Rows::Plain | Rows::Warm => {}
|
||||
}
|
||||
cost.record(path, elapsed, local);
|
||||
}
|
||||
|
||||
pub fn probe<C, T>(&self, cost: &Cost, cx: &mut C, local: usize, coded: impl FnOnce(&mut C) -> Option<T>) {
|
||||
if !self.pending.swap(false, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let begin = Instant::now();
|
||||
let tried = coded(cx).is_some();
|
||||
let part = Self::per(begin.elapsed(), local);
|
||||
let saving = self.part.load(Ordering::Relaxed).saturating_sub(part);
|
||||
match (tried, saving > 0 && saving.saturating_mul(Self::MARGIN) >= self.plain.load(Ordering::Relaxed)) {
|
||||
(true, true) => {
|
||||
self.coded.store(self.plain.load(Ordering::Relaxed).saturating_sub(saving), Ordering::Relaxed);
|
||||
self.trial.store(true, Ordering::Relaxed);
|
||||
cost.credit(saving);
|
||||
}
|
||||
(true, false) => self.coded.store(u64::MAX, Ordering::Relaxed),
|
||||
(false, _) => self.coded.store(Self::FAILED, Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
fn per(elapsed: Duration, rows: usize) -> u64 {
|
||||
u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128).unwrap_or(Self::FAILED)
|
||||
}
|
||||
|
||||
pub fn reps(program: &Program, leaves: &[Leaf], codes: &[Hint], positions: Option<&Rc<[usize]>>, rows: usize) -> Option<(Outputs, Vec<u32>)> {
|
||||
let (reps, ids) = Self::distinct(leaves, codes, positions, rows)?;
|
||||
let picks: Rc<[usize]> = reps.into();
|
||||
let picked: Vec<Leaf> = leaves.iter().map(|leaf| leaf.pick(&picks)).collect();
|
||||
let call = TypedCall {
|
||||
rows: picks.len(),
|
||||
columns: &picked,
|
||||
lists: Vec::new(),
|
||||
select: None,
|
||||
};
|
||||
Some((call.run(program)?, ids))
|
||||
}
|
||||
|
||||
pub fn coded(program: &Program, leaves: &[Leaf], codes: &[Hint], positions: Option<&Rc<[usize]>>, rows: usize) -> Option<Outputs> {
|
||||
let (mut out, ids) = Self::reps(program, leaves, codes, positions, rows)?;
|
||||
out.spread(rows, &ids, positions.map(|p| &p[..])).then_some(out)
|
||||
}
|
||||
|
||||
pub fn codes(column: &Column, rows: usize) -> Hint {
|
||||
match column.values {
|
||||
Values::Scaled { .. } | Values::I64(_) => Self::numbered(column, rows),
|
||||
Values::Text { offsets, data } => Coder::keys(data.as_bytes(), offsets.get(..=rows)?),
|
||||
Values::Utf8 { offsets, data } => Coder::keys(data, offsets.get(..=rows)?),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ready(&self) -> bool {
|
||||
@@ -242,3 +392,79 @@ impl Dedup {
|
||||
Some((codes.into(), count))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Choice, Dedup};
|
||||
use crate::compiled::core::switch::{Cost, Path};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct Spin;
|
||||
|
||||
impl Spin {
|
||||
fn run(micros: u64) -> Option<u64> {
|
||||
let until = Instant::now() + Duration::from_micros(micros);
|
||||
while Instant::now() < until {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
Some(micros)
|
||||
}
|
||||
|
||||
fn call(dedup: &Dedup, cost: &Cost, plain: u64, coded: u64, merged: u64) -> Option<u64> {
|
||||
let start = Instant::now();
|
||||
let (out, choice): (Option<u64>, Choice) = dedup.choose(&mut (), 1024, |_| Self::run(plain), |_| Self::run(coded));
|
||||
Self::run(merged);
|
||||
dedup.settle(cost, (Path::Typed, false), choice, start.elapsed(), 1024);
|
||||
dedup.probe(cost, &mut (), 1024, |_| Self::run(coded));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clearly_cheaper_coded_run_is_tried_and_kept() {
|
||||
let (dedup, cost) = (Dedup::new(), Cost::new());
|
||||
let runs: Vec<Option<u64>> = (0..6).map(|_| Spin::call(&dedup, &cost, 400, 50, 20)).collect();
|
||||
assert_eq!(&runs[..2], &[Some(400), Some(400)]);
|
||||
assert!(runs[2..].iter().all(|run| *run == Some(50)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_coded_trial_that_loses_reverts_to_plain() {
|
||||
let (dedup, cost) = (Dedup::new(), Cost::new());
|
||||
let mut runs: Vec<Option<u64>> = (0..2).map(|_| Spin::call(&dedup, &cost, 400, 50, 20)).collect();
|
||||
let start = Instant::now();
|
||||
let (out, choice) = dedup.choose(&mut (), 1024, |_| Spin::run(400), |_| Spin::run(50));
|
||||
Spin::run(900);
|
||||
dedup.settle(&cost, (Path::Typed, false), choice, start.elapsed(), 1024);
|
||||
runs.push(out);
|
||||
runs.extend((0..3).map(|_| Spin::call(&dedup, &cost, 400, 50, 20)));
|
||||
assert_eq!(runs[2], Some(50));
|
||||
assert!(runs[3..].iter().all(|run| *run == Some(400)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marginal_saving_is_not_tried() {
|
||||
let (dedup, cost) = (Dedup::new(), Cost::new());
|
||||
let runs: Vec<Option<u64>> = (0..6).map(|_| Spin::call(&dedup, &cost, 400, 360, 20)).collect();
|
||||
assert!(runs.iter().all(|run| *run == Some(400)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_warm_up_skips_the_probe() {
|
||||
let (dedup, cost) = (Dedup::new(), Cost::new());
|
||||
let mut tried = 0;
|
||||
for _ in 0..6 {
|
||||
let (out, choice) = dedup.choose(&mut tried, 1024, |_| Some(1), |tried| {
|
||||
*tried += 1;
|
||||
None::<u32>
|
||||
});
|
||||
assert_eq!(out, Some(1));
|
||||
dedup.settle(&cost, (Path::Typed, false), choice, Duration::from_micros(10), 1024);
|
||||
dedup.probe(&cost, &mut tried, 1024, |tried| {
|
||||
*tried += 1;
|
||||
None::<u32>
|
||||
});
|
||||
}
|
||||
assert_eq!(tried, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,16 @@ impl Cost {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn typed(&self, per: u64) {
|
||||
self.typed.store(per, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn credit(&self, saving: u64) {
|
||||
if saving > 0 {
|
||||
let _ = self.typed.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |typed| Some(typed.saturating_sub(saving)));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record(&self, (path, fresh): (Path, bool), elapsed: Duration, rows: usize) {
|
||||
let per = u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128).unwrap_or(u64::MAX - 1);
|
||||
let cell = match path {
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::compiled::graph::plan::{SegPlan, Source};
|
||||
use zen_expression::typed::Outputs;
|
||||
use crate::nodes::NodeError;
|
||||
use crate::compiled::shred::{Listing, Normalizer};
|
||||
use crate::compiled::core::exec::{Dedup, Hint};
|
||||
use crate::compiled::leaf::{Bits, Dict, Leaf, Records};
|
||||
use crate::EvaluationError;
|
||||
use std::rc::Rc;
|
||||
@@ -70,6 +71,7 @@ pub(crate) struct Store<'a> {
|
||||
pub(super) groups: Vec<Group<'a>>,
|
||||
pub(super) hints: Vec<(SlotId, Rc<[i32]>, usize)>,
|
||||
views: Vec<(SlotId, bool, Option<Shown<'a>>)>,
|
||||
codes: Vec<(SlotId, bool, Hint)>,
|
||||
viewed: Vec<(SlotId, M, bool, Leaf<'a>)>,
|
||||
listings: std::cell::RefCell<Vec<Cached<'a>>>,
|
||||
pub(super) counts: (usize, usize),
|
||||
@@ -127,6 +129,7 @@ impl<'a> Store<'a> {
|
||||
groups: Vec::new(),
|
||||
hints: Vec::new(),
|
||||
views: Vec::new(),
|
||||
codes: Vec::new(),
|
||||
viewed: Vec::new(),
|
||||
listings: std::cell::RefCell::new(Vec::new()),
|
||||
counts: (0, 0),
|
||||
@@ -150,6 +153,7 @@ impl<'a> Store<'a> {
|
||||
};
|
||||
self.masked.retain(|(slot, m, _)| kept(*slot, *m));
|
||||
self.views.retain(|(slot, ..)| kept(*slot, M::All));
|
||||
self.codes.retain(|(slot, ..)| kept(*slot, M::All));
|
||||
self.viewed.retain(|(slot, m, ..)| kept(*slot, *m));
|
||||
self.listings.get_mut().retain(|(slot, ..)| kept(*slot, M::All));
|
||||
}
|
||||
@@ -293,6 +297,15 @@ impl<'a> Store<'a> {
|
||||
masked
|
||||
}
|
||||
|
||||
pub(super) fn codes(&mut self, slot: SlotId, code: bool, leaf: &Leaf<'a>) -> Hint {
|
||||
if let Some((.., hint)) = self.codes.iter().find(|(s, c, _)| *s == slot && *c == code) {
|
||||
return hint.clone();
|
||||
}
|
||||
let hint = Dedup::codes(&leaf.column(), self.rows);
|
||||
self.codes.push((slot, code, hint.clone()));
|
||||
hint
|
||||
}
|
||||
|
||||
pub(super) fn viewed(&mut self, seg: &SegPlan, r: Ref, code: bool) -> (Leaf<'a>, Option<Rc<[u64]>>) {
|
||||
let leaf = self.leaf(r.slot);
|
||||
let code = code && matches!(leaf.column().values, Values::Text { .. });
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use crate::compiled::graph::plan::view::{M, SlotId};
|
||||
use crate::compiled::graph::table::{First, Table};
|
||||
use crate::compiled::core::exec::{Hint, ListPart, Select, TypedCall};
|
||||
use crate::compiled::core::exec::{Choice, Dedup, Hint, ListPart, Select, TypedCall};
|
||||
use crate::compiled::core::retry::Take;
|
||||
use crate::compiled::core::switch::{Density, Path};
|
||||
use crate::compiled::graph::plan::typed::{Deferred, Grouping, Piece, Target, TypedOp};
|
||||
use crate::compiled::graph::plan::{Op, SegPlan, TableOp};
|
||||
use zen_expression::typed::{Data as Slotted, Slot};
|
||||
use zen_expression::lane::Values;
|
||||
use zen_expression::typed::{Data as Slotted, Outputs, Slot};
|
||||
use crate::compiled::shred::{Normalizer, Seen};
|
||||
use crate::compiled::leaf::{Bits, Leaf};
|
||||
use crate::compiled::graph::{Body, Kind};
|
||||
@@ -14,6 +15,8 @@ use std::time::Instant;
|
||||
use super::Run;
|
||||
use super::store::{Lowered, Prepared, Store};
|
||||
|
||||
type Held<'a> = (Choice, Vec<Leaf<'a>>, Vec<Hint>);
|
||||
|
||||
impl<'a> Run<'_, 'a> {
|
||||
pub(super) fn deferred(&mut self, seg: &SegPlan, op: &Deferred, units: &[Op], positions: Option<&Rc<[usize]>>) {
|
||||
let rows = self.store.rows;
|
||||
@@ -68,14 +71,17 @@ impl<'a> Run<'_, 'a> {
|
||||
}
|
||||
let path = op.cost.path();
|
||||
let start = Instant::now();
|
||||
let mut held: Held<'a> = (Choice::default(), Vec::new(), Vec::new());
|
||||
let typed = match path.0 {
|
||||
Path::Typed => self.lowered(seg, op, positions).map(|lowered| self.merged(seg, op, units, positions, lowered)).is_some(),
|
||||
Path::Typed => self.lowered(seg, op, positions, &mut held).map(|lowered| self.merged(seg, op, units, positions, lowered)).is_some(),
|
||||
Path::Lane => false,
|
||||
};
|
||||
if !typed {
|
||||
self.laned(seg, units, positions);
|
||||
}
|
||||
op.cost.record(path, start.elapsed(), local);
|
||||
let (choice, leaves, hints) = held;
|
||||
op.dedup.settle(&op.cost, path, choice, start.elapsed(), local);
|
||||
op.dedup.probe(&op.cost, self, local, |run| run.coded(op, &leaves, &hints, positions));
|
||||
}
|
||||
|
||||
fn laned(&mut self, seg: &SegPlan, units: &[Op], positions: Option<&Rc<[usize]>>) {
|
||||
@@ -230,7 +236,7 @@ impl<'a> Run<'_, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn lowered(&mut self, seg: &SegPlan, op: &TypedOp, positions: Option<&Rc<[usize]>>) -> Option<Lowered> {
|
||||
fn lowered(&mut self, seg: &SegPlan, op: &TypedOp, positions: Option<&Rc<[usize]>>, held: &mut Held<'a>) -> Option<Lowered> {
|
||||
let rows = self.store.rows;
|
||||
let mut hints: Vec<Hint> = op
|
||||
.columns
|
||||
@@ -238,7 +244,8 @@ impl<'a> Run<'_, 'a> {
|
||||
.map(|read| self.store.hints.iter().find(|(slot, _, _)| *slot == read.slot).map(|(_, codes, size)| (codes.clone(), *size)))
|
||||
.collect();
|
||||
let raw: Vec<Leaf<'a>> = op.columns.iter().map(|read| self.store.leaf(read.slot)).collect();
|
||||
let keyed = op.dedup.ready() && op.lists.is_empty() && op.dedup.eligible(&op.program, &raw, &hints);
|
||||
let eligible = op.lists.is_empty() && op.dedup.eligible(&op.program, &raw, &hints);
|
||||
let keyed = op.dedup.ready() && eligible;
|
||||
let mut prefault: Option<Vec<u64>> = None;
|
||||
let mut leaves: Vec<Leaf<'a>> = Vec::with_capacity(op.columns.len());
|
||||
for (at, read) in op.columns.iter().enumerate() {
|
||||
@@ -263,36 +270,67 @@ impl<'a> Run<'_, 'a> {
|
||||
}
|
||||
None => {
|
||||
let select: Option<Vec<u64>> = positions.map(|positions| Select::bits(rows, positions));
|
||||
let mut listed: Vec<Prepared<'a>> = Vec::with_capacity(op.lists.len());
|
||||
for (read, chain) in &op.lists {
|
||||
let chain: Vec<&str> = chain.iter().map(|field| field.as_ref()).collect();
|
||||
let listing = self.store.listing(read.slot, &chain)?;
|
||||
let (validity, faults) = match (chain.is_empty(), Store::implied(seg, *read)) {
|
||||
(true, false) => {
|
||||
let mask = self.store.mask(seg, read.present);
|
||||
let mut validity = listing.frame.validity.as_deref().map_or_else(|| Bits::ones(rows), <[u64]>::to_vec);
|
||||
let mut faults = listing.hosted.as_deref().map_or_else(|| vec![0u64; rows.div_ceil(64)], <[u64]>::to_vec);
|
||||
for row in (0..rows).filter(|&row| !Bits::get(&mask, row)) {
|
||||
match listing.frame.offsets[row] == listing.frame.offsets[row + 1] {
|
||||
true => Bits::set(&mut validity, row, false),
|
||||
false => Bits::set(&mut faults, row, true),
|
||||
}
|
||||
}
|
||||
(Some(validity), Some(faults))
|
||||
}
|
||||
_ => (None, None),
|
||||
};
|
||||
listed.push((listing, validity, faults));
|
||||
}
|
||||
let call = TypedCall {
|
||||
rows,
|
||||
columns: &leaves,
|
||||
lists: listed.iter().map(|(listing, validity, faults)| ListPart::Listing(listing, validity.as_deref(), faults.as_deref())).collect(),
|
||||
select: select.as_deref(),
|
||||
let local = positions.map_or(rows, |p| p.len());
|
||||
let (out, ids) = match op.lists.is_empty() && !eligible {
|
||||
true => {
|
||||
let (out, choice) = op.dedup.choose(self, local, |run| run.plain(seg, op, &leaves, select.as_deref()).map(|out| (out, None)), |run| run.coded(op, &leaves, &hints, positions));
|
||||
*held = (choice, leaves, hints);
|
||||
out?
|
||||
}
|
||||
false => (self.plain(seg, op, &leaves, select.as_deref())?, None),
|
||||
};
|
||||
let out = call.run(&op.program)?;
|
||||
Some((out, None, select, prefault))
|
||||
let select = match ids {
|
||||
Some(_) => None,
|
||||
None => select,
|
||||
};
|
||||
Some((out, ids, select, prefault))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(&mut self, seg: &SegPlan, op: &TypedOp, leaves: &[Leaf<'a>], select: Option<&[u64]>) -> Option<Outputs> {
|
||||
let rows = self.store.rows;
|
||||
let mut listed: Vec<Prepared<'a>> = Vec::with_capacity(op.lists.len());
|
||||
for (read, chain) in &op.lists {
|
||||
let chain: Vec<&str> = chain.iter().map(|field| field.as_ref()).collect();
|
||||
let listing = self.store.listing(read.slot, &chain)?;
|
||||
let (validity, faults) = match (chain.is_empty(), Store::implied(seg, *read)) {
|
||||
(true, false) => {
|
||||
let mask = self.store.mask(seg, read.present);
|
||||
let mut validity = listing.frame.validity.as_deref().map_or_else(|| Bits::ones(rows), <[u64]>::to_vec);
|
||||
let mut faults = listing.hosted.as_deref().map_or_else(|| vec![0u64; rows.div_ceil(64)], <[u64]>::to_vec);
|
||||
for row in (0..rows).filter(|&row| !Bits::get(&mask, row)) {
|
||||
match listing.frame.offsets[row] == listing.frame.offsets[row + 1] {
|
||||
true => Bits::set(&mut validity, row, false),
|
||||
false => Bits::set(&mut faults, row, true),
|
||||
}
|
||||
}
|
||||
(Some(validity), Some(faults))
|
||||
}
|
||||
_ => (None, None),
|
||||
};
|
||||
listed.push((listing, validity, faults));
|
||||
}
|
||||
let call = TypedCall {
|
||||
rows,
|
||||
columns: leaves,
|
||||
lists: listed.iter().map(|(listing, validity, faults)| ListPart::Listing(listing, validity.as_deref(), faults.as_deref())).collect(),
|
||||
select,
|
||||
};
|
||||
call.run(&op.program)
|
||||
}
|
||||
|
||||
fn coded(&mut self, op: &TypedOp, leaves: &[Leaf<'a>], hints: &[Hint], positions: Option<&Rc<[usize]>>) -> Option<(Outputs, Option<Vec<u32>>)> {
|
||||
let rows = self.store.rows;
|
||||
let mut codes: Vec<Hint> = Vec::with_capacity(leaves.len());
|
||||
for (at, ((read, leaf), hint)) in op.columns.iter().zip(leaves).zip(hints).enumerate() {
|
||||
let code = match (hint, leaf.column().values) {
|
||||
(Some(hint), _) => Some(hint.clone()),
|
||||
(None, Values::Dict { .. } | Values::Bool { .. }) => None,
|
||||
(None, _) => Some(self.store.codes(read.slot, op.shared.get(at).copied().unwrap_or(false), leaf)?),
|
||||
};
|
||||
codes.push(code);
|
||||
}
|
||||
Dedup::reps(&op.program, leaves, &codes, positions, rows).map(|(out, ids)| (out, Some(ids)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::compiled::core::fuse::Fused;
|
||||
use super::{Bind, Member, Pass, Sheet};
|
||||
use crate::compiled::core::switch::{Cost, Density, Path};
|
||||
use crate::compiled::core::variants::Variants;
|
||||
use crate::compiled::core::exec::{ListPart, Select, TypedCall};
|
||||
use crate::compiled::core::exec::{Choice, Dedup, Hint, ListPart, Select, TypedCall};
|
||||
use crate::compiled::core::group::{Built, Prefix, Step};
|
||||
use crate::compiled::core::list::Frame;
|
||||
use crate::compiled::core::retry::Take;
|
||||
@@ -14,6 +14,7 @@ use crate::policy::blocks::BlockKind;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use zen_expression::lane::Values;
|
||||
use zen_expression::typed::{Lowering, Outputs, Program, Resolve, Resolved};
|
||||
|
||||
pub(crate) struct TypedGroup {
|
||||
@@ -21,6 +22,7 @@ pub(crate) struct TypedGroup {
|
||||
sinks: Vec<Sink>,
|
||||
pub(super) units: usize,
|
||||
pub(super) cost: Cost,
|
||||
dedup: Dedup,
|
||||
probe: Box<[Probed]>,
|
||||
columns: Vec<usize>,
|
||||
lists: Vec<Option<usize>>,
|
||||
@@ -147,6 +149,7 @@ impl TypedGroup {
|
||||
sinks: Vec::new(),
|
||||
units: 0,
|
||||
cost: Cost::new(),
|
||||
dedup: Dedup::new(),
|
||||
probe: record.into(),
|
||||
columns: Vec::new(),
|
||||
lists: Vec::new(),
|
||||
@@ -184,6 +187,7 @@ impl TypedGroup {
|
||||
sinks,
|
||||
units,
|
||||
cost: Cost::new(),
|
||||
dedup: Dedup::new(),
|
||||
probe: record.into(),
|
||||
columns,
|
||||
lists,
|
||||
@@ -257,9 +261,18 @@ impl<'s, 'a> Pass<'s, 'a> {
|
||||
if path.0 == Path::Lane {
|
||||
return Typed::Lane(group, path);
|
||||
}
|
||||
let (start, count) = (Instant::now(), rows.len());
|
||||
let (start, count, asked, whole) = (Instant::now(), rows.len(), rows, full);
|
||||
let select = (!full).then(|| Select::bits(total, rows));
|
||||
let Some(mut out) = self.execute(&group, program, &sources, entity, select.as_deref()) else {
|
||||
let (out, choice) = match group.lists.is_empty() {
|
||||
true => group.dedup.choose(
|
||||
self,
|
||||
count,
|
||||
|pass| pass.execute(&group, program, &sources, entity, select.as_deref()),
|
||||
|pass| pass.deduped(&group, program, &sources, asked, whole),
|
||||
),
|
||||
false => (self.execute(&group, program, &sources, entity, select.as_deref()), Choice::default()),
|
||||
};
|
||||
let Some(mut out) = out else {
|
||||
return Typed::Skipped;
|
||||
};
|
||||
let (faulted, kept) = match out.faults().any() {
|
||||
@@ -271,7 +284,8 @@ impl<'s, 'a> Pass<'s, 'a> {
|
||||
false => kept.as_slice(),
|
||||
};
|
||||
if rows.is_empty() {
|
||||
group.cost.record(path, start.elapsed(), count);
|
||||
group.dedup.settle(&group.cost, path, choice, start.elapsed(), count);
|
||||
group.dedup.probe(&group.cost, self, count, |pass| pass.deduped(&group, program, &sources, asked, whole));
|
||||
return Typed::Ran(group.units, faulted);
|
||||
}
|
||||
let full = rows.len() == total;
|
||||
@@ -299,10 +313,35 @@ impl<'s, 'a> Pass<'s, 'a> {
|
||||
self.sink(&group.sinks, leaves, Some((at, &kids)), rows);
|
||||
}
|
||||
}
|
||||
group.cost.record(path, start.elapsed(), count);
|
||||
group.dedup.settle(&group.cost, path, choice, start.elapsed(), count);
|
||||
group.dedup.probe(&group.cost, self, count, |pass| pass.deduped(&group, program, &sources, asked, whole));
|
||||
Typed::Ran(group.units, faulted)
|
||||
}
|
||||
|
||||
fn deduped(&self, group: &TypedGroup, program: &Program, sources: &[Source], rows: &[usize], full: bool) -> Option<Outputs> {
|
||||
let leaves: Vec<Leaf<'a>> = group
|
||||
.columns
|
||||
.iter()
|
||||
.map(|&at| match sources.get(at)? {
|
||||
Source::Entry(entry) => Some(self.sheet.entries[*entry].leaf.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let total = self.sheet.rows;
|
||||
let codes: Vec<Hint> = leaves
|
||||
.iter()
|
||||
.map(|leaf| {
|
||||
let column = leaf.column();
|
||||
match column.values {
|
||||
Values::Dict { .. } | Values::Bool { .. } => Some(None),
|
||||
_ => Dedup::codes(&column, total).map(Some),
|
||||
}
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let positions: Option<Rc<[usize]>> = (!full).then(|| rows.into());
|
||||
Dedup::coded(program, &leaves, &codes, positions.as_ref(), total)
|
||||
}
|
||||
|
||||
fn execute(&self, group: &TypedGroup, program: &Program, sources: &[Source], entity: Option<usize>, select: Option<&[u64]>) -> Option<Outputs> {
|
||||
let leaf = |at: usize| -> Option<Leaf<'a>> {
|
||||
match sources.get(at)? {
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(crate) enum Seen {
|
||||
Mixed,
|
||||
}
|
||||
|
||||
struct Coder<'d> {
|
||||
pub(crate) struct Coder<'d> {
|
||||
data: &'d [u8],
|
||||
slots: [u8; Coder::SLOTS],
|
||||
entries: Vec<((u64, u64, usize), usize)>,
|
||||
@@ -411,7 +411,7 @@ impl<'d> Coder<'d> {
|
||||
(hash >> 57) as usize
|
||||
}
|
||||
|
||||
fn codes(mut self, offsets: &[i32]) -> Option<(Vec<i32>, Dict)> {
|
||||
fn scan(&mut self, offsets: &[i32]) -> Option<Vec<i32>> {
|
||||
let mut codes = Vec::with_capacity(offsets.len().saturating_sub(1));
|
||||
for (at, w) in offsets.windows(2).enumerate() {
|
||||
if at == Self::SAMPLE && self.entries.len() > Self::SAMPLED {
|
||||
@@ -419,6 +419,17 @@ impl<'d> Coder<'d> {
|
||||
}
|
||||
codes.push(self.code(usize::try_from(w[0]).ok()?, usize::try_from(w[1]).ok()?)?);
|
||||
}
|
||||
Some(codes)
|
||||
}
|
||||
|
||||
pub(crate) fn keys(data: &'d [u8], offsets: &[i32]) -> Option<(Rc<[i32]>, usize)> {
|
||||
let mut coder = Self::new(data);
|
||||
let codes = coder.scan(offsets)?;
|
||||
Some((codes.into(), coder.entries.len()))
|
||||
}
|
||||
|
||||
fn codes(mut self, offsets: &[i32]) -> Option<(Vec<i32>, Dict)> {
|
||||
let codes = self.scan(offsets)?;
|
||||
let mut dict_offsets = Vec::with_capacity(self.entries.len() + 1);
|
||||
let mut text = String::new();
|
||||
dict_offsets.push(0);
|
||||
|
||||
@@ -571,12 +571,15 @@ async fn columnar_graph_throughput() {
|
||||
continue;
|
||||
}
|
||||
let mut best = [f64::MAX; 2];
|
||||
for _ in 0..5 {
|
||||
let start = std::time::Instant::now();
|
||||
for c in contexts.iter().take(256) {
|
||||
let _ = walker.evaluate(c.clone()).await;
|
||||
let calls: usize = std::env::var("BENCH_CALLS").ok().and_then(|v| v.parse().ok()).unwrap_or(5);
|
||||
for call in 0..calls {
|
||||
if call < 5 {
|
||||
let start = std::time::Instant::now();
|
||||
for c in contexts.iter().take(256) {
|
||||
let _ = walker.evaluate(c.clone()).await;
|
||||
}
|
||||
best[0] = best[0].min(start.elapsed().as_nanos() as f64 / rows.min(256) as f64);
|
||||
}
|
||||
best[0] = best[0].min(start.elapsed().as_nanos() as f64 / rows.min(256) as f64);
|
||||
let start = std::time::Instant::now();
|
||||
let output = compiled.evaluate_columns(&columns, options).await;
|
||||
if read {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -166,6 +166,53 @@ impl Slot {
|
||||
}
|
||||
}
|
||||
|
||||
fn spread(&mut self, sources: &[u32]) {
|
||||
let rows = sources.len();
|
||||
let pick = |id: u32| (id != u32::MAX).then_some(id as usize);
|
||||
let mut valid = vec![0u64; K::words(rows)];
|
||||
for (row, &id) in sources.iter().enumerate() {
|
||||
if pick(id).is_some_and(|at| K::get(&self.valid, at)) {
|
||||
K::set(&mut valid, row, true);
|
||||
}
|
||||
}
|
||||
self.data = match std::mem::replace(&mut self.data, Data::Bool(Vec::new())) {
|
||||
Data::Num { mant, scale } => Data::Num {
|
||||
mant: sources.iter().map(|&id| pick(id).and_then(|at| mant.get(at).copied()).unwrap_or(0)).collect(),
|
||||
scale: sources.iter().map(|&id| pick(id).and_then(|at| scale.get(at).copied()).unwrap_or(0)).collect(),
|
||||
},
|
||||
Data::Bool(bits) => {
|
||||
let mut out = vec![0u64; K::words(rows)];
|
||||
for (row, &id) in sources.iter().enumerate() {
|
||||
if pick(id).is_some_and(|at| K::get(&bits, at)) {
|
||||
K::set(&mut out, row, true);
|
||||
}
|
||||
}
|
||||
Data::Bool(out)
|
||||
}
|
||||
Data::Code(codes) => Data::Code(sources.iter().map(|&id| pick(id).and_then(|at| codes.get(at).copied()).unwrap_or(0)).collect()),
|
||||
Data::Text { span, data } => Data::Text {
|
||||
span: sources.iter().map(|&id| pick(id).and_then(|at| span.get(at).copied()).unwrap_or((0, 0))).collect(),
|
||||
data,
|
||||
},
|
||||
Data::Date(dates) => Data::Date(sources.iter().map(|&id| pick(id).and_then(|at| dates.get(at).copied().flatten())).collect()),
|
||||
};
|
||||
if !self.wide.is_empty() {
|
||||
let wide = std::mem::take(&mut self.wide);
|
||||
self.wide = sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(row, &id)| {
|
||||
let at = pick(id)?;
|
||||
let found = wide.binary_search_by_key(&at, |(at, _)| *at).ok()?;
|
||||
wide.get(found).map(|(_, d)| (row, *d))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
self.valid = valid;
|
||||
self.fault = self.fault.spread(sources);
|
||||
self.len = rows;
|
||||
}
|
||||
|
||||
fn reset(&mut self, len: usize) {
|
||||
self.len = len;
|
||||
self.wide.clear();
|
||||
@@ -206,6 +253,20 @@ impl Slot {
|
||||
}
|
||||
|
||||
impl Faults {
|
||||
fn spread(&self, sources: &[u32]) -> Self {
|
||||
let mut bits = vec![0u64; K::words(sources.len())];
|
||||
let mut any = false;
|
||||
if self.any {
|
||||
for (row, &id) in sources.iter().enumerate() {
|
||||
if id != u32::MAX && K::get(&self.bits, id as usize) {
|
||||
K::set(&mut bits, row, true);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { bits, rows: sources.len(), any }
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self, rows: usize) {
|
||||
self.bits.clear();
|
||||
self.bits.resize(K::words(rows), 0);
|
||||
@@ -313,6 +374,29 @@ impl Outputs {
|
||||
&self.faults
|
||||
}
|
||||
|
||||
pub fn spread(&mut self, rows: usize, ids: &[u32], positions: Option<&[usize]>) -> bool {
|
||||
let reps = self.rows;
|
||||
if self.slots.iter().any(|slot| slot.offsets.is_some() || slot.len != reps) || positions.is_some_and(|p| p.len() != ids.len()) {
|
||||
return false;
|
||||
}
|
||||
let mut sources = match positions {
|
||||
None => ids.to_vec(),
|
||||
Some(_) => vec![u32::MAX; rows],
|
||||
};
|
||||
if let Some(positions) = positions {
|
||||
positions.iter().zip(ids).for_each(|(&row, &id)| sources[row] = id);
|
||||
}
|
||||
if sources.len() != rows || sources.iter().any(|&id| id != u32::MAX && id as usize >= reps) {
|
||||
return false;
|
||||
}
|
||||
self.rows = rows;
|
||||
self.faults = self.faults.spread(&sources);
|
||||
for slot in &mut self.slots {
|
||||
slot.spread(&sources);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn parts(&mut self) -> (&mut [Slot], &mut Faults) {
|
||||
(&mut self.slots, &mut self.faults)
|
||||
}
|
||||
@@ -386,3 +470,77 @@ impl Slot {
|
||||
self.offsets = Some(out);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Data, Faults, Outputs, Slot};
|
||||
use crate::typed::hir::{Kind, Scope};
|
||||
use crate::typed::kernel::K;
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
struct Build;
|
||||
|
||||
impl Build {
|
||||
fn slot(kind: Kind, data: Data, valid: &[bool], faulted: &[usize], wide: Vec<(usize, Decimal)>) -> Slot {
|
||||
let mut bits = vec![0u64; K::words(valid.len())];
|
||||
valid.iter().enumerate().for_each(|(at, &on)| K::set(&mut bits, at, on));
|
||||
let mut fault = Faults::default();
|
||||
fault.reset(valid.len());
|
||||
faulted.iter().for_each(|&at| fault.set(at));
|
||||
Slot {
|
||||
name: String::new(),
|
||||
scope: Scope::Row,
|
||||
kind,
|
||||
len: valid.len(),
|
||||
data,
|
||||
valid: bits,
|
||||
fault,
|
||||
wide,
|
||||
offsets: None,
|
||||
keep: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn reps() -> Outputs {
|
||||
let num = Self::slot(Kind::Num(None), Data::Num { mant: vec![15, 7, 0], scale: vec![1, 0, 0] }, &[true, true, false], &[2], vec![(1, Decimal::MAX)]);
|
||||
let text = Self::slot(Kind::Text, Data::Text { span: vec![(0, 2), (2, 5), (5, 5)], data: b"abxyz".to_vec() }, &[true, true, false], &[], Vec::new());
|
||||
let flag = Self::slot(Kind::Bool, Data::Bool(vec![0b101]), &[true, false, true], &[], Vec::new());
|
||||
let mut faults = Faults::default();
|
||||
faults.reset(3);
|
||||
faults.set(2);
|
||||
Outputs { rows: 3, slots: vec![num, text, flag], faults }
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_maps_every_row_to_its_representative() {
|
||||
let mut out = Build::reps();
|
||||
assert!(out.spread(5, &[1, 0, 2, 1, 0], None));
|
||||
assert_eq!(out.rows(), 5);
|
||||
let num = &out.slots()[0];
|
||||
assert_eq!((0..5).map(|at| num.decimal(at)).collect::<Vec<_>>(), vec![Some(Decimal::MAX), Some(Decimal::new(15, 1)), None, Some(Decimal::MAX), Some(Decimal::new(15, 1))]);
|
||||
assert_eq!(num.fault.iter().collect::<Vec<_>>(), vec![2]);
|
||||
assert_eq!(out.faults().iter().collect::<Vec<_>>(), vec![2]);
|
||||
let text = &out.slots()[1];
|
||||
assert_eq!((0..5).map(|at| text.text(at)).collect::<Vec<_>>(), vec![Some("xyz"), Some("ab"), None, Some("xyz"), Some("ab")]);
|
||||
let flag = &out.slots()[2];
|
||||
assert_eq!((0..5).map(|at| flag.boolean(at)).collect::<Vec<_>>(), vec![None, Some(true), Some(true), None, Some(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_leaves_unselected_rows_invalid_and_unfaulted() {
|
||||
let mut out = Build::reps();
|
||||
assert!(out.spread(6, &[2, 0, 1], Some(&[1, 3, 4])));
|
||||
let num = &out.slots()[0];
|
||||
assert_eq!((0..6).map(|at| num.is_valid(at)).collect::<Vec<_>>(), vec![false, false, false, true, true, false]);
|
||||
assert_eq!(num.fault.iter().collect::<Vec<_>>(), vec![1]);
|
||||
assert_eq!(num.wide, vec![(4, Decimal::MAX)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_rejects_mismatched_ids() {
|
||||
let mut out = Build::reps();
|
||||
assert!(!out.spread(2, &[0, 3], None));
|
||||
assert!(!out.spread(4, &[0, 1], Some(&[0])));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user