Package 'TabICL2'

Title: A TabICL2 tabular foundation model
Description: A TabICL2 tabular foundation model.
Authors: Christophe Regouby [aut, cre]
Maintainer: Christophe Regouby <[email protected]>
License: MIT + file LICENSE
Version: 0.0.0.9000
Built: 2026-11-22 17:15:07 UTC
Source: https://github.com/cregouby/TabICL2

Help Index


Manages asynchronous GPU-to-CPU copies using CUDA streams

Description

Uses a dedicated CUDA stream for device-to-host (D2H) transfers, allowing GPU computation to overlap with data movement.

Value

An AsyncCopyManager object.

Methods

reset_bytes_counter()

Reset the bytes written counter

clear()

Clear pending copies without completing them

Methods

Public methods


AsyncCopyManager$new()

Usage
AsyncCopyManager$new(device, max_pending = 4L, buffer_pool = NULL)
Arguments
device

torch.device. CUDA device.

max_pending

Integer. Max pending copies.

buffer_pool

PinnedBufferPool or NULL.


AsyncCopyManager$submit_copy()

Usage
AsyncCopyManager$submit_copy(gpu_tensor, target, indices)
Arguments
gpu_tensor

Tensor. Source tensor on GPU.

target

Tensor or DiskTensor. Target storage.

indices

List. Indices where to write in target.


AsyncCopyManager$drain_all()

Usage
AsyncCopyManager$drain_all()
Returns

Numeric. Total bytes written in MB.


AsyncCopyManager$get_bytes_written()

Usage
AsyncCopyManager$get_bytes_written()
Returns

Numeric.


AsyncCopyManager$reset_bytes_counter()

Usage
AsyncCopyManager$reset_bytes_counter()
Returns

NULL


AsyncCopyManager$clear()

Usage
AsyncCopyManager$clear()
Returns

NULL


AsyncCopyManager$clone()

The objects of this class are cloneable with this method.

Usage
AsyncCopyManager$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


Distribution-aware Column-wise Embedding Module

Description

This module maps scalar cells to high-dimensional embeddings using a shared Set Transformer. It supports feature grouping, target-aware encoding, and affine transformation of features.

Usage

ColEmbedding(
  embed_dim,
  num_blocks,
  nhead,
  dim_feedforward,
  num_inds,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  affine = TRUE,
  feature_group = FALSE,
  feature_group_size = 3L,
  target_aware = FALSE,
  max_classes = 10L,
  reserve_cls_tokens = 4L,
  ssmax = FALSE,
  mixed_radix_ensemble = TRUE,
  recompute = FALSE
)

Arguments

embed_dim

Integer. Embedding dimension.

num_blocks

Integer. Number of induced self-attention blocks.

nhead

Integer. Number of attention heads.

dim_feedforward

Integer. Feedforward network dimension.

num_inds

Integer. Number of inducing points.

dropout

Numeric. Dropout probability (default: 0.0).

activation

Character. Activation function (default: "gelu").

norm_first

Logical. Pre-norm architecture (default: TRUE).

bias_free_ln

Logical. Remove LayerNorm bias (default: FALSE).

affine

Logical. Compute features * W + b (default: TRUE).

feature_group

Logical or Character. Grouping mode:

  • FALSE: No grouping.

  • TRUE or "same": Circular permutation.

  • "valid": Padding and reshaping.

feature_group_size

Integer. Size of feature groups (default: 3L).

target_aware

Logical. Use target info (default: FALSE).

max_classes

Integer. Number of classes (default: 10L).

reserve_cls_tokens

Integer. CLS token slots (default: 4L).

ssmax

Logical or Character. Scalable softmax type.

mixed_radix_ensemble

Logical. Mixed-radix ensembling (default: TRUE).

recompute

Logical. Gradient checkpointing (default: FALSE).

Value

An nn_module object.


Create an SSMax Layer by Type

Description

Factory function that instantiates the appropriate SSMax* module (or NULL) from a string identifier.

Usage

create_ssmax_layer(ssmax_type, num_heads, embed_dim)

Arguments

ssmax_type

character(1) One of: "none", "ssmax", "ssmax-mlp", "ssmax-mlp-elementwise", "qassmax-mlp", "qassmax-mlp-elementwise".

num_heads

integer(1) Number of attention heads.

embed_dim

integer(1) Total embedding dimension (num_heads * head_dim).

Value

An nn_module instance, or NULL when ssmax_type = "none".

See Also

SSMax, SSMaxMLP, QASSMaxMLP


A tensor backed by a memory-mapped file on disk

Description

Uses R's bigmemory or base file I/O for storage and provides a torch tensor interface for seamless integration. This enables storing tensors larger than available RAM by using disk space.

Value

A DiskTensor object.

Methods

flush()

Flush changes to disk

Methods

Public methods


DiskTensor$new()

Usage
DiskTensor$new(shape, dtype, path, cleanup = TRUE)
Arguments
shape

Integer vector. Shape of the tensor.

dtype

torch.dtype. Data type.

path

Character. File path.

cleanup

Logical. Auto-cleanup on GC.


DiskTensor$tensor()

Usage
DiskTensor$tensor()
Returns

A torch tensor.


DiskTensor$get()

Usage
DiskTensor$get(indices)
Arguments
indices

List of indices or slices.

Returns

A torch tensor.


DiskTensor$set()

Usage
DiskTensor$set(indices, value)
Arguments
indices

List of indices.

value

Tensor. Value to write.


DiskTensor$flush()

Usage
DiskTensor$flush()
Returns

Invisible flush to disk


DiskTensor$nbytes()

Usage
DiskTensor$nbytes()
Returns

Integer. Size in bytes.


DiskTensor$clone()

The objects of this class are cloneable with this method.

Usage
DiskTensor$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Note

R6 doesn't support [ overloading directly; use ⁠$get()⁠ instead.

Examples

## Not run: 
# Create a disk-backed tensor
dt <- disk_tensor$new(c(1000L, 128L), torch_float(), "/tmp/my_tensor.mmap")

# Write data (automatically persists to disk)
dt[1:100, ..] <- torch_randn(100L, 128L)

# Read data
x <- dt[1:50, ..]$tensor

# Flush changes to disk
dt$flush()

## End(Not run)

Encoder

Description

Stack of multihead attention blocks.

Usage

Encoder(
  num_blocks,
  d_model,
  nhead,
  dim_feedforward,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  use_rope = FALSE,
  rope_base = 100000L,
  rope_interleaved = TRUE,
  ssmax = FALSE,
  recompute = FALSE
)

Arguments

num_blocks

Integer. Number of multihead attention blocks in the stack.

d_model

Integer. Model dimension.

nhead

Integer. Number of attention heads and should be a divisor of d_model.

dim_feedforward

Integer. Dimension of the feedforward network in each block.

dropout

Float, default 0. Dropout probability.

activation

Character string or unary function, default "gelu". The activation function used in the feedforward network.

norm_first

Logical, default TRUE. If TRUE, uses pre-norm architecture (LayerNorm before attention and feedforward).

bias_free_ln

Logical, default FALSE. If TRUE, removes bias from all LayerNorm layers.

use_rope

Logical, default FALSE. Whether to use rotary positional encoding.

rope_base

Integer, default 100000L. A base scaling factor for rotary position encoding.

rope_interleaved

Logical, default TRUE. If TRUE, uses interleaved rotation where dimension pairs are (1,2), (3,4), etc. If FALSE, uses non-interleaved rotation where the embedding is split into first half and second half.

ssmax

Logical or character string, default FALSE. Type of scalable softmax to use. If TRUE, equivalent to "qassmax-mlp-elementwise". If FALSE, equivalent to "none". If a string, uses the specified scalable softmax type. Options include: "none", "ssmax", "ssmax-mlp", "ssmax-mlp-elementwise", "qassmax-mlp", "qassmax-mlp-elementwise".

recompute

Logical, default FALSE. If TRUE, uses gradient checkpointing to save memory at the cost of additional computation.

Value

An nn_module instance of class Encoder.

Methods

Usage

enc <- Encoder(num_blocks = 6L, d_model = 128L, nhead = 8L, dim_feedforward = 256L)
enc$forward(src, train_size = NULL)
enc$forward_with_cache(src, icl_cache, train_size, use_cache, store_cache)

See Also

multihead_attention_block, RotaryEmbedding, KVCache, KVCacheEntry


Enforce monotonicity of quantiles to fix crossing

Description

Enforce monotonicity of quantiles to fix crossing

Usage

enforce_monotonicity(quantiles, method = "sort", weights = NULL)

Arguments

quantiles

Tensor. Predicted quantiles that may have crossing violations. Shape: ⁠(*batch_shape, num_quantiles)⁠.

method

Character. Method for fixing crossing:

  • "sort": Sort values (fast, default)

  • "isotonic": Pool Adjacent Violators (optimal L2, O(N))

  • "cummax": Cumulative maximum (fast but distorts distribution)

weights

Tensor or NULL. Case weights for PAVA method. Shape: ⁠(*batch_shape, num_quantiles)⁠ or NULL.

Value

Tensor. Monotonically non-decreasing quantiles. Shape: ⁠(*batch_shape, num_quantiles)⁠.


Temporarily enable or disable Flash Attention 3

Description

This function provides a simple save/restore pattern to control whether Flash Attention 3 is used during attention computation.

Temporarily enable or disable Flash Attention 3 during inference.

Usage

flash_attn3_toggle(enabled)

flash_attn3_toggle(enabled)

Arguments

enabled

Logical. Whether to enable FA3.

Value

A function that, when called, restores the previous setting.

Function. Restoration function to call when done.

Examples

## Not run: 
# Temporarily disable Flash Attention 3
restore <- flash_attn3_toggle(FALSE)
# ... run inference ...
restore()  # Restore previous setting

# Or use with on.exit() for automatic restoration
old <- flash_attn3_toggle(FALSE)
on.exit(old(), add = TRUE)
# ... code that uses attention ...

## End(Not run)

## Not run: 
# Temporarily disable FA3
restore <- flash_attn3_toggle(FALSE)
# ... run inference ...
restore()  # Restore previous setting

## End(Not run)

Dataset-wise In-Context Learning Module

Description

Implements in-context learning for tabular data using transformer architecture. Supports both classification (with hierarchical classification for many classes) and regression tasks. Includes KV caching for efficient inference.

Usage

ICLearning(
  max_classes,
  out_dim,
  d_model,
  num_blocks,
  nhead,
  dim_feedforward,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  ssmax = FALSE,
  recompute = FALSE
)

Arguments

max_classes

Integer. Determines task type and output behavior:

  • If max_classes = 0: Regression using quantile prediction

  • If max_classes > 0: Classification. Specifies native class support. If dataset classes exceed this, hierarchical classification is used.

out_dim

Integer. Output dimension of the model.

d_model

Integer. Model dimension for the transformer.

num_blocks

Integer. Number of transformer blocks.

nhead

Integer. Number of attention heads.

dim_feedforward

Integer. Feedforward network dimension.

dropout

Numeric. Dropout probability (default: 0.0).

activation

Character or function. Activation function (default: "gelu").

norm_first

Logical. Use pre-norm architecture (default: TRUE).

bias_free_ln

Logical. Remove bias from LayerNorm (default: FALSE).

ssmax

Logical or character. Scalable softmax type (default: FALSE).

recompute

Logical. Use gradient checkpointing (default: FALSE).

Value

An nn_module object.

Methods

forward(R, y_train, ...)

Main forward pass

prepare_repr_cache(R, y_train)

Prepare representation cache

forward_with_repr_cache(...)

Forward with representation cache

forward_with_cache(...)

Forward with KV cache

Examples

## Not run: 
icl <- ICLearning(
  max_classes = 10L,
  out_dim = 10L,
  d_model = 128L,
  num_blocks = 6L,
  nhead = 8L,
  dim_feedforward = 512L
)

## End(Not run)

Induced Self-Attention Block for efficient O(n) attention

Description

This module implements a bottleneck attention mechanism using a small set of learned inducing points that mediate interactions between input elements. The complexity is reduced from O(n²) to O(n) by:

  1. Projecting inputs onto inducing points (size m << n)

  2. Propagating information through these inducing points

  3. Projecting back to the original sequence

Usage

induced_self_attention_block(
  d_model,
  nhead,
  dim_feedforward,
  num_inds,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  ssmax = FALSE,
  skip_value = -100
)

Arguments

d_model

Integer. Model dimension.

nhead

Integer. Number of attention heads.

dim_feedforward

Integer. Dimension of the feedforward network.

num_inds

Integer. Number of inducing points (controls capacity vs. efficiency).

dropout

Numeric. Dropout probability (default: 0.0).

activation

Character or function. Activation function for feedforward (default: "gelu").

norm_first

Logical. If TRUE, uses pre-norm architecture (default: TRUE).

bias_free_ln

Logical. If TRUE, removes bias from all LayerNorm layers (default: FALSE).

ssmax

Logical or character. Type of scalable softmax to use in attention. Note that only the first attention layer uses SSMax (default: FALSE).

skip_value

Numeric. Value used to mark inputs that should be skipped (default: -100.0).

Value

A nn_module for induced self-attention.

References

Lee et al. "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks", ICML 2019


Manages memory-efficient model inference by automatically batching inputs

Description

Service class that orchestrates memory-efficient inference through automatic batching, flexible offloading (GPU/CPU/disk), and OOM recovery.

Format

An R6Class generator object.

Methods

initialize(enc_name, out_dim, out_no_seq)

Create a new inference manager

configure(...)

Configure inference parameters

forward(forward_fn, inputs, auto_batch, output_repeat)

Run inference

Examples

## Not run: 
mgr <- inference_manager$new(enc_name = "tf_col", out_dim = 128L)
mgr$configure(offload = "auto", verbose = TRUE)

## End(Not run)

Concatenate Multiple KVCache Objects

Description

Concatenate multiple KVCache objects along a dimension.

Usage

kv_cache_concat(caches, dim = 1)

Arguments

caches

List of KVCache instances. All must have the same layer indices.

dim

Integer. Dimension to concatenate along (batch dimension). Default is 1 (R 1-based; corresponds to Python dim 0).

Value

A new KVCache with concatenated entries at each layer index.


Concatenate Multiple KVCacheEntry Objects

Description

Concatenate multiple KVCacheEntry objects along a dimension.

Usage

kv_cache_entry_concat(entries, dim = 1)

Arguments

entries

List of KVCacheEntry instances. All valid entries are concatenated; invalid ones are silently skipped.

dim

Integer. Dimension to concatenate along. Default is 1 (batch dimension in R 1-based indexing; corresponds to Python dim 0).

Value

A new KVCacheEntry with concatenated key and value tensors. Returns an empty entry if no valid entries are found.

Examples

## Not run: 
  e1 <- KVCacheEntry$new(key = torch_randn(2, 4, 10, 64),
                         value = torch_randn(2, 4, 10, 64))
  e2 <- KVCacheEntry$new(key = torch_randn(3, 4, 10, 64),
                         value = torch_randn(3, 4, 10, 64))
  e_cat <- kv_cache_entry_concat(list(e1, e2), dim = 1)

## End(Not run)

Base Class for Key-Value Caches

Description

Provides common structure and operations for caches that store mappings from layer/block index to cached key-value projections.

Format

An R6::R6Class object.

Details

Layer indices are stored as character strings in the named list kv, since R lists cannot have integer names that start from 0.

Public fields

kv

Named list mapping layer index (character) to KVCacheEntry.

Methods

Public methods


KVCache$new()

Create a new KVCache.

Usage
KVCache$new(kv = list())
Arguments
kv

Optional named list of KVCacheEntry instances.


KVCache$is_populated()

Check if this cache has valid entries.

Returns TRUE when the cache contains data (use_cache mode). Returns FALSE when the cache is empty (store_cache mode).

Usage
KVCache$is_populated()
Returns

Logical scalar.


KVCache$slice()

Slice all entries along batch dimensions.

Returns a new cache of the same class with sliced entries.

Usage
KVCache$slice(indices)
Arguments
indices

Indices for slicing.

Returns

A new KVCache instance.


KVCache$write()

Write batch-sliced entries into this pre-allocated cache.

Usage
KVCache$write(indices, other)
Arguments
indices

Indices for writing.

other

A KVCache instance to write from.

Returns

Invisible self (for method chaining).


KVCache$to()

Move all entries to the given device and optionally cast dtype.

Returns a new cache of the same class.

Usage
KVCache$to(device, dtype = NULL)
Arguments
device

Device string.

dtype

Optional torch_dtype.

Returns

A new KVCache instance.


KVCache$preallocate()

Pre-allocate entries in this cache based on shapes from a reference.

K/V tensors always have shape (*batch, num_heads, seq_len, head_dim). This method keeps the last three dimensions from the reference entry and prepends batch_shape as the leading dimensions.

Usage
KVCache$preallocate(reference, batch_shape, device = "cpu", dtype = NULL)
Arguments
reference

A KVCache from a single batch whose entry shapes are used as a template.

batch_shape

Integer vector. The full batch shape for leading dims.

device

Device on which to allocate tensors. Default "cpu".

dtype

Optional torch_dtype. If NULL, uses reference entry dtype.

Returns

Invisible self (for method chaining).


KVCache$clone()

The objects of this class are cloneable with this method.

Usage
KVCache$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

## Not run: 
  cache <- KVCache$new()
  cache$kv[["1"]] <- KVCacheEntry$new(
    key = torch_randn(2, 4, 10, 64),
    value = torch_randn(2, 4, 10, 64)
  )
  cache$is_populated()

## End(Not run)

A Single Key-Value Cache Entry for an Attention Layer

Description

Stores cached key and value projections from an attention layer.

Format

An R6::R6Class object.

Details

Key and value tensors have shape (batch, num_heads, seq_len, head_dim).

Public fields

key

Cached key projections. A torch_tensor or NULL.

value

Cached value projections. A torch_tensor or NULL.

Methods

Public methods


KVCacheEntry$new()

Create a new KVCacheEntry.

Usage
KVCacheEntry$new(key = NULL, value = NULL)
Arguments
key

Optional torch_tensor.

value

Optional torch_tensor.


KVCacheEntry$is_valid()

Check if this cache entry contains valid data.

Usage
KVCacheEntry$is_valid()
Returns

Logical scalar.


KVCacheEntry$slice()

Slice key/value along batch dimensions.

Returns a new KVCacheEntry with sliced tensors, or an empty entry if this entry is not valid.

Usage
KVCacheEntry$slice(indices, drop = FALSE)
Arguments
indices

Indices for slicing. Can be an integer vector, a torch_tensor, or use .. for all elements.

drop

drop unitary dimension

Returns

A new KVCacheEntry instance.


KVCacheEntry$write()

Write a batch slice into this entry.

Usage
KVCacheEntry$write(indices, other)
Arguments
indices

Indices for writing.

other

A KVCacheEntry instance to write from.

Returns

Invisible self (for method chaining).


KVCacheEntry$to()

Move this entry to the given device and optionally cast dtype.

Returns a new KVCacheEntry.

Usage
KVCacheEntry$to(device, dtype = NULL)
Arguments
device

Device string, e.g. "cpu" or "cuda".

dtype

Optional torch_dtype.

Returns

A new KVCacheEntry instance.


KVCacheEntry$clone()

The objects of this class are cloneable with this method.

Usage
KVCacheEntry$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

## Not run: 
  entry <- KVCacheEntry$new(
    key = torch_randn(2, 4, 10, 64),
    value = torch_randn(2, 4, 10, 64)
  )
  entry$is_valid()

## End(Not run)

Enhanced multi-head attention with RoPE, scalable softmax, and KV caching

Description

Enhanced multi-head attention with RoPE, scalable softmax, and KV caching

Usage

multihead_attention(embed_dim, num_heads, dropout = 0, ssmax = FALSE)

Arguments

embed_dim

Integer. Model dimension (total size of each attention head combined).

num_heads

Integer. Number of attention heads.

dropout

Numeric. Dropout probability applied to attention weights (default: 0.0).

ssmax

Logical or character. Type of scalable softmax to use:

  • FALSE or "none": No scaling applied

  • TRUE or "qassmax-mlp-elementwise": Elementwise query-aware scaling

  • Other strings: specific scalable softmax type (default: FALSE)

Value

A nn_module for multi-head attention with advanced features.

Note

The implementation always uses batch_first = TRUE, so input tensors have shape ⁠(.., seq_len, embed_dim)⁠.

References

  1. Su et al., "RoFormer: Enhanced Transformer with Rotary Position Embedding"

  2. Liu et al., "Scalable-Softmax Is Superior for Attention"


Attention block supporting RoPE, scalable softmax, and KV caching

Description

Attention block supporting RoPE, scalable softmax, and KV caching

Usage

multihead_attention_block(
  d_model,
  nhead,
  dim_feedforward,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  ssmax = FALSE
)

Arguments

d_model

Integer. Model dimension.

nhead

Integer. Number of attention heads.

dim_feedforward

Integer. Dimension of the feedforward network.

dropout

Numeric. Dropout probability (default: 0.0).

activation

Character or function. Activation function for feedforward: "relu", "gelu", or a unary callable (default: "gelu").

norm_first

Logical. If TRUE, uses pre-norm architecture (LayerNorm before attention and feedforward) (default: TRUE).

bias_free_ln

Logical. If TRUE, removes bias from all LayerNorm layers (default: FALSE).

ssmax

Logical or character. Type of scalable softmax to use in attention (default: FALSE).

Value

A nn_module for transformer encoder layer with advanced features.


NanoTabICL v2 Model

Description

A compact tabular in-context learning model with column, row, and ICL attention blocks.

Usage

NanoTabICLv2(
  max_classes,
  out_dim,
  embed_dim = 128L,
  col_n_block = 3L,
  row_n_block = 3L,
  icl_n_block = 12L,
  col_n_head = 8L,
  row_n_head = 8L,
  icl_n_head = 8L,
  feature_group_size = 3L,
  col_n_cls = 4L,
  row_n_cls = 128L
)

Arguments

max_classes

Maximum number of classes (0 for regression)

out_dim

Output dimension (n_classes for classification, n_quantiles for regression)

embed_dim

Embedding dimension for features

col_n_block

Number of column transformer blocks

row_n_block

Number of row transformer blocks

icl_n_block

Number of ICL transformer blocks

col_n_head

Number of attention heads for column blocks

row_n_head

Number of attention heads for row blocks

icl_n_head

Number of attention heads for ICL blocks

feature_group_size

Size of feature groups for repeated grouping

col_n_cls

Number of CLS tokens per column

row_n_cls

Number of inducing vectors for column attention

Value

An nn_module ready for training/inference


One-hot encoding combined with linear projection

Description

Combines one-hot encoding and linear projection in a single efficient operation to convert categorical indices to embeddings.

Usage

one_hot_and_linear(num_classes, embed_dim)

Arguments

num_classes

Integer. Number of distinct categories for one-hot encoding.

embed_dim

Integer. Output embedding dimension.

Value

A nn_module that transforms integer indices to dense embeddings.

Examples

## Not run: 
encoder <- one_hot_and_linear(num_classes = 10L, embed_dim = 32L)
indices <- torch_randint(1L, 11L, c(2L, 20L))  # [batch, seq_len]
embeddings <- encoder(indices)  # [batch, seq_len, embed_dim]

## End(Not run)

Pool of pinned CPU memory buffers for efficient GPU-to-CPU transfers

Description

Pinned (page-locked) memory enables faster async GPU-to-CPU data transfers by allowing the GPU to directly access the CPU memory without involving the CPU. This class maintains a pool of such buffers to avoid the overhead of repeated allocation and deallocation.

Value

A PinnedBufferPool object.

Methods

Public methods


PinnedBufferPool$new()

Usage
PinnedBufferPool$new(max_buffers_per_shape = 4L)
Arguments
max_buffers_per_shape

Integer. Maximum buffers per (shape, dtype)


PinnedBufferPool$get()

Usage
PinnedBufferPool$get(shape, dtype)
Arguments
shape

Integer vector. Shape of the tensor.

dtype

torch.dtype. Data type of the tensor.

Returns

A pinned CPU tensor.


PinnedBufferPool$put()

Usage
PinnedBufferPool$put(buf)
Arguments
buf

Tensor. Buffer to return.


PinnedBufferPool$clear()

Usage
PinnedBufferPool$clear()
Returns

A cleared private pool


PinnedBufferPool$clone()

The objects of this class are cloneable with this method.

Usage
PinnedBufferPool$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

## Not run: 
pool <- pinned_buffer_pool$new(max_buffers_per_shape = 8L)
buf <- pool$get(c(100L, 128L), torch_float())
# ... use buffer ...
pool$put(buf)  # Return to pool for reuse

## End(Not run)

Predict using TabICL2

Description

Predict using TabICL2

Usage

## S3 method for class 'tab_icl_v2'
predict(object, new_data, ...)

## S3 method for class 'tab_icl_v2.regressor'
predict(object, new_data, levels, train_dim, ...)

## S3 method for class 'tab_icl_v2.classifier'
predict(object, new_data, levels, train_dim, ...)

## S3 method for class 'tab_icl_v2'
augment(x, new_data, ...)

Arguments

object

A tab_icl_v2 object.

new_data

A data frame or matrix of new predictors.

...

Not used, but required for extensibility.

levels

for regressor, the number of quantiles. For classifier, the number of levels in the outcome.

train_dim

the number of rows of the training part within new_data.

x

A tab_icl_v2 object.

Value

predict() returns a tibble of predictions and augment() appends the columns in new_data. In either case, the number of rows in the tibble is guaranteed to be the same as the number of rows in new_data.

For regression data, the prediction is in the column .pred. For classification, the class predictions are in .pred_class and the probability estimates are in columns with the pattern ⁠.pred_{level}⁠ where level is the levels of the outcome factor vector.

Examples

car_split <- rsample::initial_split(mtcars)

## Not run: 
# Fit
if (torch_is_installed() & interactive()) {
 mod <- tab_icl2(mpg ~ cyl + log(drat), car_split)

 # Predict
 predict(mod, testing(car_split))

 # Augment
 augment(mod, testing(car_split))
}

## End(Not run)

QASSMaxMLP – Query-Aware Scalable Softmax with MLPs

Description

Applies scaling to queries using two MLPs:

qscaled=q⋅base_mlp(log⁡n)⋅(1+tanh⁡(query_mlp(q)))q_{\text{scaled}} = q \cdot \text{base\_mlp}(\log n) \cdot (1 + \tanh(\text{query\_mlp}(q)))

The base MLP learns length-dependent scaling while the query MLP learns query-dependent modulation. The query MLP is zero-initialised so that the initial modulation is the identity (1+0=11 + 0 = 1).

Usage

QASSMaxMLP(num_heads, head_dim, n_hidden = 64L, elementwise = FALSE)

Arguments

num_heads

integer(1) Number of attention heads.

head_dim

integer(1) Dimension of each attention head.

n_hidden

integer(1) Number of hidden units in each MLP. Default: 64L.

elementwise

logical(1) If TRUE, apply elementwise scaling per head dimension. Default: FALSE.

Value

An nn_module object (class generator).

See Also

create_ssmax_layer


Module wrapper for QuantileDistribution

Description

Converts predicted quantiles to QuantileDistribution with analytical statistics.

Usage

quantile_to_distribution(
  alpha_levels = NULL,
  num_quantiles = 999L,
  tail_type = "exp",
  fix_crossing = TRUE,
  crossing_method = "sort"
)

Arguments

alpha_levels

Numeric vector or NULL. Quantile levels.

num_quantiles

Integer. Number of quantile levels (if alpha_levels not provided).

tail_type

Character. "exp" or "gpd".

fix_crossing

Logical. Enforce monotonicity?

crossing_method

Character. Method for fixing crossing.


Probability distribution constructed from predicted quantiles

Description

Wraps a set of predicted quantiles into a proper distribution with:

  • Monotonicity enforcement (fixes quantile crossing)

  • Tail extrapolation (exponential or GPD) with data-inferred parameters

  • Analytical statistics (CDF, PDF, CRPS, mean, variance)

Usage

QuantileDistribution(
  quantiles,
  alpha_levels = NULL,
  tail_type = "exp",
  fix_crossing = TRUE,
  crossing_method = "sort"
)

Arguments

quantiles

Tensor. Quantile values after monotonicity correction. Shape: ⁠(*batch_shape, num_quantiles)⁠.

alpha_levels

Numeric vector or NULL. Quantile levels.

tail_type

Character. "exp" or "gpd".

fix_crossing

Logical. Enforce monotonicity?

crossing_method

Character. Method for fixing crossing.


Configuration constants for Quantile Distribution

Description

Numerical stability parameters, tail parameters, computational limits, and tail inference parameters for quantile distribution estimation.

Usage

QuantileDistributionConfig

Numerical Stability Parameters

  • TOL: General numerical tolerance (default: 1e-6)

  • MIN_SLOPE: Minimum allowed slope dQ/dα (default: 1e-6)

  • MAX_SLOPE: Maximum allowed slope dQ/dα (default: 1e6)

Tail Parameters

  • MIN_BETA: Minimum tail scale parameter β (default: 0.01)

  • MAX_BETA: Maximum tail scale parameter β (default: 100.0)

  • MIN_ETA: Minimum GPD shape parameter η (default: -0.49)

  • MAX_ETA: Maximum GPD shape parameter η (default: 0.49)

  • ETA_TOLERANCE: Threshold for treating η ≈ 0 (default: 0.01)

Computational Limits

  • MAX_LOG_RATIO: Maximum log(ratio) (default: 15.0)

  • MAX_EXPONENT: Maximum exponent before exp() (default: 15.0)

  • MAX_CRPS: Maximum CRPS value (default: 1e4)

Tail Inference Parameters

  • TAIL_QUANTILES_FOR_ESTIMATION: Number of tail quantiles (default: 20)


Rotary Positional Embeddings Module

Description

Rotary embeddings encode positional information in a way that allows continuous rotation of embeddings, enhancing the model's ability to capture long-range dependencies and positional relations.

Usage

RotaryEmbedding(
  dim,
  interleaved = TRUE,
  custom_freqs = NULL,
  freqs_for = "lang",
  theta = 10000,
  max_freq = 10,
  num_freqs = 1L,
  learned_freq = FALSE,
  use_xpos = FALSE,
  xpos_scale_base = 512,
  interpolate_factor = 1,
  theta_rescale_factor = 1,
  seq_before_head_dim = FALSE,
  cache_if_possible = TRUE
)

Arguments

dim

Integer. The dimension of the embeddings.

interleaved

Logical. If TRUE, uses interleaved rotation (default: TRUE).

custom_freqs

Tensor or NULL. Custom frequency tensor (default: NULL).

freqs_for

Character. One of "lang", "pixel", or "constant" (default: "lang").

theta

Numeric. Base scaling factor (default: 10000).

max_freq

Numeric. Maximum frequency for pixel-based embeddings (default: 10).

num_freqs

Integer. Number of frequencies for "constant" mode (default: 1L).

learned_freq

Logical. If TRUE, frequencies are learnable parameters (default: FALSE).

use_xpos

Logical. If TRUE, uses extrapolatable rotary embeddings (XPOS) (default: FALSE).

xpos_scale_base

Numeric. Base scaling factor used for XPOS (default: 512).

interpolate_factor

Numeric. Factor by which sequence length is interpolated (default: 1.0).

theta_rescale_factor

Numeric. Rescaling factor applied to theta (default: 1.0).

seq_before_head_dim

Logical. If TRUE, sequences are handled before head dim (default: FALSE).

cache_if_possible

Logical. If TRUE, caches computed frequencies (default: TRUE).

Value

An nn_module object.


Row-Wise Feature Interaction Module

Description

Captures interactions between features within each row using a transformer encoder with rotary positional encoding (RoPE). Prepends learnable CLS tokens to feature embeddings and uses only those tokens to aggregate per-row representations.

Usage

RowInteraction(
  embed_dim,
  num_blocks,
  nhead,
  dim_feedforward,
  num_cls = 4L,
  rope_base = 1e+05,
  rope_interleaved = TRUE,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  recompute = FALSE
)

Arguments

embed_dim

Integer. Embedding dimension.

num_blocks

Integer. Number of transformer blocks in the encoder.

nhead

Integer. Number of attention heads.

dim_feedforward

Integer. Dimension of the feedforward network.

num_cls

Integer. Number of learnable CLS tokens prepended to feature embeddings. Their outputs are concatenated to form the row representation (default: 4L).

rope_base

Numeric. Base scaling factor for rotary position encoding (default: 100000).

rope_interleaved

Logical. If TRUE, uses interleaved rotation where dimension pairs are (0,1), (2,3), etc. If FALSE, splits the embedding into first and second halves (default: TRUE).

dropout

Numeric. Dropout probability in the encoder (default: 0.0).

activation

Character or function. Activation for the feedforward network: "relu", "gelu", or a unary callable (default: "gelu").

norm_first

Logical. If TRUE, uses pre-norm architecture (LayerNorm before attention and feedforward) (default: TRUE).

bias_free_ln

Logical. If TRUE, removes bias from all LayerNorm layers (default: FALSE).

recompute

Logical. If TRUE, uses gradient checkpointing to save memory at the cost of extra computation (default: FALSE).

Value

An nn_module instance of class RowInteraction.

Forward signature

row_int <- RowInteraction(embed_dim = 128L, num_blocks = 3L,
                          nhead = 8L, dim_feedforward = 256L)
# Training
repr <- row_int(embeddings, d = d)
# Inference
repr <- row_int(embeddings)

See Also

Encoder, RotaryEmbedding


Stack of induced self-attention blocks.

Description

A set transformer uses induced self-attention mechanism to efficiently process variable-sized sets while maintaining permutation invariance.

Usage

set_transformer(
  num_blocks,
  d_model,
  nhead,
  dim_feedforward,
  num_inds = 16L,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  ssmax = FALSE,
  recompute = FALSE
)

Arguments

num_blocks

Integer. Number of induced self-attention blocks in the stack.

d_model

Integer. Model dimension.

nhead

Integer. Number of attention heads and should be a divisor of d_model.

dim_feedforward

Integer. Dimension of the feedforward network in each block.

num_inds

Integer, default 16L. Number of inducing points used in self-attention blocks.

dropout

Float, default 0. Dropout probability.

activation

Character string or unary function, default "gelu". The activation function used in the feedforward network.

norm_first

Logical, default TRUE. If TRUE, uses pre-norm architecture (LayerNorm before attention and feedforward).

bias_free_ln

Logical, default FALSE. If TRUE, removes bias from all LayerNorm layers.

ssmax

Logical or character string, default FALSE. Type of scalable softmax to use in attention. Note that only the first attention layer of the induced self-attention blocks uses SSMax. If TRUE, equivalent to "qassmax-mlp-elementwise". If FALSE, equivalent to "none". If a string, uses the specified scalable softmax type. Options include: "none", "ssmax", "ssmax-mlp", "ssmax-mlp-elementwise", "qassmax-mlp", "qassmax-mlp-elementwise".

recompute

Logical, default FALSE. If TRUE, uses gradient checkpointing to save memory at the cost of additional computation.

Value

An nn_module instance of class SetTransformer.

Methods

Usage

st <- SetTransformer(num_blocks = 3L, d_model = 128L, nhead = 8L,
                     dim_feedforward = 256L, num_inds = 128L)
st$forward(src, train_size = NULL)
st$forward_with_cache(src, col_cache, train_size, use_cache, store_cache)

References

Lee et al. "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks", ICML 2019.

See Also

induced_self_attention_block, KVCache, KVCacheEntry


Linear layer that handles inputs flagged with a skip value

Description

First applies the linear transformation to all inputs, then replaces outputs for inputs where all values equal skip_value with the skip_value.

Usage

skippable_linear(in_features, out_features, bias = TRUE, skip_value = -100)

Arguments

in_features

Integer. Size of each input sample.

out_features

Integer. Size of each output sample.

bias

Logical. If FALSE, the layer will not learn an additive bias (default: TRUE).

skip_value

Numeric. Value used to mark inputs that should be skipped (default: -100.0).

Value

A nn_module that applies linear transformation with skip handling.

Examples

## Not run: 
layer <- skippable_linear(in_features = 10L, out_features = 20L)
x <- torch_randn(32L, 10L)
x[1:5, ] <- -100.0  # Mark rows to skip
out <- layer(x)  # Skipped rows remain -100.0 in output

## End(Not run)

SSMax – Scalable Softmax with Learnable Per-Head Scaling

Description

Applies scaling to queries: qscaled=q⋅(s⋅log⁡n)q_{\text{scaled}} = q \cdot (s \cdot \log n), where ss is a learnable per-head parameter.

Usage

SSMax(num_heads)

Arguments

num_heads

integer(1) Number of attention heads.

Value

An nn_module object (class generator).

See Also

create_ssmax_layer


SSMaxMLP – Scalable Softmax with MLP-Computed Scaling

Description

Applies scaling to queries: qscaled=q⋅mlp(log⁡n)q_{\text{scaled}} = q \cdot \text{mlp}(\log n), where a small MLP learns to map sequence length to scaling factors.

Usage

SSMaxMLP(num_heads, n_hidden = 64L, elementwise = FALSE, head_dim = NULL)

Arguments

num_heads

integer(1) Number of attention heads.

n_hidden

integer(1) Number of hidden units in the MLP. Default: 64L.

elementwise

logical(1) If TRUE, apply elementwise scaling per head dimension so that each element in the head dimension gets its own scaling factor. Default: FALSE.

head_dim

integer(1) or NULL. Dimension of each attention head. Required when elementwise = TRUE.

Value

An nn_module object (class generator).

See Also

create_ssmax_layer


Fit a TabICL2 model.

Description

tab_icl2() applies data to a pre-estimated deep learning model defined by Qu et al (2026). This model emulates Bayesian inference for regression and classification models.

Usage

tab_icl2(x, ...)

## Default S3 method:
tab_icl2(x, ...)

## S3 method for class 'data.frame'
tab_icl2(
  x,
  y,
  config = tab_icl2_config(),
  control = tab_icl2_control(),
  model_version = NULL,
  ...
)

## S3 method for class 'matrix'
tab_icl2(
  x,
  y,
  config = tab_icl2_config(),
  control = tab_icl2_control(),
  model_version = NULL,
  ...
)

## S3 method for class 'formula'
tab_icl2(
  formula,
  data,
  config = tab_icl2_config(),
  control = tab_icl2_control(),
  model_version = NULL,
  ...
)

## S3 method for class 'recipe'
tab_icl2(
  x,
  data,
  config = tab_icl2_config(),
  control = tab_icl2_control(),
  model_version = NULL,
  ...
)

Arguments

x

Depending on the context:

  • A data frame of predictors.

  • A matrix of predictors.

  • A recipe specifying a set of preprocessing steps created from recipes::recipe().

...

Not currently used, but required for extensibility.

y

When x is a data frame or matrix, y is the outcome specified as:

  • A data frame with 1 numeric column.

  • A matrix with 1 numeric column.

  • A numeric vector for regression or a factor for classification.

config

A list of model architecture options produced by tab_icl2_config(). Ignored when a pretrained checkpoint is loaded via model_version.

control

A list of inference execution options produced by tab_icl2_control().

model_version

A character string identifying the checkpoint to load. Three forms are accepted:

Registry key

A name from the built-in registry (e.g. "tabicl_classifier_v2"). The file is downloaded once and cached.

HTTPS URL

Any ⁠https://⁠ or ⁠http://⁠ address pointing to a checkpoint file. The file is downloaded once and cached.

Local file URI

A ⁠file:///path/to/model.pt⁠ URI. The file must already exist on disk.

When NULL (the default) a randomly initialised model is built from config.

formula

A formula specifying the outcome terms on the left-hand side, and the predictor terms on the right-hand side.

data

When a recipe or formula is used, data is specified as:

  • A rsplit object from rsample package containing both the predictors and the outcome.

Details

Computing Requirements

This model can be used with or without a graphics processing unit (GPU). However, it is fairly limited when used with a CPU (and no GPU). There might be additional data size limitation warnings with CPU computations, and, understandably, the execution time is much longer. CPU computations can also consume a significant amount of system memory, depending on the size of your data.

GPUs using CUDA (Compute Unified Device Architecture) are most effective. Limited testing with others has shown that GPUs with Metal Performance Shaders (MPS) instructions (e.g., Apple GPUs) have limited utility for these specific computations and might be slower than the CPU for some data sets.

Data

Predictors do not require preprocessing; missing values and factor vectors are allowed.

Model Selection

Selecting a model version

Use the model_version argument to load a specific pretrained checkpoint. Three forms are accepted:

  # Built-in registry key (downloaded and cached automatically)
  mod <- tab_icl2(predictors, outcome,
                  model_version = "tabicl_classifier_v2")

  # Any HTTPS URL (downloaded and cached automatically)
  mod <- tab_icl2(predictors, outcome,
                  model_version = "https://example.com/my_model.pt")

  # Local file via file:// URI
  mod <- tab_icl2(predictors, outcome,
                  model_version = "file:///path/to/model.pt")

Calculations

For the softmax_temperature value, the softmax terms are:

exp(value / softmax_temperature)

A value of softmax_temperature = 1 results in a plain softmax value.

Value

A tab_icl2 object with elements:

  • fit: the object containing the model.

  • levels: a character string of class levels (or NULL for regression)

  • t_dim : the dimension of the training set inside the T-shape XY dataset

  • t_predictors : a tibble of training and validation set predictors

  • t_outcome : a tibble of validation set outcome

  • logging : unused

References

Jingang Qu, David Holzmüller, Gaël Varoquaux, Marine Le Morvan. "TabICLv2: A better, faster, scalable, and open tabular foundation model." arXiv preprint arXiv:2602.11139 (2026).

Jingang Qu, David Holzmüller, Gaël Varoquaux, Marine Le Morvan. "TabICL: A Tabular Foundation Model for In-Context Learning on Large Data." arXiv preprint arXiv:2502.05564 (2025).

See Also

tab_icl2_config(), tab_icl2_control(), predict.tab_icl_v2()

Examples

predictors <- mtcars[, -1]
outcome <- mtcars[, 1]
mtcars_split <- rsample::initial_split(mtcars)

## Not run: 
if (torch_is_installed() && interactive()) {
 # XY interface
 mod <- tab_icl2(predictors, outcome)
 mod

 # Formula interface
 mod2 <- tab_icl2(mpg ~ ., mtcars_split)
 mod2

 # Recipes interface
 if (rlang::is_installed("recipes")) {
  rec <-
   recipes::recipe(mpg ~ ., mtcars) %>%
   recipes::step_log(disp)

  mod3 <- tab_icl2(rec, mtcars_split)
  mod3
 }
}

## End(Not run)

Configure TabICL2 model architecture

Description

Configure TabICL2 model architecture

Usage

tab_icl2_config(
  embed_dim = 128L,
  col_n_block = 3L,
  row_n_block = 3L,
  icl_n_block = 12L,
  col_n_head = 8L,
  row_n_head = 8L,
  icl_n_head = 8L,
  feature_group_size = 3L,
  col_n_cls = 128L,
  row_n_cls = 4L,
  num_quantiles = 999L,
  ...
)

Arguments

embed_dim

A positive integer. Embedding dimension shared across all transformer stages.

col_n_block

A positive integer. Number of column-wise transformer blocks.

row_n_block

A positive integer. Number of row-wise transformer blocks.

icl_n_block

A positive integer. Number of in-context-learning transformer blocks.

col_n_head

A positive integer. Number of attention heads for column blocks.

row_n_head

A positive integer. Number of attention heads for row blocks.

icl_n_head

A positive integer. Number of attention heads for ICL blocks.

feature_group_size

A positive integer. Size of feature groups for cyclic repeated grouping.

col_n_cls

A positive integer. Number of CLS tokens per column, concatenated to produce the row representation fed into the ICL stage.

row_n_cls

A positive integer. Number of inducing vectors used in the induced self-attention column blocks.

num_quantiles

A positive integer (>= 5). Number of quantiles predicted by the regression head.

...

Additional named arguments stored in the returned config object. Use this for architecture settings not covered by the named parameters above (e.g., arguments added in newer versions of the model).

Value

A list with class "tab_icl2_config" containing one element per architecture parameter, all coerced to integer.

Examples

tab_icl2_config()
tab_icl2_config(embed_dim = 256L, icl_n_block = 8L)

Control TabICL2 inference execution

Description

Control TabICL2 inference execution

Usage

tab_icl2_control(
  device = NULL,
  use_amp = TRUE,
  use_fa3 = TRUE,
  verbose = FALSE,
  min_batch_size = 1L,
  safety_factor = 0.8,
  offload = "auto",
  ignore_pretraining_limits = FALSE,
  col_config = list(),
  row_config = list(),
  icl_config = list(),
  ...
)

inference_config(
  device = NULL,
  use_amp = TRUE,
  use_fa3 = TRUE,
  verbose = FALSE,
  min_batch_size = 1L,
  safety_factor = 0.8,
  offload = "auto",
  ignore_pretraining_limits = FALSE,
  col_config = list(),
  row_config = list(),
  icl_config = list(),
  ...
)

Arguments

device

A character string or NULL for the torch device (e.g., "cpu", "cuda", "mps"). Applied to all three transformer stages.

use_amp

A logical. Enable automatic mixed precision. Applied to all stages.

use_fa3

A logical. Enable Flash Attention 3 kernels. Applied to all stages.

verbose

A logical. Enable verbose logging. Applied to all stages.

min_batch_size

A positive integer. Minimum batch size passed to the memory manager. Applied to all stages.

safety_factor

A number in [0, 1]. Memory safety margin for batch size estimation. Applied to all stages.

offload

A logical or one of "auto", "gpu", "cpu", "disk". Offload strategy for the column-embedding (COL) stage. Row-interaction (ROW) and in-context-learning (ICL) stages default to FALSE unless overridden via row_config/icl_config.

ignore_pretraining_limits

A logical. Bypass the default data size limits on training set rows (50,000) and predictors (2,000).

col_config

A named list of additional settings for the COL stage, overriding any of the defaults or parameters above.

row_config

A named list of additional settings for the ROW stage.

icl_config

A named list of additional settings for the ICL stage.

...

Additional named arguments stored in the returned control object. Use this for settings not covered above (e.g. auto_offload_threshold, disk_offload_dir, use_async, etc.) that apply uniformly. Per-stage values must go in col_config, row_config, or icl_config.

Value

A list with class "tab_icl2_control" containing resolved per-stage settings in ⁠$col⁠, ⁠$row⁠, and ⁠$icl⁠, plus ⁠$ignore_pretraining_limits⁠.

Examples

tab_icl2_control()
tab_icl2_control(use_amp = FALSE, offload = "cpu")
tab_icl2_control(col_config = list(disk_offload_dir = tempdir()))
tab_icl2_control(ignore_pretraining_limits = TRUE)

Concatenate Multiple TabICLCache Objects

Description

Concatenate multiple TabICLCache objects along the batch dimension.

Usage

tabicl_cache_concat(caches, dim = 1)

Arguments

caches

List of TabICLCache instances.

dim

Integer. Dimension to concatenate along (batch dimension). Default is 1 (R 1-based; corresponds to Python dim 0).

Value

A new TabICLCache with concatenated caches.


Top-Level Cache Container for the Entire TabICL Model

Description

Aggregates caches for different components of TabICL:

  • ColEmbedding cache (for ISAB blocks in column embedding)

  • ICLearning cache (for Encoder layers in the ICL transformer)

Format

An R6::R6Class object.

Details

The train_shape field stores (batch_size, train_size, num_features) as a 3-element integer vector.

Public fields

col_cache

Optional KVCache for ColEmbedding ISAB blocks.

row_repr

Optional torch_tensor. Cached row representations.

icl_cache

Optional KVCache for ICLearning Encoder layers.

train_shape

Integer vector of length 3: (batch_size, train_size, num_features).

num_classes

Optional integer. Number of classes in classification tasks (0 for regression). Stored when caching to ensure consistent output shape during cache use.

Methods

Public methods


TabICLCache$new()

Create a new TabICLCache.

Initializes sub-caches automatically if not provided.

Usage
TabICLCache$new(
  col_cache = NULL,
  row_repr = NULL,
  icl_cache = NULL,
  train_shape = c(0, 0, 0),
  num_classes = NULL
)
Arguments
col_cache

Optional KVCache.

row_repr

Optional torch_tensor.

icl_cache

Optional KVCache.

train_shape

Integer vector of length 3. Default c(0, 0, 0).

num_classes

Optional integer.


TabICLCache$cache_type()

Return the cache type.

Usage
TabICLCache$cache_type()
Returns

Character string: "kv", "repr", or "empty".


TabICLCache$cache_size_mb()

Return the memory occupied by cached tensors in MB.

Usage
TabICLCache$cache_size_mb()
Returns

Integer.


TabICLCache$is_empty()

Check if the cache is empty.

Usage
TabICLCache$is_empty()
Returns

Logical scalar.


TabICLCache$slice_batch()

Slice this cache along the batch dimension (dim 1 in R).

Usage
TabICLCache$slice_batch(start, end)
Arguments
start

Integer. Start index of the batch slice (1-based, inclusive).

end

Integer. End index of the batch slice (1-based, exclusive).

Returns

A new TabICLCache with sliced tensors (views of original).


TabICLCache$to()

Move all cached tensors to the given device and optionally cast dtype.

Usage
TabICLCache$to(device, dtype = NULL)
Arguments
device

Device string, e.g. "cpu" or "cuda:0".

dtype

Optional torch_dtype. If NULL, preserves existing dtype.

Returns

A new TabICLCache with all tensors on the target device.


TabICLCache$clone()

The objects of this class are cloneable with this method.

Usage
TabICLCache$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

## Not run: 
  cache <- TabICLCache$new(
    train_shape = c(4, 100, 20),
    num_classes = 10
  )
  cache$cache_type()

## End(Not run)

TabICL: A Tabular In-Context Learning Foundation Model

Description

TabICL is a transformer-based architecture for in-context learning on tabular data. This class is the underlying raw torch module.

Usage

TabICLv2(
  config,
  max_classes = 10L,
  col_affine = FALSE,
  col_feature_group = "same",
  col_target_aware = TRUE,
  col_ssmax = "qassmax-mlp-elementwise",
  row_rope_base = 1e+05,
  row_rope_interleaved = FALSE,
  icl_ssmax = "qassmax-mlp-elementwise",
  ff_factor = 2L,
  dropout = 0,
  activation = "gelu",
  norm_first = TRUE,
  bias_free_ln = FALSE,
  recompute = FALSE
)

Arguments

config

A tab_icl2_config object providing

  • embed_dim Integer, default 128L. Model dimension.

  • num_quantiles Integer, default 999L. Number of quantiles for regression.

  • col_n_block Integer, default 3L.

  • col_n_head Integer, default 8L.

  • col_n_cls Integer, default 128L.

  • col_feature_group_size Integer, default 3L.

  • row_n_block Integer, default 3L.

  • row_n_head Integer, default 8L.

  • row_n_cls Integer, default 4L.

  • icl_n_block Integer, default 12L.

  • icl_n_head Integer, default 8L.

max_classes

Integer, default 10L. 0 for regression.

col_affine

Logical, default FALSE.

col_feature_group

Character, default "same".

col_target_aware

Logical, default TRUE.

col_ssmax

Character, default "qassmax-mlp-elementwise".

row_rope_base

Float, default 100000.

row_rope_interleaved

Logical, default FALSE.

icl_ssmax

Character, default "qassmax-mlp-elementwise".

ff_factor

Integer, default 2L.

dropout

Float, default 0.

activation

Character, default "gelu".

norm_first

Logical, default TRUE.

bias_free_ln

Logical, default FALSE.

recompute

Logical, default FALSE.

Details

TabICL: A Tabular In-Context Learning Foundation Model

TabICL is a transformer-based architecture for in-context learning on tabular data to make predictions without fine-tuning. It processes tabular data through three sequential stages:

  1. Column-wise embedding creates distribution-aware embeddings.

  2. Row-wise interaction captures interactions between features within each row.

  3. Dataset-wise in-context learning to learn patterns from labeled examples and make predictions.

This class is the underlying raw torch module for TabICL. It is not intended to be used directly. Instead, use the classes from the top-level tabicl package such as TabICLClassifier or TabICLRegressor that wrap this class to include the necessary preprocessing of input features and postprocessing of predictions.

Value

An nn_module instance of class TabICL.

Methods

Usage

model <- TabICL$new(max_classes = 10L)
model$forward(X, y_train)
model$predict_stats(X, y_train, output_type = "mean")
model$forward_with_cache(X_train, y_train, store_cache = TRUE)
model$predict_stats_with_cache(X_test = X_test, use_cache = TRUE)
model$has_cache()
model$clear_cache()

forward(X, y_train, d, embed_with_test, feature_shuffles, return_logits, softmax_temperature, inference_config)

Column-wise embedding -> row-wise interaction -> dataset-wise in-context learning. Dispatches to train_forward() in training mode and inference_forward() in evaluation mode.

  • X: Input tensor of shape (B, TT, H) where B is the number of tables, TT is the number of samples (rows), and H is the number of features (columns). The first train_size positions contain training samples, and the remaining positions contain test samples.

  • y_train: Training labels of shape (B, train_size).

  • d: Optional tensor. The number of features per dataset. Used only in training mode.

  • embed_with_test: Logical, default FALSE. If TRUE, allow training samples to attend to test samples during embedding.

  • feature_shuffles: Optional list of integer vectors. Feature shuffle patterns for each table in the batch. Used only in inference mode.

  • return_logits: Logical, default TRUE. If TRUE, return raw logits instead of probabilities. Used only in inference mode.

  • softmax_temperature: Float, default 0.9. Temperature for the softmax function. Used only in inference mode.

  • inference_config: An inference_config object. Used only in inference mode.

Returns a tensor. For training mode: predictions of shape (B, test_size, out_dim). For inference mode: logits or probabilities of shape (B, test_size, num_classes) for classification, or predictions of shape (B, test_size, num_quantiles) for regression.

predict_stats(X, y_train, output_type, alphas, embed_with_test, inference_config)

Compute summary statistics from predicted quantiles. Only applicable for regression tasks (max_classes = 0).

  • output_type: Character string or character vector. Supported values: "mean", "variance", "median", "quantiles", "raw_quantiles". If a vector, returns a named list.

  • alphas: Optional numeric vector. Probability levels for quantile output. Default: c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9).

Returns a tensor (single output type) or a named list of tensors (multiple output types). Output shapes: "mean", "variance", "median" return (B, test_size); "quantiles" returns (B, test_size, len(alphas)); "raw_quantiles" returns (B, test_size, num_quantiles).

forward_with_cache(X_train, y_train, X_test, return_logits, softmax_temperature, use_cache, store_cache, cache, cache_mode, inference_config)

Forward pass with caching support for efficient inference. Two caching modes are supported:

  • "kv": Cache KV projections from both column embedding and ICL transformer layers. Fastest inference but uses more memory.

  • "repr": Cache column embedding KV projections and row interaction outputs. Uses approximately 24x less memory for the ICL part, at the cost of re-running the ICL transformer.

Exactly one of use_cache or store_cache must be TRUE. When store_cache = TRUE, requires X_train and y_train. When use_cache = TRUE, requires X_test and a populated cache.

  • X_train: Optional tensor of shape (B, train_size, H). Required when store_cache = TRUE.

  • y_train: Optional tensor of shape (B, train_size). Required when store_cache = TRUE.

  • X_test: Optional tensor of shape (B, test_size, H). Required when use_cache = TRUE.

  • return_logits: Logical, default TRUE.

  • softmax_temperature: Float, default 0.9.

  • use_cache: Logical, default FALSE.

  • store_cache: Logical, default TRUE.

  • cache: Optional TabICLCache. If provided, equivalent to setting use_cache = TRUE and store_cache = FALSE.

  • cache_mode: Character string, default "kv". Caching strategy.

  • inference_config: Optional inference_config.

Returns predictions of shape (B, test_size, out_dim), or NULL if store_cache = TRUE and X_test is not provided.

predict_stats_with_cache(X_train, y_train, X_test, output_type, alphas, use_cache, store_cache, cache, cache_mode, inference_config)

Compute summary statistics from predicted quantiles with KV caching. Only applicable for regression tasks (max_classes = 0). Parameters and return value are the same as predict_stats(), with additional caching parameters matching forward_with_cache(). Returns NULL if store_cache = TRUE and X_test is not provided.

has_cache()

Check if a valid cache is stored. Returns a logical value.

clear_cache()

Clear the stored cache. Called for its side effect; returns NULL invisibly.

See Also

ColEmbedding, RowInteraction, ICLearning, quantile_to_distribution, TabICLCache, inference_config