Skip to content

Instantly share code, notes, and snippets.

@juliasilge
Created September 21, 2022 20:59
Show Gist options
  • Save juliasilge/b4c04c80eed1481454e273be833ae3e1 to your computer and use it in GitHub Desktop.
Save juliasilge/b4c04c80eed1481454e273be833ae3e1 to your computer and use it in GitHub Desktop.
Create a vetiver Dockerfile that mounts the pin inside

First in R:

library(tidymodels)
data(Sacramento, package = "modeldata")

rf_spec <- rand_forest(mode = "regression")
rf_form <- price ~ type + sqft + beds + baths

rf_fit <-
  workflow(rf_form, rf_spec) %>%
  fit(Sacramento)

library(vetiver)
#> 
#> Attaching package: 'vetiver'
#> The following object is masked from 'package:tune':
#> 
#>     load_pkgs
v <- vetiver_model(rf_fit, "sacramento-houses")

library(pins)
b <- board_folder("my-pins")
b %>% vetiver_pin_write(v)
#> Creating new version '20220921T205544Z-52d58'
#> Writing to pin 'sacramento-houses'
#> 
#> Create a Model Card for your published model
#> • Model Cards provide a framework for transparent, responsible reporting
#> • Use the vetiver `.Rmd` template as a place to start

vetiver_write_plumber(b, "sacramento-houses", rsconnect = FALSE)
vetiver_write_docker(v)
#> * Lockfile written to 'vetiver_renv.lock'.

Created on 2022-09-21 with reprex v2.0.2

plumber.R looks like this:

# Generated by the vetiver package; edit with care

library(pins)
library(plumber)
library(rapidoc)
library(vetiver)
b <- board_folder(path = "my-pins")
v <- vetiver_pin_read(b, "sacramento-houses")

#* @plumber
function(pr) {
    pr %>% vetiver_api(v)
}

Open and edit the Dockerfile to mount the pin directory inside the container:

# Generated by the vetiver package; edit with care

FROM rocker/r-ver:4.2.1
ENV RENV_CONFIG_REPOS_OVERRIDE https://packagemanager.rstudio.com/cran/latest

RUN apt-get update -qq && apt-get install -y --no-install-recommends \
  libcurl4-openssl-dev \
  libicu-dev \
  libsodium-dev \
  libssl-dev \
  make \
  zlib1g-dev \
  && apt-get clean

COPY vetiver_renv.lock renv.lock
RUN Rscript -e "install.packages('renv')"
RUN Rscript -e "renv::restore()"
ADD my-pins /opt/ml/my-pins
COPY plumber.R /opt/ml/plumber.R
EXPOSE 8000
ENTRYPOINT ["R", "-e", "pr <- plumber::plumb('/opt/ml/plumber.R'); pr$run(host = '0.0.0.0', port = 8000)"]

What I changed was ADD my-pins /opt/ml/my-pins; this mounts the directory where your pins are stored inside the container.

Now you can build and then run the container:

docker build --platform linux/amd64 -t pin-inside-demo .   
docker run --rm -p 8000:8000 pin-inside-demo

You don't need to authenticate in this case because the model object is actually inside the container.

@wdefreitas
Copy link

This is awesome!! Thank you so much for this!! With that one little change I was able to get it to work and was able to play around with the predictions. Thanks a million!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment