pyhealth.models.XGBoostModel#
Gradient-boosted trees (XGBoost) on fixed-width tabular and bag-of-codes
features. The model is fit once with model.fit(train_loader, val_loader),
then evaluated, saved and interpreted through the usual PyHealth APIs.
Install the optional extra first:
pip install "pyhealth[xgboost]"
from pyhealth.datasets import get_dataloader
from pyhealth.models import XGBoostModel
from pyhealth.trainer import Trainer
model = XGBoostModel(
sample_dataset,
bag_of_codes=True, # code sequences -> per-sample code counts
n_estimators=400, max_depth=4, learning_rate=0.05,
scale_pos_weight="balanced", # negatives / positives in the training labels
)
model.fit(get_dataloader(train_ds, 256), get_dataloader(val_ds, 256))
trainer = Trainer(model=model)
trainer.evaluate(get_dataloader(test_ds, 256))
trainer.save_ckpt("xgb.ckpt") # the fitted trees round-trip
model.mean_abs_shap(test_ds) # global TreeSHAP ranking
Things to know:
Trainer.trainraises aTypeErrorfor this model: fit it withmodel.fit.Inputs. Columns are built from the fields in
input_schemaorder, which matters because column subsampling depends on the order. Padded code sequences raise an error unless you passbag_of_codes=True.Missing values.
NaNstays missing and XGBoost learns where it goes at each split. This gives different trees from median imputation.Imbalance.
scale_pos_weightinflates probabilities. Recalibrate on a patient-grouped calibration split (e.g. Platt scaling) if you need calibrated risks; the model does not calibrate silently.Memory. The training matrix is held in memory as dense float32 (
n_samples x n_columns x 4bytes).macOS. PyTorch’s wheel bundles its own
libomp.dylib. XGBoost loads Homebrew’slibomp. Two OpenMP runtimes in one process can crash multithreaded fits with a segfault orOMP: Error #179. Make the two share one runtime, for example by replacing<site-packages>/torch/lib/libomp.dylibwith a symlink to$(brew --prefix libomp)/lib/libomp.dylib, or passn_jobs=1.
Example: examples/mortality_prediction/mortality_mimic3_xgboost.py compares
XGBoost with LogisticRegression and MLP on the same patient split.
- class pyhealth.models.XGBoostModel(dataset, n_estimators=None, max_depth=None, learning_rate=None, subsample=None, colsample_bytree=None, tree_method=None, random_state=None, n_jobs=None, missing=nan, device=None, early_stopping_rounds=None, eval_metric=None, scale_pos_weight=None, bag_of_codes=False, feature_names=None, **xgb_params)[source]#
Bases:
GradientBoostedTreeModelGradient-boosted trees (XGBoost) with PyHealth’s dataset, Trainer and metrics.
Fit once with
fit()(notTrainer.train, which raises aTypeErrorfor this model), then useTrainer.evaluate/Trainer.inferenceandTrainer.save_ckpt/load_ckptas for any other model. SeeGradientBoostedTreeModelfor the supported input fields and how the feature matrix is built.Label modes, read from the output processor:
binary:XGBClassifierwithobjective="binary:logistic". Predictions are identical to a plainXGBClassifierwith the same parameters on the same matrix (seebuild_feature_matrix()).multiclass:XGBClassifierwithobjective="multi:softprob".multilabel: one booster per label (binary:logistic), so each label gets its ownscale_pos_weightand early-stopping round.regression:XGBRegressor(reg:squarederrorunlessobjectiveis given).
logitis the booster margin (output_margin=True) andy_probthe booster’s own probabilities, so no probability is clipped or inverted.Missing values.
NaNis passed to XGBoost as missing (missing=np.nan), and each split learns which way missing values go. Imputing first (e.g. median imputation in a processor) gives different trees from this native handling. XGBoost stores features as float32; a processor that imputes or scales should compute its statistics in float64 and cast to float32 once, which matches scikit-learn pipelines exactly.Class imbalance.
scale_pos_weight="balanced"(or"auto") uses negatives / positives in the training labels, per label for multilabel. It inflates predicted probabilities; if calibration matters, recalibrate on a patient-grouped calibration split (e.g. Platt scaling) rather than reading the raw probabilities as risks.Early stopping. Off by default, so results match a plain
XGBClassifier. Withearly_stopping_roundsand aval_datainfit(), training stops wheneval_metric(e.g."aucpr"for rare outcomes) stops improving, and predictions use the best iteration.Interpretation.
explain()gives exact TreeSHAP values from XGBoost (pred_contribs=True);mean_abs_shap()ranks columns; andpyhealth.interpret.methods.TreeSHAPmaps them onto the input fields like the other interpreters.macOS. XGBoost and PyTorch each load an OpenMP runtime (Homebrew’s
libompand the copy bundled in the torch wheel). Two copies in one process can crash multithreaded fits (segfault, orOMP: Error #179). Make both use one copy, e.g. replacetorch/lib/libomp.dylibwith a symlink to Homebrew’slibomp.dylib, or usen_jobs=1.- Parameters:
dataset (
SampleDataset) – The dataset defining inputs and the label.n_estimators (
Optional[int]) – tree_method, random_state, n_jobs, device: Passed to XGBoost; None keeps XGBoost’s default.device=Noneuses"cuda"when the model is on a CUDA device at fit time.max_depth (
Optional[int]) – tree_method, random_state, n_jobs, device: Passed to XGBoost; None keeps XGBoost’s default.device=Noneuses"cuda"when the model is on a CUDA device at fit time.learning_rate (
Optional[float]) – tree_method, random_state, n_jobs, device: Passed to XGBoost; None keeps XGBoost’s default.device=Noneuses"cuda"when the model is on a CUDA device at fit time.subsample (
Optional[float]) – tree_method, random_state, n_jobs, device: Passed to XGBoost; None keeps XGBoost’s default.device=Noneuses"cuda"when the model is on a CUDA device at fit time.colsample_bytree (
Optional[float]) – tree_method, random_state, n_jobs, device: Passed to XGBoost; None keeps XGBoost’s default.device=Noneuses"cuda"when the model is on a CUDA device at fit time.
- :paramtree_method, random_state, n_jobs, device: Passed to XGBoost; None
keeps XGBoost’s default.
device=Noneuses"cuda"when the model is on a CUDA device at fit time.
- Parameters:
missing (
float) – Value treated as missing. Defaultnp.nan.early_stopping_rounds (
Optional[int]) – Rounds without improvement onval_databefore stopping. Default None (no early stopping).eval_metric (
Optional[str]) – Metric forval_data(e.g."aucpr","logloss").scale_pos_weight (
UnionType[float,Sequence[float],str,None]) – A number, one per label (multilabel),"balanced"/"auto", or None.bag_of_codes (
bool) – Encode code sequences as per-sample code counts.feature_names (
Optional[dict[str,Sequence[str]]]) – Optional{field: [name, ...]}for tensor fields.**xgb_params (
Any) – Any other XGBoost parameter (nthread,reg_lambda,min_child_weight,objectivefor regression, …).
Examples
>>> from pyhealth.datasets import create_sample_dataset, get_dataloader >>> from pyhealth.models import XGBoostModel >>> samples = [ ... {"patient_id": f"p{i}", "labs": [float(i % 7), float(i % 3)], ... "label": int(i % 7 > 3)} ... for i in range(40) ... ] >>> dataset = create_sample_dataset( ... samples, {"labs": "tensor"}, {"label": "binary"} ... ) >>> model = XGBoostModel(dataset, n_estimators=20, max_depth=2) >>> loader = get_dataloader(dataset, batch_size=16) >>> model = model.fit(loader) >>> out = model(**next(iter(loader))) >>> out["y_prob"].shape torch.Size([16, 1]) >>> model.feature_names ['labs[0]', 'labs[1]']
Initializes the BaseModel.
- Parameters:
dataset (SampleDataset) – The dataset to train the model.
- add_module(name, module)#
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)#
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()#
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)#
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type:
Iterator[Tensor]
- build_feature_matrix(**batch)#
Turns a batch into the float32
(n, n_columns)matrix the trees see.Examples
>>> X = model.build_feature_matrix(**batch) >>> X.shape[1] == len(model.feature_names) True
- Return type:
ndarray
- children()#
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- Return type:
Iterator[Module]
- compile(*args, **kwargs)#
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()#
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)#
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- property device: device#
Gets the device of the model.
- Returns:
The device on which the model is located.
- Return type:
torch.device
- double()#
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()#
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- explain(**batch)#
Exact TreeSHAP attributions for a batch, per field and column.
Contributions are on the margin (log-odds for classification) and add up exactly, up to float32 rounding: for every sample, the sum over all columns plus
biasequalslogit.- Return type:
- Returns:
A dict with
"attributions"({field: tensor}, each(n, field_width), with a trailing class/label dimension for multiclass and multilabel),"bias"((n,), or(n, K)),"logit"and"feature_names"({field: [name, ...]}).
Examples
>>> out = model.explain(**batch) >>> total = sum(a.sum(1) for a in out["attributions"].values()) >>> torch.allclose(total + out["bias"], out["logit"].squeeze(-1), atol=1e-4) True
- extra_repr()#
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- fit(train_data, val_data=None)#
Fits the trees on the full training set in one call.
Batches are concatenated in loader order and no sample is dropped. Pass an unshuffled loader (or a dataset, which is read unshuffled) so the fit is reproducible.
- Parameters:
train_data (
DataLoader|SampleDataset) – Training loader or dataset (the training split only).val_data (
UnionType[DataLoader,SampleDataset,None]) – Optional validation loader or dataset, used for early stopping whenearly_stopping_roundsis set.
- Return type:
- Returns:
The fitted model.
- Raises:
ValueError – If a field is not fixed-width, the loader drops samples, or a multiclass training set lacks a class.
- fit_outside_trainer = True#
Tells
Trainer.trainthat this model is fit withmodel.fit.
- float()#
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(**kwargs)#
Predicts with the fitted trees.
logitis the trees’ raw margin (not an inverted probability), andlossisget_loss_function()on it.
- get_buffer(target)#
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()#
Fitted trees as raw bytes in uint8 tensors, plus the feature layout.
Only tensors, strings and numbers, so checkpoints load with
torch.load(weights_only=True).
- get_loss_function()#
Gets the default loss function using self.mode.
- The default loss functions are:
binary: F.binary_cross_entropy_with_logits
multiclass: F.cross_entropy
multilabel: F.binary_cross_entropy_with_logits
regression: F.mse_loss
timeseries_binary: F.binary_cross_entropy_with_logits per time step, averaged over the labeled steps
timeseries_regression: F.mse_loss per time step, averaged over the labeled steps
The timeseries losses take per-step logits of shape (batch, steps, 1) and the batched
(value, mask)label, each of shape (batch, steps), produced by an output processor whoseprocess()returns(value, mask)per sample with mask 0 for steps without a label. Values at masked steps are ignored and may be NaN.For binary and multilabel labels, a weight set with
set_pos_weight()is passed aspos_weight.- Returns:
The default loss function.
- Return type:
Callable
- get_output_size()#
Gets the default output size using the label tokenizer and self.mode.
If the mode is “binary”, the output size is 1. If the mode is “multiclass” or “multilabel”, the output size is the number of classes or labels.
- Returns:
The output size of the model.
- Return type:
- get_parameter(target)#
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)#
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()#
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)#
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)#
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- mean_abs_shap(data)#
Global importance: mean |TreeSHAP| per column, largest first.
For multiclass and multilabel outputs the mean is also taken over classes or labels.
Examples
>>> ranking = model.mean_abs_shap(test_loader) >>> list(ranking)[:3] ['age', 'fev1', 'conditions=J45.909']
- property mode: str | None#
one of
VALID_MODES, orNoneif not applicable.- Type:
The label kind
- Return type:
Optional[str]
- modules(remove_duplicate=True)#
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type:
Iterator[Module]
- mtia(device=None)#
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)#
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()#
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)#
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)#
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)#
Return an iterator over module parameters.
The exact order of the returned parameters is unspecified, but repeated calls to the
parameters()method of an unchanged module return the parameters in the same order.This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type:
Iterator[Parameter]
- property pos_weight: torch.Tensor | None#
Weight of positive examples in the binary/multilabel loss, or None.
- Return type:
Optional[Tensor]
- predict_numpy(X)#
Margins and probabilities (or predictions) for a feature matrix.
- Return type:
tuple[ndarray,ndarray]- Returns:
(logit, y_prob), each(n, 1)for binary and regression,(n, n_classes)for multiclass,(n, n_labels)for multilabel.
- prepare_y_prob(logits)#
Prepares the predicted probabilities for model evaluation.
This function converts the predicted logits to predicted probabilities depending on the mode. The default formats are:
- binary: a tensor of shape (batch_size, 1) with values in [0, 1],
which is obtained with torch.sigmoid()
- multiclass: a tensor of shape (batch_size, num_classes) with
values in [0, 1] and sum to 1, which is obtained with torch.softmax()
- multilabel: a tensor of shape (batch_size, num_labels) with values
in [0, 1], which is obtained with torch.sigmoid()
regression: a tensor of shape (batch_size, 1) with raw logits
- timeseries_binary: a tensor of shape (batch_size, steps, 1)
with values in [0, 1] per time step, from torch.sigmoid()
- timeseries_regression: a tensor of shape (batch_size, steps, 1)
with raw logits per time step
- Parameters:
logits (torch.Tensor) – The predicted logit tensor.
- Returns:
The predicted probability tensor.
- Return type:
torch.Tensor
- register_backward_hook(hook)#
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)#
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type:
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)#
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)#
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)#
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)#
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)#
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)#
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)#
Alias for
add_module().- Return type:
- register_parameter(name, param)#
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)#
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)#
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)#
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state)#
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- set_pos_weight(pos_weight, dataset=None)#
Weights positive examples in the default loss, for rare outcomes.
Applies to binary and multilabel labels, through
get_loss_function()(pos_weightofF.binary_cross_entropy_with_logits). Models that compute their own loss (e.g. the drug-recommendation models) are not affected. Weighting changes the scale of the predicted probabilities, so check calibration when you use it.- Parameters:
pos_weight (
UnionType[float,Sequence[float],Tensor,str,None]) – A number (binary), one number per label (multilabel),"balanced"for negatives / positives indataset, or None to remove the weight.dataset (
Optional[Iterable[dict]]) – The training samples, required for"balanced". Pass the training split, not the full dataset, so validation and test labels do not set the weight.
- Raises:
ValueError – If the label is not binary or multilabel, or
"balanced"is given without a dataset.
Examples
>>> model.set_pos_weight(4.0) >>> model.set_pos_weight("balanced", train_dataset)
- Return type:
- set_submodule(target, module, strict=False)#
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)#
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)#
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)#
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)#
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)#
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)#
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)#
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.
- class pyhealth.models.GradientBoostedTreeModel(dataset, bag_of_codes=False, feature_names=None, scale_pos_weight=None)[source]#
Bases:
BaseModelBase class for gradient-boosted tree models on fixed-width features.
Subclasses provide the library-specific parts: building one estimator, margins, probabilities, exact TreeSHAP contributions, and converting a fitted estimator to and from bytes.
Feature matrix. Fields are concatenated in the order of the dataset’s
input_schema(self.feature_keys). Column order matters: column subsampling (e.g.colsample_bytree) depends on it, so the same seed with a different order gives different trees. Each field’s columns are recorded infeature_layoutand named infeature_names.Supported inputs:
tensor,timeseriesand label processors used as inputs (binary,multiclass,regression): flattened per sample. The per-sample shape must be the same in every batch, or aValueErrornames the field.NaNis passed through as missing.multi_hot: one column per vocabulary entry.nested_multihot: summed over visits, one column per code (number of visits containing the code), excluding<pad>and<unk>.sequence,nested_sequence,deep_nested_sequence: only withbag_of_codes=True, as per-sample counts over the processor’s vocabulary, excluding<pad>and<unk>. Their padded width depends on the batch, so flattening them would misalign columns between batches; withoutbag_of_codesthey raise aValueErrornaming the field.Custom (non-PyHealth) processors returning numeric tensors: flattened like
tensor, with the same fixed-shape check.
Any other PyHealth processor raises a
ValueErrornaming the field.Memory.
fitmaterializes the training (and validation) matrix as dense float32:n_samples * n_columns * 4bytes. Withbag_of_codesthe width is the vocabulary size; trim large vocabularies first.- Parameters:
dataset (
SampleDataset) – The dataset whose schemas and processors define the inputs and the label.bag_of_codes (
bool) – Encode padded code sequences as per-sample code counts. Default False (they raise an error).feature_names (
Optional[dict[str,Sequence[str]]]) – Optional column names fortensor-like fields,{field: [name, ...]}, one per flattened column.scale_pos_weight (
UnionType[float,Sequence[float],str,None]) – Weight of positive examples for binary and multilabel labels: a number, one number per label (multilabel),"balanced"(alias"auto") for negatives / positives in the training labels, or None. Weighting inflates predicted probabilities, so recalibrate on held-out patients if calibration matters.
Examples
>>> from pyhealth.models import GradientBoostedTreeModel, XGBoostModel >>> issubclass(XGBoostModel, GradientBoostedTreeModel) True >>> model = XGBoostModel(dataset, bag_of_codes=True) >>> model.fit(train_loader, val_loader) >>> model.feature_layout[0]["key"], model.feature_names[:2] ('conditions', ['conditions=4019', 'conditions=2724'])
Initializes the BaseModel.
- Parameters:
dataset (SampleDataset) – The dataset to train the model.
- fit_outside_trainer = True#
Tells
Trainer.trainthat this model is fit withmodel.fit.
- build_feature_matrix(**batch)[source]#
Turns a batch into the float32
(n, n_columns)matrix the trees see.Examples
>>> X = model.build_feature_matrix(**batch) >>> X.shape[1] == len(model.feature_names) True
- Return type:
ndarray
- fit(train_data, val_data=None)[source]#
Fits the trees on the full training set in one call.
Batches are concatenated in loader order and no sample is dropped. Pass an unshuffled loader (or a dataset, which is read unshuffled) so the fit is reproducible.
- Parameters:
train_data (
DataLoader|SampleDataset) – Training loader or dataset (the training split only).val_data (
UnionType[DataLoader,SampleDataset,None]) – Optional validation loader or dataset, used for early stopping whenearly_stopping_roundsis set.
- Return type:
- Returns:
The fitted model.
- Raises:
ValueError – If a field is not fixed-width, the loader drops samples, or a multiclass training set lacks a class.
- predict_numpy(X)[source]#
Margins and probabilities (or predictions) for a feature matrix.
- Return type:
tuple[ndarray,ndarray]- Returns:
(logit, y_prob), each(n, 1)for binary and regression,(n, n_classes)for multiclass,(n, n_labels)for multilabel.
- forward(**kwargs)[source]#
Predicts with the fitted trees.
logitis the trees’ raw margin (not an inverted probability), andlossisget_loss_function()on it.
- explain(**batch)[source]#
Exact TreeSHAP attributions for a batch, per field and column.
Contributions are on the margin (log-odds for classification) and add up exactly, up to float32 rounding: for every sample, the sum over all columns plus
biasequalslogit.- Return type:
- Returns:
A dict with
"attributions"({field: tensor}, each(n, field_width), with a trailing class/label dimension for multiclass and multilabel),"bias"((n,), or(n, K)),"logit"and"feature_names"({field: [name, ...]}).
Examples
>>> out = model.explain(**batch) >>> total = sum(a.sum(1) for a in out["attributions"].values()) >>> torch.allclose(total + out["bias"], out["logit"].squeeze(-1), atol=1e-4) True
- mean_abs_shap(data)[source]#
Global importance: mean |TreeSHAP| per column, largest first.
For multiclass and multilabel outputs the mean is also taken over classes or labels.
Examples
>>> ranking = model.mean_abs_shap(test_loader) >>> list(ranking)[:3] ['age', 'fev1', 'conditions=J45.909']
- get_extra_state()[source]#
Fitted trees as raw bytes in uint8 tensors, plus the feature layout.
Only tensors, strings and numbers, so checkpoints load with
torch.load(weights_only=True).
- set_extra_state(state)[source]#
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- add_module(name, module)#
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)#
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()#
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)#
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type:
Iterator[Tensor]
- children()#
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- Return type:
Iterator[Module]
- compile(*args, **kwargs)#
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()#
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)#
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- property device: device#
Gets the device of the model.
- Returns:
The device on which the model is located.
- Return type:
torch.device
- double()#
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()#
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr()#
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- float()#
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- get_buffer(target)#
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_loss_function()#
Gets the default loss function using self.mode.
- The default loss functions are:
binary: F.binary_cross_entropy_with_logits
multiclass: F.cross_entropy
multilabel: F.binary_cross_entropy_with_logits
regression: F.mse_loss
timeseries_binary: F.binary_cross_entropy_with_logits per time step, averaged over the labeled steps
timeseries_regression: F.mse_loss per time step, averaged over the labeled steps
The timeseries losses take per-step logits of shape (batch, steps, 1) and the batched
(value, mask)label, each of shape (batch, steps), produced by an output processor whoseprocess()returns(value, mask)per sample with mask 0 for steps without a label. Values at masked steps are ignored and may be NaN.For binary and multilabel labels, a weight set with
set_pos_weight()is passed aspos_weight.- Returns:
The default loss function.
- Return type:
Callable
- get_output_size()#
Gets the default output size using the label tokenizer and self.mode.
If the mode is “binary”, the output size is 1. If the mode is “multiclass” or “multilabel”, the output size is the number of classes or labels.
- Returns:
The output size of the model.
- Return type:
- get_parameter(target)#
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)#
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()#
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)#
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)#
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- property mode: str | None#
one of
VALID_MODES, orNoneif not applicable.- Type:
The label kind
- Return type:
Optional[str]
- modules(remove_duplicate=True)#
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type:
Iterator[Module]
- mtia(device=None)#
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)#
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()#
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)#
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)#
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)#
Return an iterator over module parameters.
The exact order of the returned parameters is unspecified, but repeated calls to the
parameters()method of an unchanged module return the parameters in the same order.This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type:
Iterator[Parameter]
- property pos_weight: torch.Tensor | None#
Weight of positive examples in the binary/multilabel loss, or None.
- Return type:
Optional[Tensor]
- prepare_y_prob(logits)#
Prepares the predicted probabilities for model evaluation.
This function converts the predicted logits to predicted probabilities depending on the mode. The default formats are:
- binary: a tensor of shape (batch_size, 1) with values in [0, 1],
which is obtained with torch.sigmoid()
- multiclass: a tensor of shape (batch_size, num_classes) with
values in [0, 1] and sum to 1, which is obtained with torch.softmax()
- multilabel: a tensor of shape (batch_size, num_labels) with values
in [0, 1], which is obtained with torch.sigmoid()
regression: a tensor of shape (batch_size, 1) with raw logits
- timeseries_binary: a tensor of shape (batch_size, steps, 1)
with values in [0, 1] per time step, from torch.sigmoid()
- timeseries_regression: a tensor of shape (batch_size, steps, 1)
with raw logits per time step
- Parameters:
logits (torch.Tensor) – The predicted logit tensor.
- Returns:
The predicted probability tensor.
- Return type:
torch.Tensor
- register_backward_hook(hook)#
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)#
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type:
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)#
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)#
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)#
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)#
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)#
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)#
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)#
Alias for
add_module().- Return type:
- register_parameter(name, param)#
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)#
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)#
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)#
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_pos_weight(pos_weight, dataset=None)#
Weights positive examples in the default loss, for rare outcomes.
Applies to binary and multilabel labels, through
get_loss_function()(pos_weightofF.binary_cross_entropy_with_logits). Models that compute their own loss (e.g. the drug-recommendation models) are not affected. Weighting changes the scale of the predicted probabilities, so check calibration when you use it.- Parameters:
pos_weight (
UnionType[float,Sequence[float],Tensor,str,None]) – A number (binary), one number per label (multilabel),"balanced"for negatives / positives indataset, or None to remove the weight.dataset (
Optional[Iterable[dict]]) – The training samples, required for"balanced". Pass the training split, not the full dataset, so validation and test labels do not set the weight.
- Raises:
ValueError – If the label is not binary or multilabel, or
"balanced"is given without a dataset.
Examples
>>> model.set_pos_weight(4.0) >>> model.set_pos_weight("balanced", train_dataset)
- Return type:
- set_submodule(target, module, strict=False)#
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)#
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)#
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)#
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)#
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)#
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)#
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)#
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.