| 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 |
Uses a dedicated CUDA stream for device-to-host (D2H) transfers, allowing GPU computation to overlap with data movement.
An AsyncCopyManager object.
reset_bytes_counter()Reset the bytes written counter
clear()Clear pending copies without completing them
AsyncCopyManager$new()AsyncCopyManager$new(device, max_pending = 4L, buffer_pool = NULL)
devicetorch.device. CUDA device.
max_pendingInteger. Max pending copies.
buffer_poolPinnedBufferPool or NULL.
AsyncCopyManager$submit_copy()AsyncCopyManager$submit_copy(gpu_tensor, target, indices)
gpu_tensorTensor. Source tensor on GPU.
targetTensor or DiskTensor. Target storage.
indicesList. Indices where to write in target.
AsyncCopyManager$drain_all()AsyncCopyManager$drain_all()
Numeric. Total bytes written in MB.
AsyncCopyManager$get_bytes_written()AsyncCopyManager$get_bytes_written()
Numeric.
AsyncCopyManager$reset_bytes_counter()AsyncCopyManager$reset_bytes_counter()
NULL
AsyncCopyManager$clear()AsyncCopyManager$clear()
NULL
AsyncCopyManager$clone()The objects of this class are cloneable with this method.
AsyncCopyManager$clone(deep = FALSE)
deepWhether to make a deep clone.
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.
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 )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 )
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: |
activation |
Character. Activation function (default: |
norm_first |
Logical. Pre-norm architecture (default: |
bias_free_ln |
Logical. Remove LayerNorm bias (default: |
affine |
Logical. Compute |
feature_group |
Logical or Character. Grouping mode:
|
feature_group_size |
Integer. Size of feature groups (default: |
target_aware |
Logical. Use target info (default: |
max_classes |
Integer. Number of classes (default: |
reserve_cls_tokens |
Integer. CLS token slots (default: |
ssmax |
Logical or Character. Scalable softmax type. |
mixed_radix_ensemble |
Logical. Mixed-radix ensembling (default: |
recompute |
Logical. Gradient checkpointing (default: |
An nn_module object.
Factory function that instantiates the appropriate
SSMax* module (or NULL) from a string identifier.
create_ssmax_layer(ssmax_type, num_heads, embed_dim)create_ssmax_layer(ssmax_type, num_heads, embed_dim)
ssmax_type |
|
num_heads |
|
embed_dim |
|
An nn_module instance, or NULL when
ssmax_type = "none".
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.
A DiskTensor object.
flush()Flush changes to disk
DiskTensor$new()DiskTensor$new(shape, dtype, path, cleanup = TRUE)
shapeInteger vector. Shape of the tensor.
dtypetorch.dtype. Data type.
pathCharacter. File path.
cleanupLogical. Auto-cleanup on GC.
DiskTensor$tensor()DiskTensor$tensor()
A torch tensor.
DiskTensor$get()DiskTensor$get(indices)
indicesList of indices or slices.
A torch tensor.
DiskTensor$set()DiskTensor$set(indices, value)
indicesList of indices.
valueTensor. Value to write.
DiskTensor$flush()DiskTensor$flush()
Invisible flush to disk
DiskTensor$nbytes()DiskTensor$nbytes()
Integer. Size in bytes.
DiskTensor$clone()The objects of this class are cloneable with this method.
DiskTensor$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 doesn't support [ overloading directly; use $get() instead.
## 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)## 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)
Stack of multihead attention blocks.
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 )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 )
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
|
dim_feedforward |
Integer. Dimension of the feedforward network in each block. |
dropout |
Float, default |
activation |
Character string or unary function, default |
norm_first |
Logical, default |
bias_free_ln |
Logical, default |
use_rope |
Logical, default |
rope_base |
Integer, default |
rope_interleaved |
Logical, default |
ssmax |
Logical or character string, default |
recompute |
Logical, default |
An nn_module instance of class Encoder.
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)
multihead_attention_block, RotaryEmbedding,
KVCache, KVCacheEntry
Enforce monotonicity of quantiles to fix crossing
enforce_monotonicity(quantiles, method = "sort", weights = NULL)enforce_monotonicity(quantiles, method = "sort", weights = NULL)
quantiles |
Tensor. Predicted quantiles that may have crossing violations.
Shape: |
method |
Character. Method for fixing crossing:
|
weights |
Tensor or NULL. Case weights for PAVA method.
Shape: |
Tensor. Monotonically non-decreasing quantiles.
Shape: (*batch_shape, num_quantiles).
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.
flash_attn3_toggle(enabled) flash_attn3_toggle(enabled)flash_attn3_toggle(enabled) flash_attn3_toggle(enabled)
enabled |
Logical. Whether to enable FA3. |
A function that, when called, restores the previous setting.
Function. Restoration function to call when done.
## 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)## 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)
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.
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 )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 )
max_classes |
Integer. Determines task type and output behavior:
|
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). |
An nn_module object.
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
## Not run: icl <- ICLearning( max_classes = 10L, out_dim = 10L, d_model = 128L, num_blocks = 6L, nhead = 8L, dim_feedforward = 512L ) ## End(Not run)## Not run: icl <- ICLearning( max_classes = 10L, out_dim = 10L, d_model = 128L, num_blocks = 6L, nhead = 8L, dim_feedforward = 512L ) ## End(Not run)
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:
Projecting inputs onto inducing points (size m << n)
Propagating information through these inducing points
Projecting back to the original sequence
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 )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 )
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: |
activation |
Character or function. Activation function for feedforward
(default: |
norm_first |
Logical. If |
bias_free_ln |
Logical. If |
ssmax |
Logical or character. Type of scalable softmax to use in attention.
Note that only the first attention layer uses SSMax (default: |
skip_value |
Numeric. Value used to mark inputs that should be skipped
(default: |
A nn_module for induced self-attention.
Lee et al. "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks", ICML 2019
Service class that orchestrates memory-efficient inference through automatic batching, flexible offloading (GPU/CPU/disk), and OOM recovery.
An R6Class generator object.
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
## Not run: mgr <- inference_manager$new(enc_name = "tf_col", out_dim = 128L) mgr$configure(offload = "auto", verbose = TRUE) ## End(Not run)## 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 along a dimension.
kv_cache_concat(caches, dim = 1)kv_cache_concat(caches, dim = 1)
caches |
List of |
dim |
Integer. Dimension to concatenate along (batch dimension).
Default is |
A new KVCache with concatenated entries at each layer index.
Concatenate multiple KVCacheEntry objects along a dimension.
kv_cache_entry_concat(entries, dim = 1)kv_cache_entry_concat(entries, dim = 1)
entries |
List of |
dim |
Integer. Dimension to concatenate along. Default is |
A new KVCacheEntry with concatenated key and value tensors.
Returns an empty entry if no valid entries are found.
## 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)## 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)
Provides common structure and operations for caches that store mappings from layer/block index to cached key-value projections.
An R6::R6Class object.
Layer indices are stored as character strings in the named list kv,
since R lists cannot have integer names that start from 0.
kvNamed list mapping layer index (character) to KVCacheEntry.
KVCache$new()Create a new KVCache.
KVCache$new(kv = list())
kvOptional 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).
KVCache$is_populated()
Logical scalar.
KVCache$slice()Slice all entries along batch dimensions.
Returns a new cache of the same class with sliced entries.
KVCache$slice(indices)
indicesIndices for slicing.
A new KVCache instance.
KVCache$write()Write batch-sliced entries into this pre-allocated cache.
KVCache$write(indices, other)
indicesIndices for writing.
otherA KVCache instance to write from.
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.
KVCache$to(device, dtype = NULL)
deviceDevice string.
dtypeOptional torch_dtype.
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.
KVCache$preallocate(reference, batch_shape, device = "cpu", dtype = NULL)
referenceA KVCache from a single batch whose entry shapes
are used as a template.
batch_shapeInteger vector. The full batch shape for leading dims.
deviceDevice on which to allocate tensors. Default "cpu".
dtypeOptional torch_dtype. If NULL, uses reference
entry dtype.
Invisible self (for method chaining).
KVCache$clone()The objects of this class are cloneable with this method.
KVCache$clone(deep = FALSE)
deepWhether to make a deep clone.
## 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)## 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)
Stores cached key and value projections from an attention layer.
An R6::R6Class object.
Key and value tensors have shape (batch, num_heads, seq_len, head_dim).
keyCached key projections. A torch_tensor or NULL.
valueCached value projections. A torch_tensor or NULL.
KVCacheEntry$new()Create a new KVCacheEntry.
KVCacheEntry$new(key = NULL, value = NULL)
keyOptional torch_tensor.
valueOptional torch_tensor.
KVCacheEntry$is_valid()Check if this cache entry contains valid data.
KVCacheEntry$is_valid()
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.
KVCacheEntry$slice(indices, drop = FALSE)
indicesIndices for slicing. Can be an integer vector, a
torch_tensor, or use .. for all elements.
dropdrop unitary dimension
A new KVCacheEntry instance.
KVCacheEntry$write()Write a batch slice into this entry.
KVCacheEntry$write(indices, other)
indicesIndices for writing.
otherA KVCacheEntry instance to write from.
Invisible self (for method chaining).
KVCacheEntry$to()Move this entry to the given device and optionally cast dtype.
Returns a new KVCacheEntry.
KVCacheEntry$to(device, dtype = NULL)
deviceDevice string, e.g. "cpu" or "cuda".
dtypeOptional torch_dtype.
A new KVCacheEntry instance.
KVCacheEntry$clone()The objects of this class are cloneable with this method.
KVCacheEntry$clone(deep = FALSE)
deepWhether to make a deep clone.
## 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)## 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
multihead_attention(embed_dim, num_heads, dropout = 0, ssmax = FALSE)multihead_attention(embed_dim, num_heads, dropout = 0, ssmax = FALSE)
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: |
ssmax |
Logical or character. Type of scalable softmax to use:
|
A nn_module for multi-head attention with advanced features.
The implementation always uses batch_first = TRUE, so input tensors have
shape (.., seq_len, embed_dim).
Su et al., "RoFormer: Enhanced Transformer with Rotary Position Embedding"
Liu et al., "Scalable-Softmax Is Superior for Attention"
Attention block supporting RoPE, scalable softmax, and KV caching
multihead_attention_block( d_model, nhead, dim_feedforward, dropout = 0, activation = "gelu", norm_first = TRUE, bias_free_ln = FALSE, ssmax = FALSE )multihead_attention_block( d_model, nhead, dim_feedforward, dropout = 0, activation = "gelu", norm_first = TRUE, bias_free_ln = FALSE, ssmax = FALSE )
d_model |
Integer. Model dimension. |
nhead |
Integer. Number of attention heads. |
dim_feedforward |
Integer. Dimension of the feedforward network. |
dropout |
Numeric. Dropout probability (default: |
activation |
Character or function. Activation function for feedforward:
|
norm_first |
Logical. If |
bias_free_ln |
Logical. If |
ssmax |
Logical or character. Type of scalable softmax to use in attention
(default: |
A nn_module for transformer encoder layer with advanced features.
A compact tabular in-context learning model with column, row, and ICL attention blocks.
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 )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 )
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 |
An nn_module ready for training/inference
Combines one-hot encoding and linear projection in a single efficient operation to convert categorical indices to embeddings.
one_hot_and_linear(num_classes, embed_dim)one_hot_and_linear(num_classes, embed_dim)
num_classes |
Integer. Number of distinct categories for one-hot encoding. |
embed_dim |
Integer. Output embedding dimension. |
A nn_module that transforms integer indices to dense embeddings.
## 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)## 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)
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.
A PinnedBufferPool object.
PinnedBufferPool$new()PinnedBufferPool$new(max_buffers_per_shape = 4L)
max_buffers_per_shapeInteger. Maximum buffers per (shape, dtype)
PinnedBufferPool$get()PinnedBufferPool$get(shape, dtype)
shapeInteger vector. Shape of the tensor.
dtypetorch.dtype. Data type of the tensor.
A pinned CPU tensor.
PinnedBufferPool$put()PinnedBufferPool$put(buf)
bufTensor. Buffer to return.
PinnedBufferPool$clear()PinnedBufferPool$clear()
A cleared private pool
PinnedBufferPool$clone()The objects of this class are cloneable with this method.
PinnedBufferPool$clone(deep = FALSE)
deepWhether to make a deep clone.
## 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)## 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)
TabICL2
Predict using TabICL2
## 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, ...)## 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, ...)
object |
A |
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 |
x |
A |
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.
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)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)
Applies scaling to queries using two MLPs:
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 ().
QASSMaxMLP(num_heads, head_dim, n_hidden = 64L, elementwise = FALSE)QASSMaxMLP(num_heads, head_dim, n_hidden = 64L, elementwise = FALSE)
num_heads |
|
head_dim |
|
|
|
|
elementwise |
|
An nn_module object (class generator).
Converts predicted quantiles to QuantileDistribution with analytical statistics.
quantile_to_distribution( alpha_levels = NULL, num_quantiles = 999L, tail_type = "exp", fix_crossing = TRUE, crossing_method = "sort" )quantile_to_distribution( alpha_levels = NULL, num_quantiles = 999L, tail_type = "exp", fix_crossing = TRUE, crossing_method = "sort" )
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. |
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)
QuantileDistribution( quantiles, alpha_levels = NULL, tail_type = "exp", fix_crossing = TRUE, crossing_method = "sort" )QuantileDistribution( quantiles, alpha_levels = NULL, tail_type = "exp", fix_crossing = TRUE, crossing_method = "sort" )
quantiles |
Tensor. Quantile values after monotonicity correction.
Shape: |
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. |
Numerical stability parameters, tail parameters, computational limits, and tail inference parameters for quantile distribution estimation.
QuantileDistributionConfigQuantileDistributionConfig
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)
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)
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_QUANTILES_FOR_ESTIMATION: Number of tail quantiles (default: 20)
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.
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 )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 )
dim |
Integer. The dimension of the embeddings. |
interleaved |
Logical. If |
custom_freqs |
Tensor or |
freqs_for |
Character. One of |
theta |
Numeric. Base scaling factor (default: |
max_freq |
Numeric. Maximum frequency for pixel-based embeddings (default: |
num_freqs |
Integer. Number of frequencies for |
learned_freq |
Logical. If |
use_xpos |
Logical. If |
xpos_scale_base |
Numeric. Base scaling factor used for XPOS (default: |
interpolate_factor |
Numeric. Factor by which sequence length is interpolated (default: |
theta_rescale_factor |
Numeric. Rescaling factor applied to theta (default: |
seq_before_head_dim |
Logical. If |
cache_if_possible |
Logical. If |
An nn_module object.
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.
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 )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 )
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: |
rope_base |
Numeric. Base scaling factor for rotary position encoding
(default: |
rope_interleaved |
Logical. If |
dropout |
Numeric. Dropout probability in the encoder (default: |
activation |
Character or function. Activation for the feedforward
network: |
norm_first |
Logical. If |
bias_free_ln |
Logical. If |
recompute |
Logical. If |
An nn_module instance of class RowInteraction.
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)
A set transformer uses induced self-attention mechanism to efficiently process variable-sized sets while maintaining permutation invariance.
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 )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 )
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
|
dim_feedforward |
Integer. Dimension of the feedforward network in each block. |
num_inds |
Integer, default |
dropout |
Float, default |
activation |
Character string or unary function, default |
norm_first |
Logical, default |
bias_free_ln |
Logical, default |
ssmax |
Logical or character string, default |
recompute |
Logical, default |
An nn_module instance of class SetTransformer.
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)
Lee et al. "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks", ICML 2019.
induced_self_attention_block, KVCache,
KVCacheEntry
First applies the linear transformation to all inputs, then replaces outputs
for inputs where all values equal skip_value with the skip_value.
skippable_linear(in_features, out_features, bias = TRUE, skip_value = -100)skippable_linear(in_features, out_features, bias = TRUE, skip_value = -100)
in_features |
Integer. Size of each input sample. |
out_features |
Integer. Size of each output sample. |
bias |
Logical. If |
skip_value |
Numeric. Value used to mark inputs that should be skipped
(default: |
A nn_module that applies linear transformation with skip handling.
## 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)## 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)
Applies scaling to queries:
,
where is a learnable per-head parameter.
SSMax(num_heads)SSMax(num_heads)
num_heads |
|
An nn_module object (class generator).
Applies scaling to queries:
,
where a small MLP learns to map sequence length to scaling factors.
SSMaxMLP(num_heads, n_hidden = 64L, elementwise = FALSE, head_dim = NULL)SSMaxMLP(num_heads, n_hidden = 64L, elementwise = FALSE, head_dim = NULL)
num_heads |
|
|
|
|
elementwise |
|
head_dim |
|
An nn_module object (class generator).
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.
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, ... )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, ... )
x |
Depending on the context:
|
... |
Not currently used, but required for extensibility. |
y |
When
|
config |
A list of model architecture options produced by
|
control |
A list of inference execution options produced by
|
model_version |
A character string identifying the checkpoint to load. Three forms are accepted:
When |
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,
|
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.
Predictors do not require preprocessing; missing values and factor vectors are allowed.
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")
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.
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
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).
tab_icl2_config(), tab_icl2_control(), predict.tab_icl_v2()
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)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
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, ... )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, ... )
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). |
A list with class "tab_icl2_config" containing one element per
architecture parameter, all coerced to integer.
tab_icl2_config() tab_icl2_config(embed_dim = 256L, icl_n_block = 8L)tab_icl2_config() tab_icl2_config(embed_dim = 256L, icl_n_block = 8L)
Control TabICL2 inference execution
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(), ... )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(), ... )
device |
A character string or |
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 |
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. |
A list with class "tab_icl2_control" containing resolved
per-stage settings in $col, $row, and $icl, plus
$ignore_pretraining_limits.
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)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 along the batch dimension.
tabicl_cache_concat(caches, dim = 1)tabicl_cache_concat(caches, dim = 1)
caches |
List of |
dim |
Integer. Dimension to concatenate along (batch dimension).
Default is |
A new TabICLCache with concatenated caches.
Aggregates caches for different components of TabICL:
ColEmbedding cache (for ISAB blocks in column embedding)
ICLearning cache (for Encoder layers in the ICL transformer)
An R6::R6Class object.
The train_shape field stores (batch_size, train_size, num_features)
as a 3-element integer vector.
col_cacheOptional KVCache for ColEmbedding ISAB blocks.
row_reprOptional torch_tensor. Cached row representations.
icl_cacheOptional KVCache for ICLearning Encoder layers.
train_shapeInteger vector of length 3:
(batch_size, train_size, num_features).
num_classesOptional integer. Number of classes in classification tasks (0 for regression). Stored when caching to ensure consistent output shape during cache use.
TabICLCache$new()Create a new TabICLCache.
Initializes sub-caches automatically if not provided.
TabICLCache$new( col_cache = NULL, row_repr = NULL, icl_cache = NULL, train_shape = c(0, 0, 0), num_classes = NULL )
col_cacheOptional KVCache.
row_reprOptional torch_tensor.
icl_cacheOptional KVCache.
train_shapeInteger vector of length 3. Default c(0, 0, 0).
num_classesOptional integer.
TabICLCache$cache_type()Return the cache type.
TabICLCache$cache_type()
Character string: "kv", "repr", or "empty".
TabICLCache$cache_size_mb()Return the memory occupied by cached tensors in MB.
TabICLCache$cache_size_mb()
Integer.
TabICLCache$is_empty()Check if the cache is empty.
TabICLCache$is_empty()
Logical scalar.
TabICLCache$slice_batch()Slice this cache along the batch dimension (dim 1 in R).
TabICLCache$slice_batch(start, end)
startInteger. Start index of the batch slice (1-based, inclusive).
endInteger. End index of the batch slice (1-based, exclusive).
A new TabICLCache with sliced tensors (views of original).
TabICLCache$to()Move all cached tensors to the given device and optionally cast dtype.
TabICLCache$to(device, dtype = NULL)
deviceDevice string, e.g. "cpu" or "cuda:0".
dtypeOptional torch_dtype. If NULL, preserves
existing dtype.
A new TabICLCache with all tensors on the target device.
TabICLCache$clone()The objects of this class are cloneable with this method.
TabICLCache$clone(deep = FALSE)
deepWhether to make a deep clone.
## Not run: cache <- TabICLCache$new( train_shape = c(4, 100, 20), num_classes = 10 ) cache$cache_type() ## End(Not run)## Not run: cache <- TabICLCache$new( train_shape = c(4, 100, 20), num_classes = 10 ) cache$cache_type() ## End(Not run)
TabICL is a transformer-based architecture for in-context learning on tabular data. This class is the underlying raw torch module.
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 )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 )
config |
A
|
max_classes |
Integer, default |
col_affine |
Logical, default |
col_feature_group |
Character, default |
col_target_aware |
Logical, default |
col_ssmax |
Character, default |
row_rope_base |
Float, default |
row_rope_interleaved |
Logical, default |
icl_ssmax |
Character, default |
ff_factor |
Integer, default |
dropout |
Float, default |
activation |
Character, default |
norm_first |
Logical, default |
bias_free_ln |
Logical, default |
recompute |
Logical, default |
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:
Column-wise embedding creates distribution-aware embeddings.
Row-wise interaction captures interactions between features within each row.
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.
An nn_module instance of class TabICL.
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.
ColEmbedding, RowInteraction,
ICLearning, quantile_to_distribution,
TabICLCache, inference_config