tf.keras.layers.TorchModuleWrapper
Stay organized with collections
Save and categorize content based on your preferences.
Torch module wrapper layer.
Inherits From: Layer
, Operation
tf.keras.layers.TorchModuleWrapper(
module, name=None, **kwargs
)
TorchModuleWrapper
is a wrapper class that can turn any
torch.nn.Module
into a Keras layer, in particular by making its
parameters trackable by Keras.
Args |
module
|
torch.nn.Module instance. If it's a LazyModule
instance, then its parameters must be initialized before
passing the instance to TorchModuleWrapper (e.g. by calling
it once).
|
name
|
The name of the layer (string).
|
Example:
Here's an example of how the TorchModuleWrapper
can be used with vanilla
PyTorch modules.
import torch.nn as nn
import torch.nn.functional as F
import keras
from keras.src.layers import TorchModuleWrapper
class Classifier(keras.Model):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Wrap `torch.nn.Module`s with `TorchModuleWrapper`
# if they contain parameters
self.conv1 = TorchModuleWrapper(
nn.Conv2d(in_channels=1, out_channels=32, kernel_size=(3, 3))
)
self.conv2 = TorchModuleWrapper(
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3))
)
self.pool = nn.MaxPool2d(kernel_size=(2, 2))
self.flatten = nn.Flatten()
self.dropout = nn.Dropout(p=0.5)
self.fc = TorchModuleWrapper(nn.Linear(1600, 10))
def call(self, inputs):
x = F.relu(self.conv1(inputs))
x = self.pool(x)
x = F.relu(self.conv2(x))
x = self.pool(x)
x = self.flatten(x)
x = self.dropout(x)
x = self.fc(x)
return F.softmax(x, dim=1)
model = Classifier()
model.build((1, 28, 28))
print("Output shape:", model(torch.ones(1, 1, 28, 28).to("cuda")).shape)
model.compile(
loss="sparse_categorical_crossentropy",
optimizer="adam",
metrics=["accuracy"]
)
model.fit(train_loader, epochs=5)
Attributes |
input
|
Retrieves the input tensor(s) of a symbolic operation.
Only returns the tensor(s) corresponding to the first time
the operation was called.
|
output
|
Retrieves the output tensor(s) of a layer.
Only returns the tensor(s) corresponding to the first time
the operation was called.
|
Methods
from_config
View source
@classmethod
from_config(
config
)
Creates a layer from its config.
This method is the reverse of get_config
,
capable of instantiating the same layer from the config
dictionary. It does not handle layer connectivity
(handled by Network), nor weights (handled by set_weights
).
Args |
config
|
A Python dictionary, typically the
output of get_config.
|
Returns |
A layer instance.
|
parameters
View source
parameters(
recurse=True
)
symbolic_call
View source
symbolic_call(
*args, **kwargs
)
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Some content is licensed under the numpy license.
Last updated 2024-06-07 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-06-07 UTC."],[],[],null,["# tf.keras.layers.TorchModuleWrapper\n\n\u003cbr /\u003e\n\n|------------------------------------------------------------------------------------------------------------------|\n| [View source on GitHub](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/utils/torch_utils.py#L11-L150) |\n\nTorch module wrapper layer.\n\nInherits From: [`Layer`](../../../tf/keras/Layer), [`Operation`](../../../tf/keras/Operation) \n\n tf.keras.layers.TorchModuleWrapper(\n module, name=None, **kwargs\n )\n\n`TorchModuleWrapper` is a wrapper class that can turn any\n`torch.nn.Module` into a Keras layer, in particular by making its\nparameters trackable by Keras.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `module` | `torch.nn.Module` instance. If it's a `LazyModule` instance, then its parameters must be initialized before passing the instance to `TorchModuleWrapper` (e.g. by calling it once). |\n| `name` | The name of the layer (string). |\n\n\u003cbr /\u003e\n\n#### Example:\n\nHere's an example of how the `TorchModuleWrapper` can be used with vanilla\nPyTorch modules. \n\n import torch.nn as nn\n import torch.nn.functional as F\n\n import keras\n from keras.src.layers import TorchModuleWrapper\n\n class Classifier(keras.Model):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n # Wrap `torch.nn.Module`s with `TorchModuleWrapper`\n # if they contain parameters\n self.conv1 = TorchModuleWrapper(\n nn.Conv2d(in_channels=1, out_channels=32, kernel_size=(3, 3))\n )\n self.conv2 = TorchModuleWrapper(\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3))\n )\n self.pool = nn.MaxPool2d(kernel_size=(2, 2))\n self.flatten = nn.Flatten()\n self.dropout = nn.Dropout(p=0.5)\n self.fc = TorchModuleWrapper(nn.Linear(1600, 10))\n\n def call(self, inputs):\n x = F.relu(self.conv1(inputs))\n x = self.pool(x)\n x = F.relu(self.conv2(x))\n x = self.pool(x)\n x = self.flatten(x)\n x = self.dropout(x)\n x = self.fc(x)\n return F.softmax(x, dim=1)\n\n\n model = Classifier()\n model.build((1, 28, 28))\n print(\"Output shape:\", model(torch.ones(1, 1, 28, 28).to(\"cuda\")).shape)\n\n model.compile(\n loss=\"sparse_categorical_crossentropy\",\n optimizer=\"adam\",\n metrics=[\"accuracy\"]\n )\n model.fit(train_loader, epochs=5)\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Attributes ---------- ||\n|----------|------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `input` | Retrieves the input tensor(s) of a symbolic operation. \u003cbr /\u003e Only returns the tensor(s) corresponding to the *first time* the operation was called. |\n| `output` | Retrieves the output tensor(s) of a layer. \u003cbr /\u003e Only returns the tensor(s) corresponding to the *first time* the operation was called. |\n\n\u003cbr /\u003e\n\nMethods\n-------\n\n### `from_config`\n\n[View source](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/utils/torch_utils.py#L143-L150) \n\n @classmethod\n from_config(\n config\n )\n\nCreates a layer from its config.\n\nThis method is the reverse of `get_config`,\ncapable of instantiating the same layer from the config\ndictionary. It does not handle layer connectivity\n(handled by Network), nor weights (handled by `set_weights`).\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ||\n|----------|----------------------------------------------------------|\n| `config` | A Python dictionary, typically the output of get_config. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ||\n|---|---|\n| A layer instance. ||\n\n\u003cbr /\u003e\n\n### `parameters`\n\n[View source](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/utils/torch_utils.py#L97-L98) \n\n parameters(\n recurse=True\n )\n\n### `symbolic_call`\n\n[View source](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/ops/operation.py#L58-L70) \n\n symbolic_call(\n *args, **kwargs\n )"]]