-
Notifications
You must be signed in to change notification settings - Fork 226
[AURON #1891] Implement randn() function #1938
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
robreeves
wants to merge
31
commits into
apache:master
Choose a base branch
from
robreeves:randn
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
175fa00
randn
robreeves 5bb5ca5
reduce arg parsing complexity
robreeves 3d0fa7d
remove extra method
robreeves 0f793c4
use rand_dist
robreeves 0d041f3
revert auto format change
robreeves 0b93080
revert auto format changes
robreeves 3b78e73
autoformat
robreeves 4b2261b
handle batches
robreeves 81beb0b
new approach
robreeves a8183ae
forced format changes during build
robreeves f591295
Merge origin/master into randn
robreeves 0ea5dc9
simplify evaluate
robreeves f792b1b
revert whitespace
robreeves dd6c98b
revert whitespace
robreeves a0cf6b7
Merge origin/master into randn
robreeves 585e1be
Add end-to-end test for randn function
robreeves 388d0a1
Fix rustfmt formatting in randn.rs
robreeves 6e1f2d4
Fix clippy uninlined_format_args in randn.rs
robreeves 048fdfb
Rename randn to spark_randn to align with Spark-specific naming conve…
robreeves 8f554f8
Rename RandnExprNode to SparkRandnExprNode in proto and update refere…
robreeves 7ea58fc
fix typo
robreeves e329725
Remove unused rand/rand_distr dependencies from datafusion-ext-functions
robreeves fef5506
Handle foldable seed expressions in randn converter
robreeves 96ed5b2
Merge remote-tracking branch 'origin/master' into randn
robreeves 4b741a1
[AURON #2360] Honor config alt keys when reading from SQLConf
robreeves b606195
Remove explanatory comment on synthesized ConfigEntry alternatives
robreeves c6616fc
Make checkSparkAnswerAndOperator tolerant of NaN bit-pattern differences
robreeves 19b8426
Reword NaN canonicalization comment in plainer language
robreeves 65ddb6c
Handle acosh NaN bit difference in the test instead of the shared che…
robreeves 0a012ee
Merge branch 'altkeys' into randn
robreeves f29725e
Validate native randn without comparing values to vanilla Spark
robreeves File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,303 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one or more | ||
| // contributor license agreements. See the NOTICE file distributed with | ||
| // this work for additional information regarding copyright ownership. | ||
| // The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| // (the "License"); you may not use this file except in compliance with | ||
| // the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| use std::{ | ||
| any::Any, | ||
| fmt::{Debug, Display, Formatter}, | ||
| hash::{Hash, Hasher}, | ||
| sync::Arc, | ||
| }; | ||
|
|
||
| use arrow::{ | ||
| array::{Float64Array, RecordBatch}, | ||
| datatypes::{DataType, Schema}, | ||
| }; | ||
| use datafusion::{ | ||
| common::Result, | ||
| logical_expr::ColumnarValue, | ||
| physical_expr::{PhysicalExpr, PhysicalExprRef}, | ||
| }; | ||
| use parking_lot::Mutex; | ||
| use rand::{SeedableRng, rngs::StdRng}; | ||
| use rand_distr::{Distribution, StandardNormal}; | ||
|
|
||
| use crate::down_cast_any_ref; | ||
|
|
||
| /// Returns random values with independent and identically distributed (i.i.d.) | ||
| /// samples drawn from the standard normal distribution. | ||
| /// | ||
| /// Matches Spark's behavior: | ||
| /// - RNG is seeded with `seed + partition_id` | ||
| /// - RNG state advances for each row (stateful across batches) | ||
| pub struct SparkRandnExpr { | ||
| seed: i64, | ||
| partition_id: usize, | ||
| rng: Mutex<StdRng>, | ||
| } | ||
|
|
||
| impl SparkRandnExpr { | ||
| pub fn new(seed: i64, partition_id: usize) -> Self { | ||
| let effective_seed = (seed as u64).wrapping_add(partition_id as u64); | ||
| Self { | ||
| seed, | ||
| partition_id, | ||
| rng: Mutex::new(StdRng::seed_from_u64(effective_seed)), | ||
| } | ||
|
SteNicholas marked this conversation as resolved.
|
||
| } | ||
| } | ||
|
|
||
| impl Display for SparkRandnExpr { | ||
| fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| write!( | ||
| f, | ||
| "Randn(seed={}, partition={})", | ||
| self.seed, self.partition_id | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| impl Debug for SparkRandnExpr { | ||
| fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| write!( | ||
| f, | ||
| "Randn(seed={}, partition={})", | ||
| self.seed, self.partition_id | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| impl PartialEq for SparkRandnExpr { | ||
| fn eq(&self, other: &Self) -> bool { | ||
| self.seed == other.seed && self.partition_id == other.partition_id | ||
| } | ||
| } | ||
|
|
||
| impl Eq for SparkRandnExpr {} | ||
|
|
||
| impl Hash for SparkRandnExpr { | ||
| fn hash<H: Hasher>(&self, state: &mut H) { | ||
| self.seed.hash(state); | ||
| self.partition_id.hash(state); | ||
| } | ||
| } | ||
|
|
||
| impl PhysicalExpr for SparkRandnExpr { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn data_type(&self, _input_schema: &Schema) -> Result<DataType> { | ||
| Ok(DataType::Float64) | ||
| } | ||
|
|
||
| fn nullable(&self, _input_schema: &Schema) -> Result<bool> { | ||
| Ok(false) | ||
| } | ||
|
|
||
| fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { | ||
| let num_rows = batch.num_rows(); | ||
| let mut rng = self.rng.lock(); | ||
| let values = | ||
| Float64Array::from_iter_values(StandardNormal.sample_iter(&mut *rng).take(num_rows)); | ||
| Ok(ColumnarValue::Array(Arc::new(values))) | ||
| } | ||
|
|
||
| fn children(&self) -> Vec<&PhysicalExprRef> { | ||
| vec![] | ||
| } | ||
|
|
||
| fn with_new_children( | ||
| self: Arc<Self>, | ||
| _children: Vec<PhysicalExprRef>, | ||
| ) -> Result<PhysicalExprRef> { | ||
| Ok(Arc::new(Self::new(self.seed, self.partition_id))) | ||
| } | ||
|
|
||
| fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| write!(f, "randn({})", self.seed) | ||
| } | ||
| } | ||
|
|
||
| impl PartialEq<dyn Any> for SparkRandnExpr { | ||
| fn eq(&self, other: &dyn Any) -> bool { | ||
| down_cast_any_ref(other) | ||
| .downcast_ref::<Self>() | ||
| .map(|other| self.seed == other.seed && self.partition_id == other.partition_id) | ||
| .unwrap_or(false) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow::{array::RecordBatch, datatypes::Schema}; | ||
| use datafusion::common::{Result, cast::as_float64_array}; | ||
|
|
||
| use super::*; | ||
|
|
||
| fn create_empty_batch(num_rows: usize) -> RecordBatch { | ||
| let schema = Arc::new(Schema::empty()); | ||
| RecordBatch::try_new_with_options( | ||
| schema, | ||
| vec![], | ||
| &arrow::array::RecordBatchOptions::new().with_row_count(Some(num_rows)), | ||
| ) | ||
| .expect("Failed to create empty batch") | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_randn_generates_different_values_per_row() -> Result<()> { | ||
| let expr = SparkRandnExpr::new(42, 0); | ||
| let batch = create_empty_batch(5); | ||
|
|
||
| let result = expr.evaluate(&batch)?; | ||
| let array = result.into_array(5)?; | ||
| let float_arr = as_float64_array(&array)?; | ||
|
|
||
| // All values should be different (with extremely high probability) | ||
| let values: Vec<f64> = (0..5).map(|i| float_arr.value(i)).collect(); | ||
| for i in 0..values.len() { | ||
| for j in (i + 1)..values.len() { | ||
| assert_ne!( | ||
| values[i], values[j], | ||
| "Values at index {i} and {j} should be different" | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_randn_reproducible_with_same_seed() -> Result<()> { | ||
| let expr1 = SparkRandnExpr::new(42, 0); | ||
| let expr2 = SparkRandnExpr::new(42, 0); | ||
| let batch = create_empty_batch(5); | ||
|
|
||
| let result1 = expr1.evaluate(&batch)?; | ||
| let result2 = expr2.evaluate(&batch)?; | ||
|
|
||
| let arr1_binding = result1.into_array(5)?; | ||
| let arr2_binding = result2.into_array(5)?; | ||
| let arr1 = as_float64_array(&arr1_binding)?; | ||
| let arr2 = as_float64_array(&arr2_binding)?; | ||
|
|
||
| for i in 0..5 { | ||
| assert_eq!( | ||
| arr1.value(i), | ||
| arr2.value(i), | ||
| "Same seed should produce same values" | ||
| ); | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_randn_different_seeds_produce_different_values() -> Result<()> { | ||
| let expr1 = SparkRandnExpr::new(42, 0); | ||
| let expr2 = SparkRandnExpr::new(123, 0); | ||
| let batch = create_empty_batch(5); | ||
|
|
||
| let result1 = expr1.evaluate(&batch)?; | ||
| let result2 = expr2.evaluate(&batch)?; | ||
|
|
||
| let arr1_binding = result1.into_array(5)?; | ||
| let arr2_binding = result2.into_array(5)?; | ||
| let arr1 = as_float64_array(&arr1_binding)?; | ||
| let arr2 = as_float64_array(&arr2_binding)?; | ||
|
|
||
| // At least one value should be different | ||
| let any_different = (0..5).any(|i| arr1.value(i) != arr2.value(i)); | ||
| assert!( | ||
| any_different, | ||
| "Different seeds should produce different values" | ||
| ); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_randn_different_partitions_produce_different_values() -> Result<()> { | ||
| let expr1 = SparkRandnExpr::new(42, 0); | ||
| let expr2 = SparkRandnExpr::new(42, 1); | ||
| let batch = create_empty_batch(5); | ||
|
|
||
| let result1 = expr1.evaluate(&batch)?; | ||
| let result2 = expr2.evaluate(&batch)?; | ||
|
|
||
| let arr1_binding = result1.into_array(5)?; | ||
| let arr2_binding = result2.into_array(5)?; | ||
| let arr1 = as_float64_array(&arr1_binding)?; | ||
| let arr2 = as_float64_array(&arr2_binding)?; | ||
|
|
||
| // At least one value should be different | ||
| let any_different = (0..5).any(|i| arr1.value(i) != arr2.value(i)); | ||
| assert!( | ||
| any_different, | ||
| "Different partitions should produce different values" | ||
| ); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_randn_stateful_across_batches() -> Result<()> { | ||
| let expr = SparkRandnExpr::new(42, 0); | ||
| let batch1 = create_empty_batch(3); | ||
| let batch2 = create_empty_batch(3); | ||
|
|
||
| // Evaluate two batches sequentially | ||
| let result1 = expr.evaluate(&batch1)?; | ||
| let result2 = expr.evaluate(&batch2)?; | ||
|
|
||
| let arr1_binding = result1.into_array(3)?; | ||
| let arr2_binding = result2.into_array(3)?; | ||
| let arr1 = as_float64_array(&arr1_binding)?; | ||
| let arr2 = as_float64_array(&arr2_binding)?; | ||
|
|
||
| // Collect all values | ||
| let values1: Vec<f64> = (0..3).map(|i| arr1.value(i)).collect(); | ||
| let values2: Vec<f64> = (0..3).map(|i| arr2.value(i)).collect(); | ||
|
|
||
| // Second batch should continue from where first left off (not restart) | ||
| // So values should be different between batches | ||
| assert_ne!(values1, values2, "Batches should have different values"); | ||
|
|
||
| // Compare with fresh expr that evaluates both batches together | ||
| let expr_fresh = SparkRandnExpr::new(42, 0); | ||
| let batch_combined = create_empty_batch(6); | ||
| let result_combined = expr_fresh.evaluate(&batch_combined)?; | ||
| let arr_combined_binding = result_combined.into_array(6)?; | ||
| let arr_combined = as_float64_array(&arr_combined_binding)?; | ||
|
|
||
| // First 3 values should match values1, next 3 should match values2 | ||
| for i in 0..3 { | ||
| assert_eq!( | ||
| arr_combined.value(i), | ||
| values1[i], | ||
| "First batch values should match" | ||
| ); | ||
| assert_eq!( | ||
| arr_combined.value(i + 3), | ||
| values2[i], | ||
| "Second batch values should match continuation" | ||
| ); | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The test does pass, but it is because there is a preexisting bug in the test suite. The Spark vanilla case is actually running with auron enabled so the cases always match in the assert.
I added this log:
and it shows this:
I also reproduced it with this test.
Auron is enabled because
spark.auron.enableddefaults to true here. The reason it is not set is because the alt keys are never registered with spark soConfigEntry.findEntry("spark.auron.enable")does not return anything.When I use the correct config
spark.auron.enabled3 tests failed. Since one test is unrelated I will open a separate PR to fix this first.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#2360
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The config issue is fixed in #2361