pytabkit.models package

Subpackages

Submodules

pytabkit.models.torch_utils module

class pytabkit.models.torch_utils.ClampWithIdentityGradientFunc

Bases: Function

static backward(ctx, grad_output)

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

Parameters:

grad_output (Tensor)

static forward(ctx, input, low, high)

Define the forward of the custom autograd Function.

This function is to be overridden by all subclasses. There are two ways to define forward:

Usage 1 (Combined forward and ctx):

@staticmethod
def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any:
    pass
  • It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types).

  • See combining-forward-context for more details

Usage 2 (Separate forward and ctx):

@staticmethod
def forward(*args: Any, **kwargs: Any) -> Any:
    pass


@staticmethod
def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
    pass
  • The forward no longer accepts a ctx argument.

  • Instead, you must also override the torch.autograd.Function.setup_context() staticmethod to handle setting up the ctx object. output is the output of the forward, inputs are a Tuple of inputs to the forward.

  • See extending-autograd for more details

The context can be used to store arbitrary data that can be then retrieved during the backward pass. Tensors should not be stored directly on ctx (though this is not currently enforced for backward compatibility). Instead, tensors should be saved either with ctx.save_for_backward() if they are intended to be used in backward (equivalently, vjp) or ctx.save_for_forward() if they are intended to be used for in jvp.

Parameters:
  • input (Tensor)

  • low (Tensor)

  • high (Tensor)

class pytabkit.models.torch_utils.TorchTimer

Bases: object

Timer for measuring code blocks, with optional CUDA synchronization.

Usage:
with TorchTimer() as t:

y = model(x)

print(t.elapsed)

# Or manual start/stop: t = TorchTimer() t.start() y = model(x) t.stop() print(t.elapsed)

__init__(use_cuda=None, record_history=False)
Args:
use_cuda:
  • None (default): auto-detect; sync only if CUDA is in use.

  • True: force CUDA sync (if available).

  • False: never sync CUDA.

record_history:

If True, every measurement is appended to self.history.

Parameters:
  • use_cuda (bool | None)

  • record_history (bool)

start()
stop()
pytabkit.models.torch_utils.batch_randperm(n_batch, n, device='cpu')
pytabkit.models.torch_utils.cat_if_necessary(tensors, dim)

Implements torch.cat() but doesn’t copy if only one tensor is provided. This can make it faster if no copying behavior is needed. :param tensors: Tensors to be concatenated. :param dim: Dimension in which the tensor should be concatenated. :return: The concatenated tensor.

Parameters:
  • tensors (List[Tensor])

  • dim (int)

pytabkit.models.torch_utils.clamp_with_identity_gradient_func(x, low, high)
pytabkit.models.torch_utils.gauss_cdf(x)
pytabkit.models.torch_utils.get_available_device_names()
Return type:

List[str]

pytabkit.models.torch_utils.get_available_memory_gb(device)

Return the available memory (in GB) on the given device.

Parameters

devicestr or torch.device

Device identifier, e.g. “cuda”, “cuda:0”, or torch.device(“cuda:0”).

Returns

float

Available memory in gigabytes.

Notes

  • For CUDA devices, this uses torch.cuda.mem_get_info if available.

  • For CPU, it uses psutil.virtual_memory().available.

  • For other device types, NotImplementedError is raised.

Parameters:

device (str | device)

Return type:

float

pytabkit.models.torch_utils.hash_tensor(tensor)
Parameters:

tensor (Tensor)

Return type:

int

pytabkit.models.torch_utils.permute_idxs(idxs, seed)
pytabkit.models.torch_utils.seeded_randperm(n, device, seed)
pytabkit.models.torch_utils.torch_np_quantile(tensor, q, dim, keepdim=False)

Alternative implementation for torch.quantile() using np.quantile() since the implementation of torch.quantile() uses too much RAM (extreme for Airlines_DepDelay_10M) and can fail for too large tensors. See also https://github.com/pytorch/pytorch/issues/64947 :param tensor: tensor :param q: Quantile value. :param dim: As in torch.quantile() :param keepdim: As in torch.quantile() :return: Tensor with quantiles.

Parameters:
  • tensor (Tensor)

  • q (float)

  • dim (int)

  • keepdim (bool)

Return type:

Tensor

pytabkit.models.utils module

class pytabkit.models.utils.FunctionProcess

Bases: object

Helper class to run a single function in a separate process.

__init__(f, *args, **kwargs)
get_ram_usage_gb()
Return type:

float

is_done()
Return type:

bool

pop_result()
Return type:

Any

start()
Return type:

FunctionProcess

class pytabkit.models.utils.FunctionRunner

Bases: object

__init__(dill_f_args_kwargs, result_queue)
class pytabkit.models.utils.ObjectLoadingContext

Bases: object

__init__(obj, filename=None)
Parameters:
  • obj (Any)

  • filename (str | Path | None)

class pytabkit.models.utils.ProcessPoolMapper

Bases: object

__init__(n_processes, chunksize=1)
Parameters:

n_processes (int)

map(f, args_tuples)
Parameters:

args_tuples (List[Tuple])

Return type:

Any

class pytabkit.models.utils.TabrQuantileTransformer

Bases: BaseEstimator, TransformerMixin

__init__(noise=0.001, random_state=None, n_quantiles=1000, subsample=1000000000, output_distribution='normal')
fit(X, y=None)
transform(X, y=None)
class pytabkit.models.utils.TimePrinter

Bases: object

__init__(desc)
Parameters:

desc (str)

class pytabkit.models.utils.Timer

Bases: object

__init__()
get_result_dict()
pause()
start()
pytabkit.models.utils.adapt_config(config, **kwargs)
pytabkit.models.utils.all_equal(lst)
Parameters:

lst (List)

pytabkit.models.utils.argsort(lst)
pytabkit.models.utils.combine_seeds(seed_1, seed_2)

Combines two random seeds to a new seed in a hopefully “typically injective” way :param seed_1: First random seed. :param seed_2: Second random seed. :return: Another random seed

Parameters:
  • seed_1 (int)

  • seed_2 (int)

Return type:

int

pytabkit.models.utils.convert_numpy_dtypes(data)

Converts NumPy dtypes in a dictionary to Python dtypes. Some hyperparameter search space’s generate configs with numpy dtypes which aren’t serializable to yaml. This fixes that.

Parameters:

data (dict)

Return type:

dict

pytabkit.models.utils.copyFile(src, dst)
pytabkit.models.utils.create_dir(path)
pytabkit.models.utils.delete_file(path)
pytabkit.models.utils.deserialize(filename, compressed=False, use_json=False, use_yaml=False, use_msgpack=False, use_pickle=False)
Parameters:
  • filename (Path | str)

  • compressed (bool)

  • use_json (bool)

  • use_yaml (bool)

  • use_msgpack (bool)

  • use_pickle (bool)

pytabkit.models.utils.ensureDir(file_path)
pytabkit.models.utils.existsDir(directory)
pytabkit.models.utils.existsFile(file_path)
pytabkit.models.utils.extract_params(config, param_configs)

Convert parameters in config to correct parameter names for another method and (optionally) insert default values :param config: Dictionary with values for parameters :param param_configs: Tuples specifying parameter names, e.g.: (‘eta’, None) specifies that result[‘eta’] = config[‘eta’] should be set if ‘eta’ is in config (‘eta’, ‘lr’) specifies that result[‘eta’] = config[‘lr’] should be set if ‘lr’ is in config (‘eta, [‘eta’, ‘lr’]) specifies that either config[‘eta’] or config[‘lr’] should be used, if available A third value in the tuple specifies a default value that should be used if no value is available in config. :return: A dictionary as specified above.

Parameters:
  • config (Dict[str, Any])

  • param_configs (List[Tuple[str, str | List[str] | None] | Tuple[str, str | List[str] | None, Any]])

Return type:

Dict[str, Any]

pytabkit.models.utils.getSubfolderNames(folder)
pytabkit.models.utils.getSubfolders(folder)
pytabkit.models.utils.get_batch_intervals(n_total, batch_size)
Parameters:
  • n_total (int)

  • batch_size (int)

Return type:

List[Tuple[int, int]]

pytabkit.models.utils.get_uuid_str()
pytabkit.models.utils.identity(x)
pytabkit.models.utils.join_dicts(*dicts)
pytabkit.models.utils.map_nested(obj, f, dim)

dim=0 will apply f to obj directly, dim=1 to all elements in obj, etc.

Parameters:
  • obj (List | Dict | Any)

  • f (Callable)

  • dim (int)

pytabkit.models.utils.matchFiles(file_matcher)
pytabkit.models.utils.newDirname(prefix)
pytabkit.models.utils.nsmallest(n, inputList)
pytabkit.models.utils.numpy_to_native_rec(obj)
Parameters:

obj (Any)

pytabkit.models.utils.pretty_table_str(str_table)
pytabkit.models.utils.readFromFile(filename)
pytabkit.models.utils.reverse_argmin(x)

Does the same as np.argmin but in case of equality selects the last best one :param x: list or array of numbers :return: index of last minimum

Parameters:

x (List | ndarray)

pytabkit.models.utils.select_from_config(config, keys)
Parameters:
  • config (Dict)

  • keys (List)

pytabkit.models.utils.select_nested(obj, idx, dim)
Parameters:
  • obj (List | Dict)

  • idx (Any)

  • dim (int)

pytabkit.models.utils.serialize(filename, obj, compressed=False, use_json=False, use_yaml=False, use_msgpack=False, use_pickle=False)
Parameters:
  • filename (Path | str)

  • obj (Any)

  • compressed (bool)

  • use_json (bool)

  • use_yaml (bool)

  • use_msgpack (bool)

  • use_pickle (bool)

pytabkit.models.utils.set_none_except(lst, idxs)
pytabkit.models.utils.shift_dim_nested(obj, dim1, dim2)
Parameters:
  • obj (List | Dict)

  • dim1 (int)

  • dim2 (int)

pytabkit.models.utils.update_dict(d, update=None, remove_keys=None)
Parameters:
  • d (dict)

  • update (dict | None)

  • remove_keys (Any | List[Any] | None)

pytabkit.models.utils.writeToFile(filename, content)

Module contents