konfai.network package#
Submodules#
konfai.network.blocks module#
Reusable network blocks and tensor graph helpers for KonfAI models.
- class konfai.network.blocks.NormMode(*values)[source]#
Bases:
EnumEnumeration of normalization layers supported by KonfAI blocks.
- NONE = (0,)#
- BATCH = 1#
- INSTANCE = 2#
- GROUP = 3#
- LAYER = 4#
- SYNCBATCH = 5#
- INSTANCE_AFFINE = 6#
- konfai.network.blocks.get_norm(norm_mode, channels, dim)[source]#
Instantiate the normalization layer matching the requested mode.
- class konfai.network.blocks.UpsampleMode(*values)[source]#
Bases:
Enum- CONV_TRANSPOSE = (0,)#
- UPSAMPLE = (1,)#
- class konfai.network.blocks.DownsampleMode(*values)[source]#
Bases:
Enum- MAXPOOL = (0,)#
- AVGPOOL = (1,)#
- CONV_STRIDE = 2#
- konfai.network.blocks.get_torch_module(name_fonction, dim=None)[source]#
Return a dimensional PyTorch module class such as
Conv2dorConv3d.- Return type:
- class konfai.network.blocks.BlockConfig(kernel_size=3, stride=1, padding=1, bias=True, activation='ReLU', norm_mode='NONE')[source]#
Bases:
objectConfiguration object describing one convolutional block stage.
- class konfai.network.blocks.ConvBlock(in_channels, out_channels, block_configs, dim, alias=[[], [], []])[source]#
Bases:
ModuleArgsDictSequential convolution, normalization, and activation block.
- class konfai.network.blocks.ResBlock(in_channels, out_channels, block_configs, dim, alias=[[], [], [], [], []])[source]#
Bases:
ModuleArgsDictResidual block with optional projection on the skip path.
- class konfai.network.blocks.ResidualBlockD(in_channels, out_channels, dim, kernel_size=3, stride=1, conv_bias=True, negative_slope=0.01, norm_mode='INSTANCE_AFFINE')[source]#
Bases:
ModuleArgsDictnnU-Net ResNet-D basic residual block, reproduced as a routed KonfAI graph.
Module-for-module and in forward-execution order equal to
dynamic_network_architectures.building_blocks.residual.BasicBlockD(the block the nnU-NetResidualEncoderUNetstacks). It reproduces the ResNet-D structure of He et al., Bag of Tricks for Image Classification with CNNs (CVPR 2019):Skip path first (matching
BasicBlockD.forward, which evaluatesself.skip(x)before the main path): when the block is strided, the residual is downsampled with anAvgPoolof kernel = stride (never a strided conv); when the channel count changes, it is then projected with a1x1conv whosebiasis alwaysFalse– independent ofconv_bias– followed by a norm. When neither applies the skip is the identity (no extra module, the residual falls back to the block input branch).Main path on branch
0:Conv(stride) -> Norm -> LeakyReLU -> Conv(stride 1) -> Norm(the second conv carries no activation, exactly asBasicBlockD).The two paths are summed and a final
LeakyReLUis applied.
Executing the skip modules before the main-path convs is what makes the block transparent to the execution-order weight bridge (
konfai.utils.pretrained): its weighted leaves fire in the same order asBasicBlockD(skip conv/norm, then conv1, then conv2).
- class konfai.network.blocks.ResNetBasicBlock(in_channels, out_channels, dim, stride=1, conv_bias=False, downsample=None, norm_mode='BATCH')[source]#
Bases:
ModuleArgsDicttorchvision ResNet
BasicBlockreproduced as a routed KonfAI graph (the ResNet-18/34 block).Module-for-module and in forward-execution order equal to
torchvision.models.resnet.BasicBlock(the block theresnet18/resnet34encoders ofsegmentation_models_pytorchstack). It reproduces the post-activation residual block of He et al., Deep Residual Learning (CVPR 2016):Main path first (matching
BasicBlock.forward, which computes the residual branch before it evaluatesself.downsample(x)): on branch1Conv(stride) -> Norm -> ReLU -> Conv(stride 1) -> Norm(the second conv carries no activation), keeping the block input untouched on branch0.Projection skip on branch
2, evaluated after the main path (exactly asBasicBlockcallsself.downsample(x)only afterbn2): a1x1Conv(stride) -> Norm. It is built when the block is strided or changes channel count; otherwise the residual is the identity (block input).The two paths are summed onto branch
0and a finalReLUis applied.
Evaluating the main-path convs before the downsample projection is what makes the block transparent to the execution-order weight bridge (
konfai.utils.pretrained): its weighted leaves fire in the same order asBasicBlock(conv1, bn1, conv2, bn2, downsample.0, downsample.1).conv_biasdefaults toFalse(torchvision/timm ResNets never bias their convs) and the norm isBatchNorm(running stats, so a checkpoint’s BN buffers travel through the bridge and theeval()forward matches).
- class konfai.network.blocks.ResidualStage(dim, in_channels, out_channels, n_blocks, stride=1, kernel_size=3, conv_bias=True, negative_slope=0.01, norm_mode='INSTANCE_AFFINE')[source]#
Bases:
ModuleArgsDictOne encoder resolution stage: a stack of
n_blocksResidualBlockDas a single node.A generic, reusable building block for residual encoders (e.g. nnU-Net’s
ResidualEncoder): the first block carriesstrideand thein_channels -> out_channelschange (nnU-Net strided-conv downsampling), and the remainingn_blocks - 1blocks are stride 1 atout_channels. The blocks are wired sequentially (each on branch0), so the whole stage is a drop-in single node with one input and one output whose weighted leaves fire in the same order as the equivalent flat stack – it stays transparent to the execution-order weight bridge (konfai.utils.pretrained).
- class konfai.network.blocks.DecoderStage(dim, in_channels, skip_channels, n_conv, kernel_size=3, conv_bias=True, negative_slope=0.01, upsample_stride=2, norm_mode='INSTANCE_AFFINE')[source]#
Bases:
ModuleArgsDictOne U-Net decoder resolution stage as a single two-input node: upsample, concat skip, conv block.
A generic, reusable building block for U-Net decoders (nnU-Net’s
UNetDecodershares it between the plain and residual encoders). It is a two-input node –in_branch: [coarser, skip]– that runsConvTranspose(in_channels -> skip_channels, kernel = stride = upsample_stride)on the coarser input, concatenates the encoderskip(transpose output first, then skip), then aConvBlockofn_convconvs mapping2 * skip_channels -> skip_channels– each Conv -> InstanceNorm(affine) -> LeakyReLU with same-padding. It yields one output.upsample_stridesets both the transpose kernel and stride so anisotropic plans (per-axis lists) upsample exactly the axes their encoder downsampled.
- class konfai.network.blocks.ResNetStage(dim, in_channels, out_channels, n_blocks, stride=1, conv_bias=False, norm_mode='BATCH')[source]#
Bases:
ModuleArgsDictOne torchvision ResNet encoder stage: a stack of
n_blocksResNetBasicBlockas a single node.A generic, reusable building block for the ResNet-18/34 encoders that
segmentation_models_pytorchstacks under its U-Net / UNet++ decoders (each is torchvision’sResNetlayer1..layer4). The first block carries the stagestrideand thein_channels -> out_channelschange – its1x1projectiondownsampleskip is built automatically when the stride or the channel count changes – and the remainingn_blocks - 1blocks are stride 1 atout_channelswith identity skips. The blocks run sequentially on branch0, so the whole stage is a drop-in single node with one input and one output whose weighted leaves fire in the same order as the equivalent flatBasicBlockstack: it stays transparent to the execution-order weight bridge (konfai.utils.pretrained).conv_biasdefaults toFalseand the norm toBatchNorm– the torchvision/timm ResNet convention.
- class konfai.network.blocks.UNetPlusPlusNode(dim, up_channels, skip_channels, out_channels, n_conv=2, kernel_size=3, conv_bias=False, norm_mode='BATCH')[source]#
Bases:
ModuleArgsDictOne UNet++ dense-decoder node as a single multi-input node: upsample, dense concat, then Conv-Norm-ReLU.
A generic, reusable building block for the nested (dense) UNet++ decoder of
segmentation_models_pytorch(UnetPlusPlusDecoder). It is a multi-input node –in_branch: [coarser, skip_0, skip_1, ...]– that reproduces one grid nodex_{d}_{l}:Upsample(scale_factor=2, mode='nearest')on the shallower-column predecessor (branch0);a
Concatof the upsampled feature FIRST, then every same-resolution dense skip and the matching encoder skip (smp order), when any skip is provided;a
ConvBlockofn_convConv -> BatchNorm -> ReLUblocks (smp’sConv2dReLU) mapping the concatenated widthup_channels + sum(skip_channels)toout_channels.
skip_channelsis the list of per-skip channel widths inin_branchorder: its length wires the concat (n_skip + 1inputs) and its sum fixes the conv’s input width, so the node self-describes the dense fusion. An emptyskip_channels(the final full-resolutionx_0_depthnode) drops the concat and convolves the upsampled feature alone. The weighted leaves fire inConvBlockorder, so the node stays transparent to the execution-order weight bridge (konfai.utils.pretrained).
- konfai.network.blocks.downsample(in_channels, out_channels, downsample_mode, dim)[source]#
Return the downsampling module matching the requested strategy.
- Return type:
- konfai.network.blocks.upsample(in_channels, out_channels, upsample_mode, dim, kernel_size=2, stride=2)[source]#
Return the upsampling module matching the requested strategy.
- class konfai.network.blocks.Unsqueeze(dim=0)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Permute(dims)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Add[source]#
Bases:
Module- forward(*tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Multiply[source]#
Bases:
Module- forward(*tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.ClipNormalize[source]#
Bases:
ModuleClip to a stored intensity range, then standardize:
(clamp(x, min, max) - mean) / std.The four scalars are buffers restored from the checkpoint, not config values, so a per-checkpoint input normalization (e.g. a CT window baked into a trained model) travels with its weights. It has no learnable parameters. Used as a declarative model’s first node so that normalization stays part of the model rather than a separate preprocessing step.
- forward(x)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Concat[source]#
Bases:
Module- forward(*tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Print[source]#
Bases:
ModuleDebug block: print the tensor shape and pass it through unchanged.
- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Write(path='./Data.mha')[source]#
Bases:
ModuleDebug block: write the first channel of the first sample to disk as a volume.
The destination path is explicit (no silent hardcoded location) and each call warns, since writing to disk inside a forward pass is a development-only side effect.
- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Exit[source]#
Bases:
ModuleDebug block: stop the forward pass by raising, to halt at a chosen point.
- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Detach[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Negative[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.GetShape[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.ArgMax(dim)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Select(slices)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.NormalNoise(dim=None)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Const(shape, std)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Subset(slices)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.View(size)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.LatentDistribution(shape, latent_dim)[source]#
Bases:
ModuleArgsDict- class LatentDistributionLinear(shape, latent_dim)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class LatentDistributionDecoder(shape, latent_dim)[source]#
Bases:
Module- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class LatentDistributionZ[source]#
Bases:
Module- forward(mu, log_std)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.Attention(f_g, f_l, f_int, dim)[source]#
Bases:
ModuleArgsDict
- class konfai.network.blocks.PositionalEmbedding(num_tokens, embedding_dim)[source]#
Bases:
ModuleAdd a learnable positional embedding to a token sequence.
The input is a token sequence shaped
[B, num_tokens, embedding_dim](batch, sequence, feature), the layout produced by a patch embedding. A single learnable parameter of shape[1, num_tokens, embedding_dim]is broadcast over the batch and added, giving every token position a trainable offset. This is thelearnablepositional encoding of the Vision Transformer; the parameter is registered directly on the module so it is a self-contained, single-purpose building block.- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- class konfai.network.blocks.MultiHeadSelfAttention(hidden_size, num_heads, qkv_bias=False)[source]#
Bases:
ModuleMulti-head self-attention over a token sequence (the Transformer encoder attention).
Mirrors the self-attention of MONAI’s
SABlock/ViT in its default configuration: a single packedqkvlinear projects the[B, num_tokens, hidden_size]sequence into queries, keys and values, scaled dot-product attention is computed per head with scalehead_dim ** -0.5, and anout_projlinear mixes the concatenated heads back tohidden_size.qkv_biastoggles the bias of the packed projection (the ViT default isFalse);out_projalways carries a bias. Both projections are childLinearleaves, so the module is transparent to execution-order weight transfer.- forward(tensor)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
konfai.network.network module#
Model graph composition, routing, and optimization helpers for KonfAI.
- class konfai.network.network.NetState(*values)[source]#
Bases:
EnumExecution state of a network inside KonfAI workflows.
- TRAIN = (0,)#
- PREDICTION = 1#
- class konfai.network.network.PatchIndexed(patch, index)[source]#
Bases:
objectTrack progress while consuming the patches produced by a
ModelPatch.
- class konfai.network.network.OptimizerLoader(name='AdamW')[source]#
Bases:
objectConfiguration-aware factory for PyTorch optimizers.
- class konfai.network.network.LRSchedulersLoader(nb_step=0)[source]#
Bases:
objectConfiguration-aware factory for learning-rate schedulers.
- class konfai.network.network.LossSchedulersLoader(nb_step=0)[source]#
Bases:
objectFactory for scalar schedulers attached to losses and metrics.
- konfai.network.network.build_configured_criterions(criterions_loader, config_key_prefix, configure_attr=None)[source]#
Instantiate criteria from a KonfAI config subtree.
- Parameters:
criterions_loader (
dict[str,Any]) – Mapping from criterion classpath to criterion attributes.config_key_prefix (
str) – Config subtree preceding.criterions_loader.<classpath>.configure_attr (
Callable[[str,Any,Any],None] |None) – Optional callback used to enrich the attribute object with runtime metadata before the criterion is instantiated. It receives the criterion classpath, the attribute object, and the imported module.
- Returns:
Instantiated criteria mapped to their configuration attributes.
- Return type:
- class konfai.network.network.CriterionsAttr(schedulers={'default|Constant': <konfai.network.network.LossSchedulersLoader object>}, is_loss=True, group=0, start=0, stop=None, accumulation=False)[source]#
Bases:
objectMetadata describing how a criterion is applied within the model graph.
- class konfai.network.network.CriterionsLoader(criterions_loader={'default|torch:nn:CrossEntropyLoss|Dice|NCC': <konfai.network.network.CriterionsAttr object>})[source]#
Bases:
objectInstantiate the criteria attached to one output/target pair.
- class konfai.network.network.TargetCriterionsLoader(targets_criterions={'Labels': <konfai.network.network.CriterionsLoader object>})[source]#
Bases:
objectResolve criteria for all targets associated with one model output.
- class konfai.network.network.Measure(model_classname, outputs_criterions_loader)[source]#
Bases:
objectCollect, validate, and aggregate losses or metrics across model outputs.
- class konfai.network.network.ModuleArgsDict[source]#
-
Named module graph container supporting KonfAI branch routing metadata.
- class ModuleArgs(in_branch, out_branch, pretrained, alias, requires_grad, training)[source]#
Bases:
object
- add_module(name, module, in_branch=[0], out_branch=[0], pretrained=True, alias=[], requires_grad=None, training=None)[source]#
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- forward(*input)[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.- Return type:
- named_parameters(pretrained=False, recurse=False)[source]#
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(pretrained=False)[source]#
Return an iterator over module parameters.
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)
- class konfai.network.network.OutputsGroup(measure)[source]#
Bases:
listContainer describing one model output and its source modules.
- class konfai.network.network.Network(in_channels=1, optimizer=None, schedulers=None, outputs_criterions=None, patch=None, nb_batch_per_step=1, init_type='normal', init_gain=0.02, dim=3)[source]#
Bases:
ModuleArgsDict,ABCBase class for KonfAI networks participating in a routed model graph.
- outputsGroup: list[OutputsGroup]#
- state_dict(*args, **kwargs) dict[str, object][source]#
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']
- load_state_dict(state_dict)[source]#
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[str,Tensor]) – 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.
- apply(fn)[source]#
Apply
fnto each non-KonfAI child module and finally toself.This overrides
torch.nn.Module.applyso the recursive traversal can skip nestedNetworkinstances and keep KonfAI’s graph semantics intact.- Return type:
- forward(batch_sample, output_layers=[])[source]#
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- static to(module, device, _counter=None)[source]#
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
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 (
int) – 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:
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)
- class konfai.network.network.MinimalModel(model, optimizer=<konfai.network.network.OptimizerLoader object>, schedulers={'default|StepLR': <konfai.network.network.LRSchedulersLoader object>}, outputs_criterions={'default': <konfai.network.network.TargetCriterionsLoader object>}, patch=None, dim=3, nb_batch_per_step=1, init_type='normal', init_gain=0.02)[source]#
Bases:
NetworkSmall wrapper exposing a single network as a full KonfAI model graph.
The wrapped model arrives fully constructed — possibly carrying pretrained weights (a torchvision/MONAI/SMP class with
weights=...).loadtherefore never re-initialises:load(init=True)at training start appliesinit_funcover every descendant and would silently destroy those weights withinit_typenoise. Models built from scratch keep KonfAI’s init behaviour; checkpoint loading is unaffected.
Module contents#
Model graph primitives, blocks, and loaders used by KonfAI workflows.