Skip to content

Implement conversion from ArrowArray to R vector for basic types - #50

Merged
paleolimbot merged 37 commits into
apache:mainfrom
paleolimbot:all-the-altreps
Sep 29, 2022
Merged

paleolimbot merged 37 commits into
apache:mainfrom
paleolimbot:all-the-altreps

Conversation

@paleolimbot

@paleolimbot paleolimbot commented Sep 20, 2022 •

Copy link
Copy Markdown
Member

This PR (1) implements ALTREP strings, which are a huge part of making conversion to data.frame fast (with the bet that only a subset of strings will actually appear in R form) and (2) implements our own conversion infrastructure for data.frame(), logical(), double(), and character(). The conversion infrastructure is a lot like vcrs::vec_data()/vctrs::vec_restore():

library(nanoarrow)

df_random <- nanoarrow:::vec_gen(
  data.frame(lgl = logical(), int = integer(), dbl = double(), chr = character()),
  prop_na = 0.2,
  n = 10
)

array <- as_nanoarrow_array(df_random)

# as.data.frame() and as.vector() give default conversions
str(as.data.frame(array))
#> 'data.frame':    10 obs. of  4 variables:
#>  $ lgl: logi  NA FALSE TRUE FALSE FALSE FALSE ...
#>  $ int: int  NA 1815958320 -839617380 NA -724413115 NA 559850203 401563346 1528045745 -1132606696
#>  $ dbl: num  0.412 0.107 0.159 0.882 0.54 ...
#>  $ chr: chr  "aaaaaaaaaaaaaaaaaaaa" "bbbbbbbbbbbb" NA "dddddddd" ...
str(as.vector(array))
#> 'data.frame':    10 obs. of  4 variables:
#>  $ lgl: logi  NA FALSE TRUE FALSE FALSE FALSE ...
#>  $ int: int  NA 1815958320 -839617380 NA -724413115 NA 559850203 401563346 1528045745 -1132606696
#>  $ dbl: num  0.412 0.107 0.159 0.882 0.54 ...
#>  $ chr: chr  "aaaaaaaaaaaaaaaaaaaa" "bbbbbbbbbbbb" NA "dddddddd" ...
str(as.vector(array$children$lgl))
#>  logi [1:10] NA FALSE TRUE FALSE FALSE FALSE ...

# from_nanoarrow_array() gives more control over the conversion
from_nanoarrow_array(array$children$lgl, NULL)
#>  [1]    NA FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
from_nanoarrow_array(array$children$lgl, integer())
#>  [1] NA  0  1  0  0  0  0  1  1  0
from_nanoarrow_array(array$children$lgl, double())
#>  [1] NA  0  1  0  0  0  0  1  1  0

# ...or errors nicely otherwise
from_nanoarrow_array(array$children$lgl, character())
#> Error in from_nanoarrow_array.default(array$children$lgl, character()): Can't convert `lgl` <b> to R vector of type character

# you can also get a hypothetical ptype without doing the conversion
str(infer_nanoarrow_ptype(array))
#> 'data.frame':    0 obs. of  4 variables:
#>  $ lgl: logi 
#>  $ int: int 
#>  $ dbl: num 
#>  $ chr: chr

# ...or only change the conversion of some columns
from_nanoarrow_array(array, vctrs::partial_frame(lgl = integer()))
#>    lgl         int       dbl                  chr
#> 1   NA          NA 0.4117649 aaaaaaaaaaaaaaaaaaaa
#> 2    0  1815958320 0.1067497         bbbbbbbbbbbb
#> 3    1  -839617380 0.1590266                 <NA>
#> 4    0          NA 0.8822662             dddddddd
#> 5    0  -724413115 0.5402008   eeeeeeeeeeeeeeeeee
#> 6    0          NA 0.1512409        fffffffffffff
#> 7    0   559850203 0.5393792                  ggg
#> 8    1   401563346 0.3115846       hhhhhhhhhhhhhh
#> 9    1  1528045745 0.7741894                 <NA>
#> 10   0 -1132606696        NA                 <NA>

Created on 2022-09-27 by the reprex package (v2.0.1)

I also did some benchmarking against arrow's conversions, which are faster because they use more ALTREP and do some work in parallel. Still, to get an as.data.frame() call that takes more than 0.1 seconds would take a few hundred columns with a million rows (nanoarrow's conversion does not loop in R or S3 dispatch along data frame columns for most types).

This PR is rather unwieldy already, so I'd like to leave better type support and optimizing conversions to another one!

@codecov-commenter

codecov-commenter commented Sep 23, 2022 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.11%. Comparing base (4a42e11) to head (dafb3db).
⚠️ Report is 659 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #50      +/-   ##
==========================================
+ Coverage   92.00%   92.11%   +0.10%     
==========================================
  Files           6        6              
  Lines        1301     1319      +18     
  Branches       47       47              
==========================================
+ Hits         1197     1215      +18     
  Misses         72       72              
  Partials       32       32              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@paleolimbot
paleolimbot marked this pull request as ready for review September 23, 2022 20:07
@paleolimbot
paleolimbot marked this pull request as draft September 24, 2022 02:22
@paleolimbot
paleolimbot merged commit 16c8df7 into apache:main Sep 29, 2022
@paleolimbot
paleolimbot deleted the all-the-altreps branch September 30, 2022 00:55
paleolimbot added a commit to apache/arrow that referenced this pull request Oct 26, 2022
This PR is a more permanent fix for ARROW-16578 (#13415), which noted some very bad performance when calling `unique()` in a character vector created by us. In benchmarking a few other things and implementing some simpler altrep classes around the C Data interface (apache/arrow-nanoarrow#50), I found a few other issues...notably, that calling `head()` (or accessing a single string element) would materialize an entire string vector (rather than just materializing the elements required):

``` r
library(arrow, warn.conflicts = FALSE)

big_string <- as.character(runif(1e6))
big_string_altrep <- as.vector(as_arrow_array(big_string))

bench::mark(head(big_string), head(big_string_altrep))[c("expression", "mem_alloc")]
#> # A tibble: 2 × 2
#>   expression              mem_alloc
#>   <bch:expr>              <bch:byt>
#> 1 head(big_string)               0B
#> 2 head(big_string_altrep)    7.63MB
```

For the original STRING_ELT issue, the previous method may have been slow for a few reasons:

- First, it used `BEGIN_CPP11` and `END_CPP11`, which stack-allocates an 8 kb error message array (which is fast but not trivial).
- Second, it stack-allocates an `RStringViewer` for every string access. This is probably not that bad, but because it's not trivially destructible it couldn't be used without `BEGIN_CPP11`/`END_CPP11`, which allocates more than needed. I statically allocate one of these to solve this.
- Third, it was calling `GetOption()` (via creating the string viewer) on every string access. This is a little tricky to work around...I opted to read the option whenever we create an ALTREP vector. This means that technically the value read when an individual value materializes could be out of date; however, in the case that a user does `options(arrow.strip_nuls = TRUE)` it will be true for the rest of the session.
- Fourth, it `unwind_protect`ed for every string access (which is fast but not trivial). I fixed this by statically allocating one `RStringViewer` (so that memory does not leak from a longjmp in the frame) and removing the cpp11 calls from the Elt method (since these would throw exceptions where a longjmp is expected by the calling frame).

This PR also releases the `std::shared_ptr<ChunkedArray>` when we materialize our ALTREP vectors. We use it for length/sum/min/max implementations and for roundtripping but in many cases it's not used and is just taking up memory that could be released and used for something else. I ran ursabot's benchmarks to make sure this doesn't slow things down, and it doesn't (at least for our existing benchmarks).

In changing the above bits, I ran test coverage and noticed that there were parts of altrep.cpp that weren't tested by our test suite. Testing ALTREP is hard because it's almost completely undocumented and where exactly it gets used in the R API changes with each release. I added some helper methods and tests that more accurately reflect the C/C++ usage of ALTREP.

Finally, I noticed that we were doing a "from the beginning" (O(N squred)) search rather than a binary search O(log(n)) in some places to resolve an array/index in the array. This has a non-trivial effect on arrays with many chunks:

Before this PR:

``` r
library(arrow, warn.conflicts = FALSE)
#> Some features are not enabled in this build of Arrow. Run `arrow_info()` for more information.

chunks <- lapply(1:1000, function(i) runif(1e3))
altrep_one_chunk <- as.vector(ChunkedArray$create(unlist(chunks)))
altrep_many_chunks <- as.vector(ChunkedArray$create(!!!chunks))
random_indices <- sample(seq_len(1e6), 1e6, replace = FALSE)

bench::mark(
  altrep_one_chunk[random_indices],
  altrep_many_chunks[random_indices]
)
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 × 6
#>   expression                              min   median `itr/sec` mem_a…¹ gc/se…²
#>   <bch:expr>                         <bch:tm> <bch:tm>     <dbl> <bch:b>   <dbl>
#> 1 altrep_one_chunk[random_indices]    68.99ms  72.05ms    12.5    7.63MB  16.1  
#> 2 altrep_many_chunks[random_indices]    4.36s    4.36s     0.229  7.63MB   0.459
#> # … with abbreviated variable names ¹​mem_alloc, ²​`gc/sec`
```

After this PR:

``` r
library(arrow, warn.conflicts = FALSE)

chunks <- lapply(1:1000, function(i) runif(1e3))
altrep_one_chunk <- as.vector(ChunkedArray$create(unlist(chunks)))
altrep_many_chunks <- as.vector(ChunkedArray$create(!!!chunks))
random_indices <- sample(seq_len(1e6), 1e6, replace = FALSE)

bench::mark(
  altrep_one_chunk[random_indices],
  altrep_many_chunks[random_indices]
)
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 × 6
#>   expression                              min   median `itr/sec` mem_a…¹ gc/se…²
#>   <bch:expr>                         <bch:tm> <bch:tm>     <dbl> <bch:b>   <dbl>
#> 1 altrep_one_chunk[random_indices]     64.7ms   71.5ms     13.1   7.63MB   16.8 
#> 2 altrep_many_chunks[random_indices]  113.1ms  117.1ms      7.85  7.63MB    9.82
#> # … with abbreviated variable names ¹​mem_alloc, ²​`gc/sec`
```

I solved this by using Arrow's `ChunkResolver`. This resulted in a small change in the ALTREP implementation: it is now an external pointer around a custom `ArrowAltrepData` class that contains a `shared_ptr<ChunkedArray>` and a `ChunkResolver` (before it was just an external pointer to a `shared_ptr<ChunkedArray>`).

Lead-authored-by: Dewey Dunnington <[email protected]>
Co-authored-by: Dewey Dunnington <[email protected]>
Signed-off-by: Dewey Dunnington <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants