Learn R Programming

⚠️There's a newer version (0.14.2) of this package.Take me there.

torch

Installation

Run:

remotes::install_github("mlverse/torch")

At the first package load additional software will be installed.

Example

Currently this package is only a proof of concept and you can only create a Torch Tensor from an R object. And then convert back from a torch Tensor to an R object.

library(torch)
x <- array(runif(8), dim = c(2, 2, 2))
y <- torch_tensor(x, dtype = torch_float64())
y
#> torch_tensor 
#> (1,.,.) = 
#>   0.5406  0.8648
#>   0.3097  0.9715
#> 
#> (2,.,.) = 
#>   0.1309  0.8992
#>   0.4849  0.1902
#> [ CPUDoubleType{2,2,2} ]
identical(x, as_array(y))
#> [1] TRUE

Simple Autograd Example

In the following snippet we let torch, using the autograd feature, calculate the derivatives:

x <- torch_tensor(1, requires_grad = TRUE)
w <- torch_tensor(2, requires_grad = TRUE)
b <- torch_tensor(3, requires_grad = TRUE)
y <- w * x + b
y$backward()
x$grad
#> torch_tensor 
#>  2
#> [ CPUFloatType{1} ]
w$grad
#> torch_tensor 
#>  1
#> [ CPUFloatType{1} ]
b$grad
#> torch_tensor 
#>  1
#> [ CPUFloatType{1} ]

Linear Regression

In the following example we are going to fit a linear regression from scratch using torch’s Autograd.

Note all methods that end with _ (eg. sub_), will modify the tensors in place.

x <- torch_randn(100, 2)
y <- 0.1 + 0.5*x[,1] - 0.7*x[,2]

w <- torch_randn(2, 1, requires_grad = TRUE)
b <- torch_zeros(1, requires_grad = TRUE)

lr <- 0.5
for (i in 1:100) {
  y_hat <- torch_mm(x, w) + b
  loss <- torch_mean((y - y_hat$squeeze(1))^2)
  
  loss$backward()
  
  with_no_grad({
    w$sub_(w$grad*lr)
    b$sub_(b$grad*lr)   
    
    w$grad$zero_()
    b$grad$zero_()
  })
}
print(w)
#> torch_tensor 
#> 1e-09 *
#>  5.2672
#>  -6.7969
#> [ CPUFloatType{2,1} ]
print(b) 
#> torch_tensor 
#> 0.01 *
#> -9.6802
#> [ CPUFloatType{1} ]

Contributing

No matter your current skills it’s possible to contribute to torch development. See the contributing guide for more information.

Copy Link

Version

Install

install.packages('torch')

Monthly Downloads

7,962

Version

0.1.0

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Daniel Falbel

Last Published

September 28th, 2020

Functions in torch (0.1.0)

nn_poisson_nll_loss

Poisson NLL loss
is_torch_qscheme

Checks if an object is a QScheme
nn_init_eye_

Eye initialization
nn_adaptive_max_pool3d

Applies a 3D adaptive max pooling over an input signal composed of several input planes.
autograd_grad

Computes and returns the sum of gradients of outputs w.r.t. the inputs.
lr_multiplicative

Multiply the learning rate of each parameter group by the factor given in the specified function. When last_epoch=-1, sets initial lr as lr.
autograd_set_grad_mode

Set grad mode
is_optimizer

Checks if the object is a torch optimizer
enumerate

Enumerate an iterator
nn_conv_transpose3d

ConvTranpose3D module
enumerate.dataloader

Enumerate an iterator
is_undefined_tensor

Checks if a tensor is undefined
nn_adaptive_max_pool2d

Applies a 2D adaptive max pooling over an input signal composed of several input planes.
nn_avg_pool1d

Applies a 1D average pooling over an input signal composed of several input planes.
nn_dropout

Dropout module
lr_one_cycle

Once cycle learning rate
nn_cosine_embedding_loss

Cosine embedding loss
nn_smooth_l1_loss

Smooth L1 loss
nn_dropout2d

Dropout2D module
torch_set_default_dtype

Gets and sets the default floating point dtype.
dataloader_next

Get the next element of a dataloader iterator
autograd_function

Records operation history and defines formulas for differentiating ops.
autograd_backward

Computes the sum of gradients of given tensors w.r.t. graph leaves.
nn_module_list

Holds submodules in a list.
nn_init_kaiming_normal_

Kaiming normal initialization
dataloader

Data loader. Combines a dataset and a sampler, and provides single- or multi-process iterators over the dataset.
nn_init_xavier_uniform_

Xavier uniform initialization
dataset

An abstract class representing a Dataset.
nn_identity

Identity module
is_torch_memory_format

Check if an object is a memory format
is_torch_device

Checks if object is a device
is_nn_module

Checks if the object is an nn_module
nn_log_sigmoid

LogSigmoid module
nnf_avg_pool3d

Avg_pool3d
install_torch

Install Torch
nn_init_dirac_

Dirac initialization
cuda_current_device

Returns the index of a currently selected device.
nn_adaptive_max_pool1d

Applies a 1D adaptive max pooling over an input signal composed of several input planes.
cuda_device_count

Returns the number of GPUs available.
cuda_is_available

Returns a bool indicating if CUDA is currently available.
load_state_dict

Load a state dict file
nn_init_zeros_

Zeros initialization
nnf_hinge_embedding_loss

Hinge_embedding_loss
nn_log_softmax

LogSoftmax module
dataloader_make_iter

Creates an iterator from a DataLoader
is_torch_layout

Check if an object is a torch layout.
nn_bce_loss

Binary cross entropy loss
nn_glu

GLU module
is_dataloader

Checks if the object is a dataloader
nn_module

Base class for all neural network modules.
is_nn_parameter

Checks if an object is a nn_parameter
nn_ctc_loss

The Connectionist Temporal Classification loss.
nn_embedding

Embedding module
nn_buffer

Creates a nn_buffer
nn_bilinear

Bilinear module
nn_cross_entropy_loss

CrossEntropyLoss module
nn_fractional_max_pool2d

Applies a 2D fractional max pooling over an input signal composed of several input planes.
nn_adaptive_avg_pool2d

Applies a 2D adaptive average pooling over an input signal composed of several input planes.
lr_scheduler

Creates learning rate schedulers
nn_conv_transpose1d

ConvTranspose1D
lr_lambda

Sets the learning rate of each parameter group to the initial lr times a given function. When last_epoch=-1, sets initial lr as lr.
lr_step

Step learning rate decay
nn_bce_with_logits_loss

BCE with logits loss
nn_init_orthogonal_

Orthogonal initialization
nn_conv_transpose2d

ConvTranpose2D module
nn_rrelu

RReLU module
nn_max_pool1d

MaxPool1D module
nn_tanhshrink

Tanhshrink module
nn_hardshrink

Hardshwink module
nn_threshold

Threshoold module
nn_init_ones_

Ones initialization
nn_init_constant_

Constant initialization
nn_tanh

Tanh module
nn_max_unpool2d

Computes a partial inverse of MaxPool2d.
nn_init_trunc_normal_

Truncated normal initialization
nn_multilabel_soft_margin_loss

Multi label soft margin loss
nn_lp_pool1d

Applies a 1D power-average pooling over an input signal composed of several input planes.
nn_init_calculate_gain

Calculate gain
nn_max_unpool3d

Computes a partial inverse of MaxPool3d.
nn_batch_norm1d

BatchNorm1D module
nn_adaptive_avg_pool3d

Applies a 3D adaptive average pooling over an input signal composed of several input planes.
nn_lp_pool2d

Applies a 2D power-average pooling over an input signal composed of several input planes.
nn_init_sparse_

Sparse initialization
nnf_dropout

Dropout
nnf_conv2d

Conv2d
nn_multilabel_margin_loss

Multilabel margin loss
nn_utils_rnn_pack_padded_sequence

Packs a Tensor containing padded sequences of variable length.
nn_mse_loss

MSE loss
nnf_dropout2d

Dropout2d
nn_init_kaiming_uniform_

Kaiming uniform initialization
nn_adaptive_avg_pool1d

Applies a 1D adaptive average pooling over an input signal composed of several input planes.
nn_conv2d

Conv2D module
nn_hardswish

Hardswish module
is_nn_buffer

Checks if the object is a nn_buffer
AutogradContext

Class representing the context.
as_array

Converts to array
nn_hardtanh

Hardtanh module
nnf_alpha_dropout

Alpha_dropout
nn_triplet_margin_with_distance_loss

Triplet margin with distance loss
nn_conv1d

Conv1D module
nn_avg_pool2d

Applies a 2D average pooling over an input signal composed of several input planes.
nn_l1_loss

L1 loss
nn_adaptive_log_softmax_with_loss

AdaptiveLogSoftmaxWithLoss module
nn_gelu

GELU module
nn_relu6

ReLu6 module
nn_margin_ranking_loss

Margin ranking loss
is_torch_dtype

Check if object is a torch data type
nn_celu

CELU module
nn_softmin

Softmin
nn_batch_norm2d

BatchNorm2D
nnf_multilabel_soft_margin_loss

Multilabel_soft_margin_loss
nn_rnn

RNN module
nn_selu

SELU module
nnf_glu

Glu
nn_max_unpool1d

Computes a partial inverse of MaxPool1d.
nn_utils_rnn_pad_sequence

Pad a list of variable length Tensors with padding_value
nnf_interpolate

Interpolate
torch_bitwise_xor

Bitwise_xor
nnf_binary_cross_entropy

Binary_cross_entropy
nn_softplus

Softplus module
nn_dropout3d

Dropout3D module
nnf_adaptive_avg_pool1d

Adaptive_avg_pool1d
nn_avg_pool3d

Applies a 3D average pooling over an input signal composed of several input planes.
nnf_bilinear

Bilinear
nnf_multilabel_margin_loss

Multilabel_margin_loss
nnf_batch_norm

Batch_norm
nn_sigmoid

Sigmoid module
nn_prelu

PReLU module
nn_elu

ELU module
nn_conv3d

Conv3D module
nn_hardsigmoid

Hardsigmoid module
nn_multi_margin_loss

Multi margin loss
nnf_avg_pool1d

Avg_pool1d
nn_init_xavier_normal_

Xavier normal initialization
nnf_triplet_margin_loss

Triplet_margin_loss
nn_kl_div_loss

Kullback-Leibler divergence loss
nn_hinge_embedding_loss

Hinge embedding loss
nn_fractional_max_pool3d

Applies a 3D fractional max pooling over an input signal composed of several input planes.
nnf_dropout3d

Dropout3d
nn_init_uniform_

Uniform initialization
nnf_conv_transpose2d

Conv_transpose2d
nn_multihead_attention

MultiHead attention
nn_utils_rnn_pack_sequence

Packs a list of variable length Tensors
nn_leaky_relu

LeakyReLU module
nn_max_pool3d

Applies a 3D max pooling over an input signal composed of several input planes.
nn_max_pool2d

MaxPool2D module
nn_init_normal_

Normal initialization
nnf_cosine_embedding_loss

Cosine_embedding_loss
nn_sequential

A sequential container
nn_relu

ReLU module
nnf_hardswish

Hardswish
nn_linear

Linear module
nnf_binary_cross_entropy_with_logits

Binary_cross_entropy_with_logits
nn_nll_loss

Nll loss
nnf_grid_sample

Grid_sample
nn_soft_margin_loss

Soft margin loss
nnf_avg_pool2d

Avg_pool2d
nn_parameter

Creates an nn_parameter
torch_dtype

Torch data types
nnf_adaptive_max_pool1d

Adaptive_max_pool1d
nnf_fractional_max_pool2d

Fractional_max_pool2d
nnf_adaptive_max_pool2d

Adaptive_max_pool2d
nn_triplet_margin_loss

Triplet margin loss
nnf_fold

Fold
nnf_multi_margin_loss

Multi_margin_loss
nnf_max_unpool2d

Max_unpool2d
nnf_adaptive_avg_pool2d

Adaptive_avg_pool2d
torch_cat

Cat
nnf_poisson_nll_loss

Poisson_nll_loss
nn_utils_rnn_pad_packed_sequence

Pads a packed batch of variable length sequences.
nnf_ctc_loss

Ctc_loss
nnf_leaky_relu

Leaky_relu
nnf_cross_entropy

Cross_entropy
nnf_linear

Linear
torch_diagonal

Diagonal
nnf_softshrink

Softshrink
nnf_instance_norm

Instance_norm
nnf_embedding

Embedding
nnf_conv_transpose3d

Conv_transpose3d
nnf_hardshrink

Hardshrink
nnf_fractional_max_pool3d

Fractional_max_pool3d
nnf_affine_grid

Affine_grid
nnf_mse_loss

Mse_loss
nnf_pdist

Pdist
nnf_logsigmoid

Logsigmoid
nnf_max_pool1d

Max_pool1d
nnf_soft_margin_loss

Soft_margin_loss
nnf_adaptive_avg_pool3d

Adaptive_avg_pool3d
nnf_conv3d

Conv3d
nnf_embedding_bag

Embedding_bag
nnf_adaptive_max_pool3d

Adaptive_max_pool3d
nnf_kl_div

Kl_div
nnf_softplus

Softplus
nnf_lp_pool1d

Lp_pool1d
nn_pairwise_distance

Pairwise distance
tensor_dataset

Dataset wrapping tensors.
nnf_max_pool2d

Max_pool2d
torch_addbmm

Addbmm
nnf_multi_head_attention_forward

Multi head attention forward
torch_conv_transpose1d

Conv_transpose1d
nnf_lp_pool2d

Lp_pool2d
nnf_nll_loss

Nll_loss
nnf_softmin

Softmin
torch_bernoulli

Bernoulli
%>%

Pipe operator
nnf_unfold

Unfold
torch_argmin

Argmin
torch_avg_pool1d

Avg_pool1d
torch_addcdiv

Addcdiv
torch_generator

Create a Generator object
optim_adam

Implements Adam algorithm.
nnf_hardsigmoid

Hardsigmoid
nnf_cosine_similarity

Cosine_similarity
nnf_pad

Pad
torch_baddbmm

Baddbmm
nnf_prelu

Prelu
torch_bitwise_or

Bitwise_or
nnf_softmax

Softmax
nnf_celu

Celu
nn_softmax2d

Softmax2d module
nn_softsign

Softsign module
nn_softmax

Softmax module
nnf_conv_tbc

Conv_tbc
nn_softshrink

Softshrink module
nnf_hardtanh

Hardtanh
nnf_conv1d

Conv1d
nnf_local_response_norm

Local_response_norm
torch_argsort

Argsort
nnf_group_norm

Group_norm
nnf_softsign

Softsign
torch_conv2d

Conv2d
torch_histc

Histc
torch_cdist

Cdist
nnf_normalize

Normalize
torch_arange

Arange
nnf_margin_ranking_loss

Margin_ranking_loss
nnf_rrelu

Rrelu
nnf_conv_transpose1d

Conv_transpose1d
torch_blackman_window

Blackman_window
torch_cumsum

Cumsum
torch_empty_like

Empty_like
nnf_triplet_margin_with_distance_loss

Triplet margin with distance loss
torch_allclose

Allclose
torch_frac

Frac
torch_bitwise_not

Bitwise_not
torch_angle

Angle
torch_digamma

Digamma
nnf_gelu

Gelu
nnf_max_unpool3d

Max_unpool3d
torch_adaptive_avg_pool1d

Adaptive_avg_pool1d
nnf_l1_loss

L1_loss
torch_exp

Exp
nnf_elu

Elu
optim_required

Dummy value indicating a required value.
nnf_layer_norm

Layer_norm
torch_atan2

Atan2
nnf_one_hot

One_hot
nnf_selu

Selu
torch_addcmul

Addcmul
nnf_tanhshrink

Tanhshrink
nnf_threshold

Threshold
nnf_log_softmax

Log_softmax
torch_addmm

Addmm
torch_clamp

Clamp
torch_conv_tbc

Conv_tbc
torch_eq

Eq
torch_asin

Asin
torch_cholesky_solve

Cholesky_solve
torch_iinfo

Integer type info
torch_bmm

Bmm
torch_argmax

Argmax
torch_atan

Atan
nnf_pairwise_distance

Pairwise_distance
nnf_gumbel_softmax

Gumbel_softmax
nnf_max_pool3d

Max_pool3d
torch_abs

Abs
nnf_sigmoid

Sigmoid
torch_combinations

Combinations
nnf_max_unpool1d

Max_unpool1d
nnf_pixel_shuffle

Pixel_shuffle
torch_chunk

Chunk
torch_celu

Celu
nnf_relu

Relu
torch_qr

Qr
nnf_relu6

Relu6
optim_sgd

SGD optimizer
torch_conv3d

Conv3d
torch_full_like

Full_like
torch_as_strided

As_strided
torch_broadcast_tensors

Broadcast_tensors
torch_cummax

Cummax
torch_cummin

Cummin
torch_relu_

Relu_
torch_eye

Eye
torch_conv_transpose2d

Conv_transpose2d
torch_cholesky

Cholesky
torch_chain_matmul

Chain_matmul
torch_rfft

Rfft
torch_dist

Dist
torch_irfft

Irfft
torch_empty_strided

Empty_strided
torch_cumprod

Cumprod
torch_expm1

Expm1
torch_addmv

Addmv
nnf_smooth_l1_loss

Smooth_l1_loss
torch_div

Div
torch_cholesky_inverse

Cholesky_inverse
torch_layout

Creates the corresponding layout
torch_flip

Flip
torch_ifft

Ifft
torch_conv_transpose3d

Conv_transpose3d
torch_diagflat

Diagflat
torch_can_cast

Can_cast
torch_bincount

Bincount
torch_acos

Acos
torch_addr

Addr
torch_celu_

Celu_
torch_floor

Floor
torch_round

Round
torch_floor_divide

Floor_divide
torch_geqrf

Geqrf
torch_equal

Equal
torch_flatten

Flatten
torch_fmod

Fmod
torch_isfinite

Isfinite
torch_median

Median
torch_quantize_per_tensor

Quantize_per_tensor
torch_logical_not

Logical_not
torch_eig

Eig
torch_index_select

Index_select
torch_erfinv

Erfinv
torch_isinf

Isinf
torch_meshgrid

Meshgrid
torch_lgamma

Lgamma
torch_remainder

Remainder
torch_bitwise_and

Bitwise_and
torch_is_complex

Is_complex
torch_lerp

Lerp
torch_log

Log
torch_ceil

Ceil
torch_add

Add
torch_bartlett_window

Bartlett_window
torch_einsum

Einsum
torch_imag

Imag
torch_logdet

Logdet
torch_masked_select

Masked_select
torch_inverse

Inverse
torch_save

Saves an object to a disk file.
torch_finfo

Floating point type info
torch_conj

Conj
torch_ger

Ger
torch_dot

Dot
torch_mv

Mv
torch_conv1d

Conv1d
torch_cosine_similarity

Cosine_similarity
torch_log1p

Log1p
torch_max

Max
torch_log10

Log10
torch_logical_or

Logical_or
torch_le

Le
torch_quantize_per_channel

Quantize_per_channel
torch_logsumexp

Logsumexp
torch_orgqr

Orgqr
torch_sparse_coo_tensor

Sparse_coo_tensor
torch_matmul

Matmul
torch_logical_and

Logical_and
torch_mean

Mean
torch_cross

Cross
torch_full

Full
torch_mvlgamma

Mvlgamma
torch_det

Det
torch_nonzero

Nonzero
torch_neg

Neg
torch_rand_like

Rand_like
torch_qscheme

Creates the corresponding Scheme object
torch_min

Min
torch_lstsq

Lstsq
torch_device

Create a Device object
torch_fft

Fft
torch_mm

Mm
torch_empty

Empty
torch_isnan

Isnan
torch_reshape

Reshape
torch_prod

Prod
torch_ormqr

Ormqr
torch_cartesian_prod

Cartesian_prod
torch_diag

Diag
torch_load

Loads a saved object
torch_randperm

Randperm
torch_promote_types

Promote_types
torch_range

Range
torch_matrix_rank

Matrix_rank
torch_kthvalue

Kthvalue
torch_hamming_window

Hamming_window
torch_cosh

Cosh
torch_hann_window

Hann_window
torch_cos

Cos
torch_narrow

Narrow
torch_split

Split
torch_log2

Log2
torch_mode

Mode
torch_unsqueeze

Unsqueeze
torch_lt

Lt
torch_matrix_power

Matrix_power
torch_result_type

Result_type
torch_ones

Ones
torch_memory_format

Memory format
torch_erf

Erf
torch_diag_embed

Diag_embed
torch_tan

Tan
torch_selu_

Selu_
torch_trapz

Trapz
torch_ne

Ne
torch_rand

Rand
torch_sinh

Sinh
torch_sigmoid

Sigmoid
torch_gather

Gather
torch_erfc

Erfc
torch_gt

Gt
torch_ge

Ge
torch_lu_solve

Lu_solve
torch_slogdet

Slogdet
torch_var_mean

Var_mean
torch_sum

Sum
torch_is_floating_point

Is_floating_point
torch_logspace

Logspace
torch_selu

Selu
torch_tanh

Tanh
torch_transpose

Transpose
torch_unbind

Unbind
torch_trace

Trace
torch_unique_consecutive

Unique_consecutive
torch_randn

Randn
torch_solve

Solve
torch_lu

LU
torch_ones_like

Ones_like
torch_linspace

Linspace
torch_stft

Stft
torch_randint

Randint
torch_randint_like

Randint_like
torch_squeeze

Squeeze
torch_rot90

Rot90
torch_sin

Sin
torch_tensordot

Tensordot
torch_tensor

Converts R objects to a torch tensor
with_enable_grad

Enable grad
torch_zeros_like

Zeros_like
torch_where

Where
torch_pdist

Pdist
torch_is_installed

Verifies if torch is installed
torch_poisson

Poisson
torch_logical_xor

Logical_xor
torch_take

Take
with_no_grad

Temporarily modify gradient recording.
torch_pow

Pow
torch_norm

Norm
torch_normal

Normal
torch_mul

Mul
torch_roll

Roll
torch_triangular_solve

Triangular_solve
torch_symeig

Symeig
torch_svd

Svd
torch_renorm

Renorm
torch_polygamma

Polygamma
torch_stack

Stack
torch_triu_indices

Triu_indices
torch_triu

Triu
torch_zeros

Zeros
torch_manual_seed

Sets the seed for generating random numbers.
torch_randn_like

Randn_like
torch_multinomial

Multinomial
torch_sign

Sign
torch_pixel_shuffle

Pixel_shuffle
torch_repeat_interleave

Repeat_interleave
torch_std

Std
torch_pinverse

Pinverse
torch_sort

Sort
torch_std_mean

Std_mean
torch_tril

Tril
torch_tril_indices

Tril_indices
torch_var

Var
torch_real

Real
torch_reciprocal

Reciprocal
torch_rrelu_

Rrelu_
torch_reduction

Creates the reduction objet
torch_square

Square
torch_relu

Relu
torch_sqrt

Sqrt
torch_rsqrt

Rsqrt
torch_t

T
torch_true_divide

TRUE_divide
torch_topk

Topk
torch_threshold_

Threshold_
torch_trunc

Trunc