Skip to content

Add encoding support for vec_match() and vec_in() - #565

Merged
DavisVaughan merged 13 commits into
r-lib:masterfrom
DavisVaughan:char-encoding-match
Sep 6, 2019
Merged

DavisVaughan merged 13 commits into
r-lib:masterfrom
DavisVaughan:char-encoding-match

Conversation

@DavisVaughan

@DavisVaughan DavisVaughan commented Sep 5, 2019 •

Copy link
Copy Markdown
Member

Closes #553

Big picture ideas, I'll add some benchmarks in a bit:

  • New translate.c file holds a number of translation utility functions.

  • vec_match() and vec_in() are a bit tough to handle because they create 2 hashed dictionaries (one for needles and one for haystack) separate of each other. This is a problem if we have vec_match(needles = <utf8>, haystack = <unknown>) since haystack won't be translated to utf8. My solution is to have a translate_encoding2() that is run before the dictionary hashing, which translates both inputs to UTF8 if either requires it.

  • translate_encoding2() is simple when the inputs are character vectors. It uses translation_required_chr2() to determine if either input needs translation, and if either does it translates them.

But we obviously want to be more general, since vec_match() should work with data frames / lists too. That's where the rest of the code comes in.

  • In the case of data frame inputs, translate_encoding2() takes advantage of the fact that we ran vec_cast() to get needles and haystack to a common type beforehand. It loops over the columns (which are guaranteed to be in the same order and have the same type) and calls translate_encoding2() recursively.

  • The case of having list inputs is the toughest. vec_cast() guarantees that needles and haystack are both lists, but there is no guarantee that if the first element of needles is a character vector, then the first element of haystack is too. I think the best solution is to perform an initial loop through needles and haystack, determine if any element of either is a character vector with a "known" encoding (utf8, latin1, bytes), and if that is true then we translate every character vector in both lists to UTF-8.

While this case with lists sounds expensive, I think this is better than the base R strategy. When you give match() lists or data frames, it literally just runs as.character() on the inputs, which has some really odd looking intermediate results and can be pretty expensive. It seems to work for them though. There is even a note in ?match of "Matching for lists is potentially very slow and best avoided except in simple cases."

@DavisVaughan

Copy link
Copy Markdown
Member Author

vec_match() benchmarks. There are a number of them, but I'm trying to cover the cases of character vectors, lists, and data frames.

Setup:

vec_match_old <- vctrs2::vec_match
library(vctrs)
library(tibble)
set.seed(123)

# table - 200000 words, 10 letters each
# x - A subset of 20000 of them, with replacement
table_unknown <- stringi::stri_rand_strings(200000, 10)
x_unknown <- sample(table_unknown, 20000, replace = TRUE)

match() has always been faster than vec_match() in the ascii case:

bench::mark(
  vec_match_old(x_unknown, table_unknown),
  vec_match(x_unknown, table_unknown),
  match(x_unknown, table_unknown),
  iterations = 300
)
#> # A tibble: 3 x 6
#>   expression                                  min  median `itr/sec`
#>   <bch:expr>                              <bch:t> <bch:t>     <dbl>
#> 1 vec_match_old(x_unknown, table_unknown)  13.2ms 14.88ms      65.8
#> 2 vec_match(x_unknown, table_unknown)     13.61ms 14.53ms      67.3
#> 3 match(x_unknown, table_unknown)          4.81ms  5.24ms     186. 
#> # … with 2 more variables: mem_alloc <bch:byt>, `gc/sec` <dbl>

With any UTF8 characters, match() attempts a conversion, slowing it down.

table_utf8 <- paste0(table_unknown, "\u00B0C")
x_utf8 <- sample(table_utf8, 20000, replace = TRUE)

bench::mark(
  vec_match_old(x_utf8, table_utf8),
  vec_match(x_utf8, table_utf8),
  match(x_utf8, table_utf8),
  iterations = 300
)
#> # A tibble: 3 x 6
#>   expression                           min median `itr/sec` mem_alloc
#>   <bch:expr>                        <bch:> <bch:>     <dbl> <bch:byt>
#> 1 vec_match_old(x_utf8, table_utf8) 12.6ms 14.3ms      68.1    1.92MB
#> 2 vec_match(x_utf8, table_utf8)     13.4ms 14.4ms      67.5    1.92MB
#> 3 match(x_utf8, table_utf8)         12.6ms 14.4ms      66.8    3.75MB
#> # … with 1 more variable: `gc/sec` <dbl>

This means match() converts latin1 to utf8 when it don't need to:

table_latin1 <- iconv(table_utf8, "UTF-8", "latin1")
x_latin1 <- iconv(x_utf8, "UTF-8", "latin1")

# match() converts to UTF8, but vec_match() doesn't
bench::mark(
  vec_match_old(x_latin1, table_latin1),
  vec_match(x_latin1, table_latin1),
  match(x_latin1, table_latin1)
)
#> # A tibble: 3 x 6
#>   expression                               min median `itr/sec` mem_alloc
#>   <bch:expr>                            <bch:> <bch:>     <dbl> <bch:byt>
#> 1 vec_match_old(x_latin1, table_latin1) 13.6ms 14.7ms      67.5    1.92MB
#> 2 vec_match(x_latin1, table_latin1)     14.6ms 15.9ms      62.1    1.92MB
#> 3 match(x_latin1, table_latin1)         94.7ms 96.1ms      10.4    3.75MB
#> # … with 1 more variable: `gc/sec` <dbl>

Here we actually have to translate to UTF8 because the table was UTF8

x_utf8_but_unknown <- x_utf8
Encoding(x_utf8_but_unknown) <- "unknown"

# Having to translate `needles` to UTF8
bench::mark(
  # wrong! vec_match_old(x_utf8_but_unknown, table_utf8),
  vec_match(x_utf8_but_unknown, table_utf8),
  match(x_utf8_but_unknown, table_utf8),
  iterations = 100
)
#> # A tibble: 2 x 6
#>   expression                                   min median `itr/sec`
#>   <bch:expr>                                <bch:> <bch:>     <dbl>
#> 1 vec_match(x_utf8_but_unknown, table_utf8) 26.2ms 27.6ms      35.8
#> 2 match(x_utf8_but_unknown, table_utf8)     26.8ms 30.4ms      32.2
#> # … with 2 more variables: mem_alloc <bch:byt>, `gc/sec` <dbl>

Here we have a list that contains UTF8 characters in the haystack, which means we have to convert every character vector to UTF8. Not sure why this is slower, it's a strange case anyways, but I don't think it has to do with the new code.

lst_x_utf8_but_unknown <- as.list(x_utf8_but_unknown)
lst_table_utf8 <- as.list(table_utf8)

bench::mark(
  # wrong! vec_match_old(lst_x_utf8_but_unknown, lst_table_utf8),
  vec_match(lst_x_utf8_but_unknown, lst_table_utf8),
  match(lst_x_utf8_but_unknown, lst_table_utf8),
  iterations = 50
)
#> # A tibble: 2 x 6
#>   expression                                           min median `itr/sec`
#>   <bch:expr>                                        <bch:> <bch:>     <dbl>
#> 1 vec_match(lst_x_utf8_but_unknown, lst_table_utf8) 94.1ms 98.6ms      10.2
#> 2 match(lst_x_utf8_but_unknown, lst_table_utf8)     35.8ms 40.3ms      24.7
#> # … with 2 more variables: mem_alloc <bch:byt>, `gc/sec` <dbl>

The speed of matching with tibbles containing character vectors wasn't really affected:

table_df <- tibble(x = table_unknown, y = table_utf8)
x_df <- vec_slice(table_df, sample(vec_size(table_df), 20000, replace = TRUE))

bench::mark(
  vec_match_old(x_df, table_df),
  vec_match(x_df, table_df),
  # wrong! match(x_df, table_df),
  iterations = 50
)
#> # A tibble: 2 x 6
#>   expression                        min median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>                    <bch:t> <bch:>     <dbl> <bch:byt>    <dbl>
#> 1 vec_match_old(x_df, table_df)    50ms   56ms      17.8    1.94MB    1.14 
#> 2 vec_match(x_df, table_df)        54ms 57.6ms      17.2    1.93MB    0.715

But since the translation check is recursive we can now correctly translate the y column to UTF8, and leave the x column alone:

x_df_unknown <- x_df
x_df_unknown$y <- `Encoding<-`(x_df_unknown$y, "unknown")

bench::mark(
  # wrong! vec_match_old(x_df_unknown, table_df),
  vec_match(x_df_unknown, table_df),
  # wrong! match(x_df_unknown, table_df),
  iterations = 50
)
#> # A tibble: 1 x 6
#>   expression                           min median `itr/sec` mem_alloc
#>   <bch:expr>                        <bch:> <bch:>     <dbl> <bch:byt>
#> 1 vec_match(x_df_unknown, table_df) 67.1ms 72.2ms      13.5    3.59MB
#> # … with 1 more variable: `gc/sec` <dbl>

@lionel- lionel- left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me!

Can you just please use our regular naming scheme, and use prefixes to indicate input type. Suffixes are for output type. E.g. translate_encoding_list2() => list_translate_encoding2()

Comment thread src/vctrs.h Outdated
// `sxpinfo.gp` is exposed through `LEVELS()`, and CHARSXP info is
// extractable through a bitwise and. This copies the unexposed
// interface in Defn.h
#define BYTES_MASK 2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have evidence that other R implementations use the same protocol for encoding? Good evidence would be that it's used in Rcpp, for example.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you checked that it's worth it to use these instead of getCharCE()? We need to go through LEVELS() anyway, which is a function call because of the memory barrier, so it's not clear a priori we gain much. I'd prefer not relying on unexported API. (This should be checked with compiler optimisations enabled, maybe the branched mask inspection is optimised.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I think you might be right. I swear I thought the performance difference was more prominent, but it doesn't seem to matter too much. I'll remove in favor of Rf_getCharCE(). The good news is that it should do exactly the same thing as what I was doing based on its implementation.

vec_equal() benchmark - I switched out CHAR_ENC_TYPE() for Rf_getCharCE() here. This should be a "worst case scenario" because basically all of the strings are different, so that encoding check is run for every element. This would also be the worst case scenario for Rf_getCharCE() in general since returning CE_NATIVE is the last thing it does, after determining it isnt utf8/latin1/bytes.

library(vctrs)
set.seed(123)

x <- stringi::stri_rand_strings(1000000, 10)
x_rev <- rev(x)

# With CHAR_ENC_TYPE()
bench::mark(
  vec_equal(x, x_rev),
  iterations = 2000
)
#> # A tibble: 1 x 6
#>   expression               min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>          <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 vec_equal(x, x_rev)   10.4ms   10.8ms      91.8    3.87MB     9.92

# with Rf_getCharCE()
bench::mark(
  vec_equal(x, x_rev),
  iterations = 2000
)
#> # A tibble: 1 x 6
#>   expression               min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>          <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 vec_equal(x, x_rev)   10.7ms   11.2ms      88.7    3.87MB     9.58

vec_match() benchmark - I switched out CHAR_ENC_TYPE() for Rf_getCharCE() with the most important spot being the loop here which is run on both needles and haystack. I think the difference is small enough to just use the interface supplied by R directly.

library(vctrs)
set.seed(123)

table_unknown <- stringi::stri_rand_strings(500000, 10)
x_unknown <- sample(table_unknown, 250000, replace = TRUE)

# with CHAR_ENC_TYPE()
bench::mark(
  vec_match(x_unknown, table_unknown),
  iterations = 2000
)
#> # A tibble: 1 x 6
#>   expression                             min median `itr/sec` mem_alloc
#>   <bch:expr>                          <bch:> <bch:>     <dbl> <bch:byt>
#> 1 vec_match(x_unknown, table_unknown) 38.4ms 56.8ms      18.2    7.82MB
#> # … with 1 more variable: `gc/sec` <dbl>

# with Rf_getCharCE()
bench::mark(
  vec_match(x_unknown, table_unknown),
  iterations = 2000
)
#> # A tibble: 1 x 6
#>   expression                             min median `itr/sec` mem_alloc
#>   <bch:expr>                          <bch:> <bch:>     <dbl> <bch:byt>
#> 1 vec_match(x_unknown, table_unknown) 54.9ms 59.4ms      16.8    7.82MB
#> # … with 1 more variable: `gc/sec` <dbl>

@DavisVaughan

Copy link
Copy Markdown
Member Author

use prefixes to indicate input type. Suffixes are for output type.

I hadn't picked up that this was the convention! I'll change it.

Would you call translate_encoding() -> object_translate_encoding(). I thought about that before and was curious.

@lionel-

lionel- commented Sep 6, 2019

Copy link
Copy Markdown
Member

It could be fine as is, or maybe obj_ or sexp_?

@DavisVaughan
DavisVaughan merged commit 5f22971 into r-lib:master Sep 6, 2019
@DavisVaughan
DavisVaughan deleted the char-encoding-match branch September 6, 2019 14:31
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.

vec_unique() is sensitive to the marked encoding, where base::unique() is not

2 participants