Module fl_server_api.tests.test_inference¶
View Source
# SPDX-FileCopyrightText: 2024 Benedikt Franke <benedikt.franke@dlr.de>
# SPDX-FileCopyrightText: 2024 Florian Heinrich <florian.heinrich@dlr.de>
#
# SPDX-License-Identifier: Apache-2.0
import base64
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
import json
import io
import pickle
import torch
import torch.nn
from torchvision.transforms.functional import to_pil_image
from uuid import uuid4
from fl_server_core.tests import BASE_URL, Dummy
from fl_server_core.utils.torch_serialization import from_torch_module, from_torch_tensor
class mxb(torch.nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
return 2*x + 5
class InferenceTests(TestCase):
def setUp(self):
self.user = Dummy.create_user_and_authenticate(self.client)
def test_inference_success(self):
inp = from_torch_tensor(torch.zeros(3, 3))
training = Dummy.create_training(actor=self.user)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
def test_inference_json(self):
inp = torch.zeros(3, 3).tolist()
training = Dummy.create_training(actor=self.user)
response = self.client.post(
f"{BASE_URL}/inference/",
json.dumps({"model_id": str(training.model.id), "model_input": inp}),
content_type="application/json"
)
self.assertEqual(response.status_code, 200)
response_json = response.json()
self.assertEqual({}, response_json["uncertainty"])
inference = response_json["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
def test_inference_json_binary_output(self):
inp = torch.zeros(3, 3).tolist()
training = Dummy.create_training(actor=self.user)
response = self.client.post(
f"{BASE_URL}/inference/",
json.dumps({"model_id": str(training.model.id), "model_input": inp, "return_format": "binary"}),
content_type="application/json"
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
def test_inference_with_unknown_content_type(self):
with self.assertLogs("root", level="INFO") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": "not important", "model_input": "not important"},
"application/octet-stream"
)
self.assertEqual(cm.output, [
"ERROR:fl.server:Unknown Content-Type 'application/octet-stream'",
"WARNING:django.request:Unsupported Media Type: /api/inference/",
])
self.assertEqual(response.status_code, 415)
def test_model_not_exist(self):
inp = from_torch_tensor(torch.zeros(3, 3))
Dummy.create_model()
unused_id = uuid4()
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="WARNING") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": unused_id, "model_input": input_file},
# 'multipart/form-data; boundary=...' is set automatically (default)
)
self.assertEqual(cm.output, [
"WARNING:django.request:Bad Request: /api/inference/",
])
self.assertEqual(response.status_code, 400)
response_json = response.json()
self.assertIsNotNone(response_json)
self.assertEqual(f"Model {unused_id} not found.", response_json["detail"])
def test_model_weights_corrupted(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_broken_model()
Dummy.create_training(model=model, actor=self.user)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="ERROR"):
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": model.id, "model_input": input_file},
)
self.assertEqual(response.status_code, 500)
response_json = response.json()
self.assertIsNotNone(response_json)
self.assertEqual("Error loading torch object", response_json["detail"])
def test_inference_result_torchscript_model(self):
torch_model = torch.jit.script(mxb()) # torchscript model
self._inference_result(torch_model)
def test_inference_result_normal_model(self):
torch_model = mxb() # normal model
self._inference_result(torch_model)
def _inference_result(self, torch_model: torch.nn.Module):
model = Dummy.create_model(owner=self.user, weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
inputs = torch.as_tensor([
[0.9102, 1.0899, 2.0304, -0.8448],
[2.2616, -0.2974, 0.3805, -0.9301],
[0.4804, 0.2510, 0.2702, -0.1529],
])
input_file = SimpleUploadedFile(
"input.pt",
from_torch_tensor(inputs),
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([2, 0, 0]) == inference_tensor))
def test_inference_input_shape_positive(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_model(input_shape=[None, 3])
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
def test_inference_input_shape_negative(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_model(input_shape=[None, 5])
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="WARNING") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(cm.output, [
"WARNING:django.request:Bad Request: /api/inference/",
])
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()[0], "Input shape does not match model input shape.")
def test_inference_input_pil_image(self):
img = to_pil_image(torch.zeros(1, 5, 5))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="jpeg")
img_byte_arr = img_byte_arr.getvalue()
torch.manual_seed(42)
torch_model = torch.jit.script(torch.nn.Sequential(
torch.nn.Conv2d(1, 2, 3),
torch.nn.Flatten(),
torch.nn.Linear(3*3, 2)
))
model = Dummy.create_model(input_shape=[None, 5, 5], weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
img_byte_arr,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([0, 0]) == inference_tensor))
def test_inference_input_pil_image_base64(self):
img = to_pil_image(torch.zeros(1, 5, 5))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="jpeg")
img_byte_arr = img_byte_arr.getvalue()
inp = base64.b64encode(img_byte_arr)
torch.manual_seed(42)
torch_model = torch.jit.script(torch.nn.Sequential(
torch.nn.Conv2d(1, 2, 3),
torch.nn.Flatten(),
torch.nn.Linear(3*3, 2)
))
model = Dummy.create_model(input_shape=[None, 5, 5], weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([0, 0]) == inference_tensor))
Variables¶
Classes¶
InferenceTests¶
Similar to TransactionTestCase, but use transaction.atomic()
to achieve
test isolation.
In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).
On database backends with no transaction support, TestCase behaves as TransactionTestCase.
View Source
class InferenceTests(TestCase):
def setUp(self):
self.user = Dummy.create_user_and_authenticate(self.client)
def test_inference_success(self):
inp = from_torch_tensor(torch.zeros(3, 3))
training = Dummy.create_training(actor=self.user)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
def test_inference_json(self):
inp = torch.zeros(3, 3).tolist()
training = Dummy.create_training(actor=self.user)
response = self.client.post(
f"{BASE_URL}/inference/",
json.dumps({"model_id": str(training.model.id), "model_input": inp}),
content_type="application/json"
)
self.assertEqual(response.status_code, 200)
response_json = response.json()
self.assertEqual({}, response_json["uncertainty"])
inference = response_json["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
def test_inference_json_binary_output(self):
inp = torch.zeros(3, 3).tolist()
training = Dummy.create_training(actor=self.user)
response = self.client.post(
f"{BASE_URL}/inference/",
json.dumps({"model_id": str(training.model.id), "model_input": inp, "return_format": "binary"}),
content_type="application/json"
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
def test_inference_with_unknown_content_type(self):
with self.assertLogs("root", level="INFO") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": "not important", "model_input": "not important"},
"application/octet-stream"
)
self.assertEqual(cm.output, [
"ERROR:fl.server:Unknown Content-Type 'application/octet-stream'",
"WARNING:django.request:Unsupported Media Type: /api/inference/",
])
self.assertEqual(response.status_code, 415)
def test_model_not_exist(self):
inp = from_torch_tensor(torch.zeros(3, 3))
Dummy.create_model()
unused_id = uuid4()
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="WARNING") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": unused_id, "model_input": input_file},
# 'multipart/form-data; boundary=...' is set automatically (default)
)
self.assertEqual(cm.output, [
"WARNING:django.request:Bad Request: /api/inference/",
])
self.assertEqual(response.status_code, 400)
response_json = response.json()
self.assertIsNotNone(response_json)
self.assertEqual(f"Model {unused_id} not found.", response_json["detail"])
def test_model_weights_corrupted(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_broken_model()
Dummy.create_training(model=model, actor=self.user)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="ERROR"):
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": model.id, "model_input": input_file},
)
self.assertEqual(response.status_code, 500)
response_json = response.json()
self.assertIsNotNone(response_json)
self.assertEqual("Error loading torch object", response_json["detail"])
def test_inference_result_torchscript_model(self):
torch_model = torch.jit.script(mxb()) # torchscript model
self._inference_result(torch_model)
def test_inference_result_normal_model(self):
torch_model = mxb() # normal model
self._inference_result(torch_model)
def _inference_result(self, torch_model: torch.nn.Module):
model = Dummy.create_model(owner=self.user, weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
inputs = torch.as_tensor([
[0.9102, 1.0899, 2.0304, -0.8448],
[2.2616, -0.2974, 0.3805, -0.9301],
[0.4804, 0.2510, 0.2702, -0.1529],
])
input_file = SimpleUploadedFile(
"input.pt",
from_torch_tensor(inputs),
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([2, 0, 0]) == inference_tensor))
def test_inference_input_shape_positive(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_model(input_shape=[None, 3])
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
def test_inference_input_shape_negative(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_model(input_shape=[None, 5])
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="WARNING") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(cm.output, [
"WARNING:django.request:Bad Request: /api/inference/",
])
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()[0], "Input shape does not match model input shape.")
def test_inference_input_pil_image(self):
img = to_pil_image(torch.zeros(1, 5, 5))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="jpeg")
img_byte_arr = img_byte_arr.getvalue()
torch.manual_seed(42)
torch_model = torch.jit.script(torch.nn.Sequential(
torch.nn.Conv2d(1, 2, 3),
torch.nn.Flatten(),
torch.nn.Linear(3*3, 2)
))
model = Dummy.create_model(input_shape=[None, 5, 5], weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
img_byte_arr,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([0, 0]) == inference_tensor))
def test_inference_input_pil_image_base64(self):
img = to_pil_image(torch.zeros(1, 5, 5))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="jpeg")
img_byte_arr = img_byte_arr.getvalue()
inp = base64.b64encode(img_byte_arr)
torch.manual_seed(42)
torch_model = torch.jit.script(torch.nn.Sequential(
torch.nn.Conv2d(1, 2, 3),
torch.nn.Flatten(),
torch.nn.Linear(3*3, 2)
))
model = Dummy.create_model(input_shape=[None, 5, 5], weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([0, 0]) == inference_tensor))
Ancestors (in MRO)¶
- django.test.testcases.TestCase
- django.test.testcases.TransactionTestCase
- django.test.testcases.SimpleTestCase
- unittest.case.TestCase
Class variables¶
Static methods¶
addClassCleanup¶
Same as addCleanup, except the cleanup items are called even if
setUpClass fails (unlike tearDownClass).
View Source
captureOnCommitCallbacks¶
Context manager to capture transaction.on_commit() callbacks.
View Source
@classmethod
@contextmanager
def captureOnCommitCallbacks(cls, *, using=DEFAULT_DB_ALIAS, execute=False):
"""Context manager to capture transaction.on_commit() callbacks."""
callbacks = []
start_count = len(connections[using].run_on_commit)
try:
yield callbacks
finally:
while True:
callback_count = len(connections[using].run_on_commit)
for _, callback in connections[using].run_on_commit[start_count:]:
callbacks.append(callback)
if execute:
callback()
if callback_count == len(connections[using].run_on_commit):
break
start_count = callback_count
doClassCleanups¶
Execute all class cleanup functions. Normally called for you after
tearDownClass.
View Source
@classmethod
def doClassCleanups(cls):
"""Execute all class cleanup functions. Normally called for you after
tearDownClass."""
cls.tearDown_exceptions = []
while cls._class_cleanups:
function, args, kwargs = cls._class_cleanups.pop()
try:
function(*args, **kwargs)
except Exception:
cls.tearDown_exceptions.append(sys.exc_info())
setUpClass¶
Hook method for setting up class fixture before running tests in the class.
View Source
@classmethod
def setUpClass(cls):
super().setUpClass()
if not cls._databases_support_transactions():
return
# Disable the durability check to allow testing durable atomic blocks
# in a transaction for performance reasons.
transaction.Atomic._ensure_durability = False
try:
cls.cls_atomics = cls._enter_atomics()
if cls.fixtures:
for db_name in cls._databases_names(include_mirrors=False):
try:
call_command(
"loaddata",
*cls.fixtures,
**{"verbosity": 0, "database": db_name},
)
except Exception:
cls._rollback_atomics(cls.cls_atomics)
raise
pre_attrs = cls.__dict__.copy()
try:
cls.setUpTestData()
except Exception:
cls._rollback_atomics(cls.cls_atomics)
raise
for name, value in cls.__dict__.items():
if value is not pre_attrs.get(name):
setattr(cls, name, TestData(name, value))
except Exception:
transaction.Atomic._ensure_durability = True
raise
setUpTestData¶
Load initial data for the TestCase.
tearDownClass¶
Hook method for deconstructing the class fixture after running all tests in the class.
View Source
Methods¶
addCleanup¶
Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
View Source
def addCleanup(self, function, /, *args, **kwargs):
"""Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown)."""
self._cleanups.append((function, args, kwargs))
addTypeEqualityFunc¶
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
typeobj | None | The data type to call this function on when both values are of the same type in assertEqual(). |
None |
function | None | The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. |
None |
View Source
def addTypeEqualityFunc(self, typeobj, function):
"""Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
"""
self._type_equality_funcs[typeobj] = function
assertAlmostEqual¶
Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.
Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically compare almost equal.
View Source
def assertAlmostEqual(self, first, second, places=None, msg=None,
delta=None):
"""Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
difference between the two objects is more than the given
delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically
compare almost equal.
"""
if first == second:
# shortcut
return
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
diff = abs(first - second)
if delta is not None:
if diff <= delta:
return
standardMsg = '%s != %s within %s delta (%s difference)' % (
safe_repr(first),
safe_repr(second),
safe_repr(delta),
safe_repr(diff))
else:
if places is None:
places = 7
if round(diff, places) == 0:
return
standardMsg = '%s != %s within %r places (%s difference)' % (
safe_repr(first),
safe_repr(second),
places,
safe_repr(diff))
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
assertAlmostEquals¶
View Source
assertContains¶
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
text
occurs count
times in the content of the response.
If count
is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
View Source
def assertContains(
self, response, text, count=None, status_code=200, msg_prefix="", html=False
):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
text_repr, real_count, msg_prefix = self._assert_contains(
response, text, status_code, msg_prefix, html
)
if count is not None:
self.assertEqual(
real_count,
count,
msg_prefix
+ "Found %d instances of %s in response (expected %d)"
% (real_count, text_repr, count),
)
else:
self.assertTrue(
real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr
)
assertCountEqual¶
Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal.
View Source
def assertCountEqual(self, first, second, msg=None):
"""Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
"""
first_seq, second_seq = list(first), list(second)
try:
first = collections.Counter(first_seq)
second = collections.Counter(second_seq)
except TypeError:
# Handle case with unhashable elements
differences = _count_diff_all_purpose(first_seq, second_seq)
else:
if first == second:
return
differences = _count_diff_hashable(first_seq, second_seq)
if differences:
standardMsg = 'Element counts were not equal:\n'
lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
diffMsg = '\n'.join(lines)
standardMsg = self._truncateMessage(standardMsg, diffMsg)
msg = self._formatMessage(msg, standardMsg)
self.fail(msg)
assertDictContainsSubset¶
Checks whether dictionary is a superset of subset.
View Source
def assertDictContainsSubset(self, subset, dictionary, msg=None):
"""Checks whether dictionary is a superset of subset."""
warnings.warn('assertDictContainsSubset is deprecated',
DeprecationWarning,
stacklevel=2)
missing = []
mismatched = []
for key, value in subset.items():
if key not in dictionary:
missing.append(key)
elif value != dictionary[key]:
mismatched.append('%s, expected: %s, actual: %s' %
(safe_repr(key), safe_repr(value),
safe_repr(dictionary[key])))
if not (missing or mismatched):
return
standardMsg = ''
if missing:
standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
missing)
if mismatched:
if standardMsg:
standardMsg += '; '
standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
self.fail(self._formatMessage(msg, standardMsg))
assertDictEqual¶
View Source
def assertDictEqual(self, d1, d2, msg=None):
self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
if d1 != d2:
standardMsg = '%s != %s' % _common_shorten_repr(d1, d2)
diff = ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
assertEqual¶
Fail if the two objects are unequal as determined by the '=='
operator.
View Source
assertEquals¶
View Source
assertFalse¶
Check that the expression is false.
View Source
assertFieldOutput¶
def assertFieldOutput(
self,
fieldclass,
valid,
invalid,
field_args=None,
field_kwargs=None,
empty_value=''
)
Assert that a form field behaves correctly with various inputs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fieldclass | None | the class of the field to be tested. | None |
valid | None | a dictionary mapping valid inputs to their expected cleaned values. |
None |
invalid | None | a dictionary mapping invalid inputs to one or more raised error messages. |
None |
field_args | None | the args passed to instantiate the field | None |
field_kwargs | None | the kwargs passed to instantiate the field | None |
empty_value | None | the expected clean output for inputs in empty_values | None |
View Source
def assertFieldOutput(
self,
fieldclass,
valid,
invalid,
field_args=None,
field_kwargs=None,
empty_value="",
):
"""
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **{**field_kwargs, "required": False})
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [required.error_messages["required"]]
for e in required.empty_values:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({"min_length": 2, "max_length": 20})
self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass)
assertFormError¶
Assert that a form used to render the response has a specific field
error.
View Source
def assertFormError(self, response, form, field, errors, msg_prefix=""):
"""
Assert that a form used to render the response has a specific field
error.
"""
if msg_prefix:
msg_prefix += ": "
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail(
msg_prefix + "Response did not use any contexts to render the response"
)
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i, context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.assertTrue(
err in field_errors,
msg_prefix + "The field '%s' on form '%s' in"
" context %d does not contain the error '%s'"
" (actual errors: %s)"
% (field, form, i, err, repr(field_errors)),
)
elif field in context[form].fields:
self.fail(
msg_prefix
+ (
"The field '%s' on form '%s' in context %d contains no "
"errors"
)
% (field, form, i)
)
else:
self.fail(
msg_prefix
+ (
"The form '%s' in context %d does not contain the "
"field '%s'"
)
% (form, i, field)
)
else:
non_field_errors = context[form].non_field_errors()
self.assertTrue(
err in non_field_errors,
msg_prefix + "The form '%s' in context %d does not"
" contain the non-field error '%s'"
" (actual errors: %s)"
% (form, i, err, non_field_errors or "none"),
)
if not found_form:
self.fail(
msg_prefix + "The form '%s' was not used to render the response" % form
)
assertFormsetError¶
Assert that a formset used to render the response has a specific error.
For field errors, specify the form_index
and the field
.
For non-field errors, specify the form_index
and the field
as
None.
For non-form errors, specify form_index
as None and the field
as None.
View Source
def assertFormsetError(
self, response, formset, form_index, field, errors, msg_prefix=""
):
"""
Assert that a formset used to render the response has a specific error.
For field errors, specify the ``form_index`` and the ``field``.
For non-field errors, specify the ``form_index`` and the ``field`` as
None.
For non-form errors, specify ``form_index`` as None and the ``field``
as None.
"""
# Add punctuation to msg_prefix
if msg_prefix:
msg_prefix += ": "
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail(
msg_prefix + "Response did not use any contexts to "
"render the response"
)
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_formset = False
for i, context in enumerate(contexts):
if formset not in context or not hasattr(context[formset], "forms"):
continue
found_formset = True
for err in errors:
if field is not None:
if field in context[formset].forms[form_index].errors:
field_errors = context[formset].forms[form_index].errors[field]
self.assertTrue(
err in field_errors,
msg_prefix + "The field '%s' on formset '%s', "
"form %d in context %d does not contain the "
"error '%s' (actual errors: %s)"
% (field, formset, form_index, i, err, repr(field_errors)),
)
elif field in context[formset].forms[form_index].fields:
self.fail(
msg_prefix
+ (
"The field '%s' on formset '%s', form %d in context "
"%d contains no errors"
)
% (field, formset, form_index, i)
)
else:
self.fail(
msg_prefix
+ (
"The formset '%s', form %d in context %d does not "
"contain the field '%s'"
)
% (formset, form_index, i, field)
)
elif form_index is not None:
non_field_errors = (
context[formset].forms[form_index].non_field_errors()
)
self.assertFalse(
not non_field_errors,
msg_prefix + "The formset '%s', form %d in context %d "
"does not contain any non-field errors."
% (formset, form_index, i),
)
self.assertTrue(
err in non_field_errors,
msg_prefix + "The formset '%s', form %d in context %d "
"does not contain the non-field error '%s' (actual errors: %s)"
% (formset, form_index, i, err, repr(non_field_errors)),
)
else:
non_form_errors = context[formset].non_form_errors()
self.assertFalse(
not non_form_errors,
msg_prefix + "The formset '%s' in context %d does not "
"contain any non-form errors." % (formset, i),
)
self.assertTrue(
err in non_form_errors,
msg_prefix + "The formset '%s' in context %d does not "
"contain the non-form error '%s' (actual errors: %s)"
% (formset, i, err, repr(non_form_errors)),
)
if not found_formset:
self.fail(
msg_prefix
+ "The formset '%s' was not used to render the response" % formset
)
assertGreater¶
Just like self.assertTrue(a > b), but with a nicer default message.
View Source
assertGreaterEqual¶
Just like self.assertTrue(a >= b), but with a nicer default message.
View Source
assertHTMLEqual¶
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not significant. The arguments must be valid HTML.
View Source
def assertHTMLEqual(self, html1, html2, msg=None):
"""
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
"""
dom1 = assert_and_parse_html(
self, html1, msg, "First argument is not valid HTML:"
)
dom2 = assert_and_parse_html(
self, html2, msg, "Second argument is not valid HTML:"
)
if dom1 != dom2:
standardMsg = "%s != %s" % (safe_repr(dom1, True), safe_repr(dom2, True))
diff = "\n" + "\n".join(
difflib.ndiff(
str(dom1).splitlines(),
str(dom2).splitlines(),
)
)
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
assertHTMLNotEqual¶
Assert that two HTML snippets are not semantically equivalent.
View Source
def assertHTMLNotEqual(self, html1, html2, msg=None):
"""Assert that two HTML snippets are not semantically equivalent."""
dom1 = assert_and_parse_html(
self, html1, msg, "First argument is not valid HTML:"
)
dom2 = assert_and_parse_html(
self, html2, msg, "Second argument is not valid HTML:"
)
if dom1 == dom2:
standardMsg = "%s == %s" % (safe_repr(dom1, True), safe_repr(dom2, True))
self.fail(self._formatMessage(msg, standardMsg))
assertIn¶
Just like self.assertTrue(a in b), but with a nicer default message.
View Source
assertInHTML¶
View Source
def assertInHTML(self, needle, haystack, count=None, msg_prefix=""):
needle = assert_and_parse_html(
self, needle, None, "First argument is not valid HTML:"
)
haystack = assert_and_parse_html(
self, haystack, None, "Second argument is not valid HTML:"
)
real_count = haystack.count(needle)
if count is not None:
self.assertEqual(
real_count,
count,
msg_prefix
+ "Found %d instances of '%s' in response (expected %d)"
% (real_count, needle, count),
)
else:
self.assertTrue(
real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle
)
assertIs¶
Just like self.assertTrue(a is b), but with a nicer default message.
View Source
assertIsInstance¶
Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.
View Source
assertIsNone¶
Same as self.assertTrue(obj is None), with a nicer default message.
View Source
assertIsNot¶
Just like self.assertTrue(a is not b), but with a nicer default message.
View Source
assertIsNotNone¶
Included for symmetry with assertIsNone.
View Source
assertJSONEqual¶
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library.
View Source
def assertJSONEqual(self, raw, expected_data, msg=None):
"""
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
"""
try:
data = json.loads(raw)
except json.JSONDecodeError:
self.fail("First argument is not valid JSON: %r" % raw)
if isinstance(expected_data, str):
try:
expected_data = json.loads(expected_data)
except ValueError:
self.fail("Second argument is not valid JSON: %r" % expected_data)
self.assertEqual(data, expected_data, msg=msg)
assertJSONNotEqual¶
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library.
View Source
def assertJSONNotEqual(self, raw, expected_data, msg=None):
"""
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
"""
try:
data = json.loads(raw)
except json.JSONDecodeError:
self.fail("First argument is not valid JSON: %r" % raw)
if isinstance(expected_data, str):
try:
expected_data = json.loads(expected_data)
except json.JSONDecodeError:
self.fail("Second argument is not valid JSON: %r" % expected_data)
self.assertNotEqual(data, expected_data, msg=msg)
assertLess¶
Just like self.assertTrue(a < b), but with a nicer default message.
View Source
assertLessEqual¶
Just like self.assertTrue(a <= b), but with a nicer default message.
View Source
assertListEqual¶
A list-specific equality assertion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
list1 | None | The first list to compare. | None |
list2 | None | The second list to compare. | None |
msg | None | Optional message to use on failure instead of a list of differences. |
None |
View Source
def assertListEqual(self, list1, list2, msg=None):
"""A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
"""
self.assertSequenceEqual(list1, list2, msg, seq_type=list)
assertLogs¶
Fail unless a log message of level level or higher is emitted
on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: output
and records
.
At the end of the context manager, the output
attribute will
be a list of the matching formatted log messages and the
records
attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
View Source
def assertLogs(self, logger=None, level=None):
"""Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: `output` and `records`.
At the end of the context manager, the `output` attribute will
be a list of the matching formatted log messages and the
`records` attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
"""
# Lazy import to avoid importing logging if it is not needed.
from ._log import _AssertLogsContext
return _AssertLogsContext(self, logger, level, no_logs=False)
assertMultiLineEqual¶
Assert that two multi-line strings are equal.
View Source
def assertMultiLineEqual(self, first, second, msg=None):
"""Assert that two multi-line strings are equal."""
self.assertIsInstance(first, str, 'First argument is not a string')
self.assertIsInstance(second, str, 'Second argument is not a string')
if first != second:
# don't use difflib if the strings are too long
if (len(first) > self._diffThreshold or
len(second) > self._diffThreshold):
self._baseAssertEqual(first, second, msg)
firstlines = first.splitlines(keepends=True)
secondlines = second.splitlines(keepends=True)
if len(firstlines) == 1 and first.strip('\r\n') == first:
firstlines = [first + '\n']
secondlines = [second + '\n']
standardMsg = '%s != %s' % _common_shorten_repr(first, second)
diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
assertNoLogs¶
Fail unless no log messages of level level or higher are emitted
on logger_name or its children.
This method must be used as a context manager.
View Source
def assertNoLogs(self, logger=None, level=None):
""" Fail unless no log messages of level *level* or higher are emitted
on *logger_name* or its children.
This method must be used as a context manager.
"""
from ._log import _AssertLogsContext
return _AssertLogsContext(self, logger, level, no_logs=True)
assertNotAlmostEqual¶
Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
View Source
def assertNotAlmostEqual(self, first, second, places=None, msg=None,
delta=None):
"""Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
"""
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
diff = abs(first - second)
if delta is not None:
if not (first == second) and diff > delta:
return
standardMsg = '%s == %s within %s delta (%s difference)' % (
safe_repr(first),
safe_repr(second),
safe_repr(delta),
safe_repr(diff))
else:
if places is None:
places = 7
if not (first == second) and round(diff, places) != 0:
return
standardMsg = '%s == %s within %r places' % (safe_repr(first),
safe_repr(second),
places)
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
assertNotAlmostEquals¶
View Source
assertNotContains¶
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
text
doesn't occur in the content of the response.
View Source
def assertNotContains(
self, response, text, status_code=200, msg_prefix="", html=False
):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occur in the content of the response.
"""
text_repr, real_count, msg_prefix = self._assert_contains(
response, text, status_code, msg_prefix, html
)
self.assertEqual(
real_count, 0, msg_prefix + "Response should not contain %s" % text_repr
)
assertNotEqual¶
Fail if the two objects are equal as determined by the '!='
operator.
View Source
assertNotEquals¶
View Source
assertNotIn¶
Just like self.assertTrue(a not in b), but with a nicer default message.
View Source
assertNotIsInstance¶
Included for symmetry with assertIsInstance.
View Source
assertNotRegex¶
Fail the test if the text matches the regular expression.
View Source
def assertNotRegex(self, text, unexpected_regex, msg=None):
"""Fail the test if the text matches the regular expression."""
if isinstance(unexpected_regex, (str, bytes)):
unexpected_regex = re.compile(unexpected_regex)
match = unexpected_regex.search(text)
if match:
standardMsg = 'Regex matched: %r matches %r in %r' % (
text[match.start() : match.end()],
unexpected_regex.pattern,
text)
# _formatMessage ensures the longMessage option is respected
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
assertNotRegexpMatches¶
View Source
assertNumQueries¶
View Source
assertQuerysetEqual¶
View Source
def assertQuerysetEqual(self, qs, values, transform=None, ordered=True, msg=None):
values = list(values)
# RemovedInDjango41Warning.
if transform is None:
if (
values
and isinstance(values[0], str)
and qs
and not isinstance(qs[0], str)
):
# Transform qs using repr() if the first element of values is a
# string and the first element of qs is not (which would be the
# case if qs is a flattened values_list).
warnings.warn(
"In Django 4.1, repr() will not be called automatically "
"on a queryset when compared to string values. Set an "
"explicit 'transform' to silence this warning.",
category=RemovedInDjango41Warning,
stacklevel=2,
)
transform = repr
items = qs
if transform is not None:
items = map(transform, items)
if not ordered:
return self.assertDictEqual(Counter(items), Counter(values), msg=msg)
# For example qs.iterator() could be passed as qs, but it does not
# have 'ordered' attribute.
if len(values) > 1 and hasattr(qs, "ordered") and not qs.ordered:
raise ValueError(
"Trying to compare non-ordered queryset against more than one "
"ordered value."
)
return self.assertEqual(list(items), values, msg=msg)
assertRaises¶
Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
If called with the callable and arguments omitted, will return a context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises is used as a context object.
The context manager keeps a reference to the exception as the 'exception' attribute. This allows you to inspect the exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
View Source
def assertRaises(self, expected_exception, *args, **kwargs):
"""Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
"""
context = _AssertRaisesContext(expected_exception, self)
try:
return context.handle('assertRaises', args, kwargs)
finally:
# bpo-23890: manually break a reference cycle
context = None
assertRaisesMessage¶
Assert that expected_message is found in the message of a raised
exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expected_exception | None | Exception class expected to be raised. | None |
expected_message | None | expected error message string value. | None |
args | None | Function to be called and extra positional args. | None |
kwargs | None | Extra kwargs. | None |
View Source
def assertRaisesMessage(
self, expected_exception, expected_message, *args, **kwargs
):
"""
Assert that expected_message is found in the message of a raised
exception.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
"""
return self._assertFooMessage(
self.assertRaises,
"exception",
expected_exception,
expected_message,
*args,
**kwargs,
)
assertRaisesRegex¶
Asserts that the message in a raised exception matches a regex.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expected_exception | None | Exception class expected to be raised. | None |
expected_regex | None | Regex (re.Pattern object or string) expected to be found in error message. |
None |
args | None | Function to be called and extra positional args. | None |
kwargs | None | Extra kwargs. | None |
msg | None | Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. |
None |
View Source
def assertRaisesRegex(self, expected_exception, expected_regex,
*args, **kwargs):
"""Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
"""
context = _AssertRaisesContext(expected_exception, self, expected_regex)
return context.handle('assertRaisesRegex', args, kwargs)
assertRaisesRegexp¶
View Source
assertRedirects¶
def assertRedirects(
self,
response,
expected_url,
status_code=302,
target_status_code=200,
msg_prefix='',
fetch_redirect_response=True
)
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded.
Won't work for external links since it uses the test client to do a request (use fetch_redirect_response=False to check such links without fetching them).
View Source
def assertRedirects(
self,
response,
expected_url,
status_code=302,
target_status_code=200,
msg_prefix="",
fetch_redirect_response=True,
):
"""
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded.
Won't work for external links since it uses the test client to do a
request (use fetch_redirect_response=False to check such links without
fetching them).
"""
if msg_prefix:
msg_prefix += ": "
if hasattr(response, "redirect_chain"):
# The request was a followed redirect
self.assertTrue(
response.redirect_chain,
msg_prefix
+ (
"Response didn't redirect as expected: Response code was %d "
"(expected %d)"
)
% (response.status_code, status_code),
)
self.assertEqual(
response.redirect_chain[0][1],
status_code,
msg_prefix
+ (
"Initial response didn't redirect as expected: Response code was "
"%d (expected %d)"
)
% (response.redirect_chain[0][1], status_code),
)
url, status_code = response.redirect_chain[-1]
self.assertEqual(
response.status_code,
target_status_code,
msg_prefix
+ (
"Response didn't redirect as expected: Final Response code was %d "
"(expected %d)"
)
% (response.status_code, target_status_code),
)
else:
# Not a followed redirect
self.assertEqual(
response.status_code,
status_code,
msg_prefix
+ (
"Response didn't redirect as expected: Response code was %d "
"(expected %d)"
)
% (response.status_code, status_code),
)
url = response.url
scheme, netloc, path, query, fragment = urlsplit(url)
# Prepend the request path to handle relative path redirects.
if not path.startswith("/"):
url = urljoin(response.request["PATH_INFO"], url)
path = urljoin(response.request["PATH_INFO"], path)
if fetch_redirect_response:
# netloc might be empty, or in cases where Django tests the
# HTTP scheme, the convention is for netloc to be 'testserver'.
# Trust both as "internal" URLs here.
domain, port = split_domain_port(netloc)
if domain and not validate_host(domain, settings.ALLOWED_HOSTS):
raise ValueError(
"The test client is unable to fetch remote URLs (got %s). "
"If the host is served by Django, add '%s' to ALLOWED_HOSTS. "
"Otherwise, use "
"assertRedirects(..., fetch_redirect_response=False)."
% (url, domain)
)
# Get the redirection page, using the same client that was used
# to obtain the original response.
extra = response.client.extra or {}
redirect_response = response.client.get(
path,
QueryDict(query),
secure=(scheme == "https"),
**extra,
)
self.assertEqual(
redirect_response.status_code,
target_status_code,
msg_prefix
+ (
"Couldn't retrieve redirection page '%s': response code was %d "
"(expected %d)"
)
% (path, redirect_response.status_code, target_status_code),
)
self.assertURLEqual(
url,
expected_url,
msg_prefix
+ "Response redirected to '%s', expected '%s'" % (url, expected_url),
)
assertRegex¶
Fail the test unless the text matches the regular expression.
View Source
def assertRegex(self, text, expected_regex, msg=None):
"""Fail the test unless the text matches the regular expression."""
if isinstance(expected_regex, (str, bytes)):
assert expected_regex, "expected_regex must not be empty."
expected_regex = re.compile(expected_regex)
if not expected_regex.search(text):
standardMsg = "Regex didn't match: %r not found in %r" % (
expected_regex.pattern, text)
# _formatMessage ensures the longMessage option is respected
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
assertRegexpMatches¶
View Source
assertSequenceEqual¶
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seq1 | None | The first sequence to compare. | None |
seq2 | None | The second sequence to compare. | None |
seq_type | None | The expected datatype of the sequences, or None if no datatype should be enforced. |
None |
msg | None | Optional message to use on failure instead of a list of differences. |
None |
View Source
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
"""An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
"""
if seq_type is not None:
seq_type_name = seq_type.__name__
if not isinstance(seq1, seq_type):
raise self.failureException('First sequence is not a %s: %s'
% (seq_type_name, safe_repr(seq1)))
if not isinstance(seq2, seq_type):
raise self.failureException('Second sequence is not a %s: %s'
% (seq_type_name, safe_repr(seq2)))
else:
seq_type_name = "sequence"
differing = None
try:
len1 = len(seq1)
except (TypeError, NotImplementedError):
differing = 'First %s has no length. Non-sequence?' % (
seq_type_name)
if differing is None:
try:
len2 = len(seq2)
except (TypeError, NotImplementedError):
differing = 'Second %s has no length. Non-sequence?' % (
seq_type_name)
if differing is None:
if seq1 == seq2:
return
differing = '%ss differ: %s != %s\n' % (
(seq_type_name.capitalize(),) +
_common_shorten_repr(seq1, seq2))
for i in range(min(len1, len2)):
try:
item1 = seq1[i]
except (TypeError, IndexError, NotImplementedError):
differing += ('\nUnable to index element %d of first %s\n' %
(i, seq_type_name))
break
try:
item2 = seq2[i]
except (TypeError, IndexError, NotImplementedError):
differing += ('\nUnable to index element %d of second %s\n' %
(i, seq_type_name))
break
if item1 != item2:
differing += ('\nFirst differing element %d:\n%s\n%s\n' %
((i,) + _common_shorten_repr(item1, item2)))
break
else:
if (len1 == len2 and seq_type is None and
type(seq1) != type(seq2)):
# The sequences are the same, but have differing types.
return
if len1 > len2:
differing += ('\nFirst %s contains %d additional '
'elements.\n' % (seq_type_name, len1 - len2))
try:
differing += ('First extra element %d:\n%s\n' %
(len2, safe_repr(seq1[len2])))
except (TypeError, IndexError, NotImplementedError):
differing += ('Unable to index element %d '
'of first %s\n' % (len2, seq_type_name))
elif len1 < len2:
differing += ('\nSecond %s contains %d additional '
'elements.\n' % (seq_type_name, len2 - len1))
try:
differing += ('First extra element %d:\n%s\n' %
(len1, safe_repr(seq2[len1])))
except (TypeError, IndexError, NotImplementedError):
differing += ('Unable to index element %d '
'of second %s\n' % (len1, seq_type_name))
standardMsg = differing
diffMsg = '\n' + '\n'.join(
difflib.ndiff(pprint.pformat(seq1).splitlines(),
pprint.pformat(seq2).splitlines()))
standardMsg = self._truncateMessage(standardMsg, diffMsg)
msg = self._formatMessage(msg, standardMsg)
self.fail(msg)
assertSetEqual¶
A set-specific equality assertion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
set1 | None | The first set to compare. | None |
set2 | None | The second set to compare. | None |
msg | None | Optional message to use on failure instead of a list of differences. |
None |
View Source
def assertSetEqual(self, set1, set2, msg=None):
"""A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).
"""
try:
difference1 = set1.difference(set2)
except TypeError as e:
self.fail('invalid type when attempting set difference: %s' % e)
except AttributeError as e:
self.fail('first argument does not support set difference: %s' % e)
try:
difference2 = set2.difference(set1)
except TypeError as e:
self.fail('invalid type when attempting set difference: %s' % e)
except AttributeError as e:
self.fail('second argument does not support set difference: %s' % e)
if not (difference1 or difference2):
return
lines = []
if difference1:
lines.append('Items in the first set but not the second:')
for item in difference1:
lines.append(repr(item))
if difference2:
lines.append('Items in the second set but not the first:')
for item in difference2:
lines.append(repr(item))
standardMsg = '\n'.join(lines)
self.fail(self._formatMessage(msg, standardMsg))
assertTemplateNotUsed¶
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
View Source
def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=""):
"""
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
"""
context_mgr_template, template_names, msg_prefix = self._assert_template_used(
response, template_name, msg_prefix
)
if context_mgr_template:
# Use assertTemplateNotUsed as context manager.
return _AssertTemplateNotUsedContext(self, context_mgr_template)
self.assertFalse(
template_name in template_names,
msg_prefix
+ "Template '%s' was used unexpectedly in rendering the response"
% template_name,
)
assertTemplateUsed¶
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
View Source
def assertTemplateUsed(
self, response=None, template_name=None, msg_prefix="", count=None
):
"""
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
"""
context_mgr_template, template_names, msg_prefix = self._assert_template_used(
response, template_name, msg_prefix
)
if context_mgr_template:
# Use assertTemplateUsed as context manager.
return _AssertTemplateUsedContext(self, context_mgr_template)
if not template_names:
self.fail(msg_prefix + "No templates used to render the response")
self.assertTrue(
template_name in template_names,
msg_prefix + "Template '%s' was not a template used to render"
" the response. Actual template(s) used: %s"
% (template_name, ", ".join(template_names)),
)
if count is not None:
self.assertEqual(
template_names.count(template_name),
count,
msg_prefix + "Template '%s' was expected to be rendered %d "
"time(s) but was actually rendered %d time(s)."
% (template_name, count, template_names.count(template_name)),
)
assertTrue¶
Check that the expression is true.
View Source
assertTupleEqual¶
A tuple-specific equality assertion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tuple1 | None | The first tuple to compare. | None |
tuple2 | None | The second tuple to compare. | None |
msg | None | Optional message to use on failure instead of a list of differences. |
None |
View Source
def assertTupleEqual(self, tuple1, tuple2, msg=None):
"""A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
"""
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
assertURLEqual¶
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name.
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but /path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
View Source
def assertURLEqual(self, url1, url2, msg_prefix=""):
"""
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name.
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
/path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
"""
def normalize(url):
"""Sort the URL's query string parameters."""
url = str(url) # Coerce reverse_lazy() URLs.
scheme, netloc, path, params, query, fragment = urlparse(url)
query_parts = sorted(parse_qsl(query))
return urlunparse(
(scheme, netloc, path, params, urlencode(query_parts), fragment)
)
self.assertEqual(
normalize(url1),
normalize(url2),
msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2),
)
assertWarns¶
Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.
If called with the callable and arguments omitted, will return a context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns is used as a context object.
The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
View Source
def assertWarns(self, expected_warning, *args, **kwargs):
"""Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and
keyword arguments. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
"""
context = _AssertWarnsContext(expected_warning, self)
return context.handle('assertWarns', args, kwargs)
assertWarnsMessage¶
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
View Source
assertWarnsRegex¶
Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expected_warning | None | Warning class expected to be triggered. | None |
expected_regex | None | Regex (re.Pattern object or string) expected to be found in error message. |
None |
args | None | Function to be called and extra positional args. | None |
kwargs | None | Extra kwargs. | None |
msg | None | Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. |
None |
View Source
def assertWarnsRegex(self, expected_warning, expected_regex,
*args, **kwargs):
"""Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
"""
context = _AssertWarnsContext(expected_warning, self, expected_regex)
return context.handle('assertWarnsRegex', args, kwargs)
assertXMLEqual¶
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML.
View Source
def assertXMLEqual(self, xml1, xml2, msg=None):
"""
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
"""
try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = "First or second argument is not valid XML\n%s" % e
self.fail(self._formatMessage(msg, standardMsg))
else:
if not result:
standardMsg = "%s != %s" % (
safe_repr(xml1, True),
safe_repr(xml2, True),
)
diff = "\n" + "\n".join(
difflib.ndiff(xml1.splitlines(), xml2.splitlines())
)
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
assertXMLNotEqual¶
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML.
View Source
def assertXMLNotEqual(self, xml1, xml2, msg=None):
"""
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
"""
try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = "First or second argument is not valid XML\n%s" % e
self.fail(self._formatMessage(msg, standardMsg))
else:
if result:
standardMsg = "%s == %s" % (
safe_repr(xml1, True),
safe_repr(xml2, True),
)
self.fail(self._formatMessage(msg, standardMsg))
assert_¶
View Source
countTestCases¶
debug¶
Perform the same as call(), without catching the exception.
View Source
defaultTestResult¶
doCleanups¶
Execute all cleanup functions. Normally called for you after
tearDown.
View Source
def doCleanups(self):
"""Execute all cleanup functions. Normally called for you after
tearDown."""
outcome = self._outcome or _Outcome()
while self._cleanups:
function, args, kwargs = self._cleanups.pop()
with outcome.testPartExecutor(self):
self._callCleanup(function, *args, **kwargs)
# return this for backwards compatibility
# even though we no longer use it internally
return outcome.success
fail¶
Fail immediately, with the given message.
View Source
failIf¶
View Source
failIfAlmostEqual¶
View Source
failIfEqual¶
View Source
failUnless¶
View Source
failUnlessAlmostEqual¶
View Source
failUnlessEqual¶
View Source
failUnlessRaises¶
View Source
id¶
modify_settings¶
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
View Source
run¶
View Source
def run(self, result=None):
if result is None:
result = self.defaultTestResult()
startTestRun = getattr(result, 'startTestRun', None)
stopTestRun = getattr(result, 'stopTestRun', None)
if startTestRun is not None:
startTestRun()
else:
stopTestRun = None
result.startTest(self)
try:
testMethod = getattr(self, self._testMethodName)
if (getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False)):
# If the class or method was skipped.
skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
or getattr(testMethod, '__unittest_skip_why__', ''))
self._addSkip(result, self, skip_why)
return result
expecting_failure = (
getattr(self, "__unittest_expecting_failure__", False) or
getattr(testMethod, "__unittest_expecting_failure__", False)
)
outcome = _Outcome(result)
try:
self._outcome = outcome
with outcome.testPartExecutor(self):
self._callSetUp()
if outcome.success:
outcome.expecting_failure = expecting_failure
with outcome.testPartExecutor(self, isTest=True):
self._callTestMethod(testMethod)
outcome.expecting_failure = False
with outcome.testPartExecutor(self):
self._callTearDown()
self.doCleanups()
for test, reason in outcome.skipped:
self._addSkip(result, test, reason)
self._feedErrorsToResult(result, outcome.errors)
if outcome.success:
if expecting_failure:
if outcome.expectedFailure:
self._addExpectedFailure(result, outcome.expectedFailure)
else:
self._addUnexpectedSuccess(result)
else:
result.addSuccess(self)
return result
finally:
# explicitly break reference cycles:
# outcome.errors -> frame -> outcome -> outcome.errors
# outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure
outcome.errors.clear()
outcome.expectedFailure = None
# clear the outcome, no more needed
self._outcome = None
finally:
result.stopTest(self)
if stopTestRun is not None:
stopTestRun()
setUp¶
Hook method for setting up the test fixture before exercising it.
settings¶
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
View Source
shortDescription¶
Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of the specified test method's docstring.
View Source
def shortDescription(self):
"""Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of
the specified test method's docstring.
"""
doc = self._testMethodDoc
return doc.strip().split("\n")[0].strip() if doc else None
skipTest¶
Skip this test.
subTest¶
Return a context manager that will return the enclosed block
of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.
View Source
@contextlib.contextmanager
def subTest(self, msg=_subtest_msg_sentinel, **params):
"""Return a context manager that will return the enclosed block
of code in a subtest identified by the optional message and
keyword parameters. A failure in the subtest marks the test
case as failed but resumes execution at the end of the enclosed
block, allowing further test code to be executed.
"""
if self._outcome is None or not self._outcome.result_supports_subtests:
yield
return
parent = self._subtest
if parent is None:
params_map = _OrderedChainMap(params)
else:
params_map = parent.params.new_child(params)
self._subtest = _SubTest(self, msg, params_map)
try:
with self._outcome.testPartExecutor(self._subtest, isTest=True):
yield
if not self._outcome.success:
result = self._outcome.result
if result is not None and result.failfast:
raise _ShouldStop
elif self._outcome.expectedFailure:
# If the test is expecting a failure, we really want to
# stop now and register the expected failure.
raise _ShouldStop
finally:
self._subtest = parent
tearDown¶
Hook method for deconstructing the test fixture after testing it.
View Source
test_inference_input_pil_image¶
View Source
def test_inference_input_pil_image(self):
img = to_pil_image(torch.zeros(1, 5, 5))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="jpeg")
img_byte_arr = img_byte_arr.getvalue()
torch.manual_seed(42)
torch_model = torch.jit.script(torch.nn.Sequential(
torch.nn.Conv2d(1, 2, 3),
torch.nn.Flatten(),
torch.nn.Linear(3*3, 2)
))
model = Dummy.create_model(input_shape=[None, 5, 5], weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
img_byte_arr,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([0, 0]) == inference_tensor))
test_inference_input_pil_image_base64¶
View Source
def test_inference_input_pil_image_base64(self):
img = to_pil_image(torch.zeros(1, 5, 5))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="jpeg")
img_byte_arr = img_byte_arr.getvalue()
inp = base64.b64encode(img_byte_arr)
torch.manual_seed(42)
torch_model = torch.jit.script(torch.nn.Sequential(
torch.nn.Conv2d(1, 2, 3),
torch.nn.Flatten(),
torch.nn.Linear(3*3, 2)
))
model = Dummy.create_model(input_shape=[None, 5, 5], weights=from_torch_module(torch_model))
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
inference_tensor = torch.as_tensor(inference)
self.assertTrue(torch.all(torch.tensor([0, 0]) == inference_tensor))
test_inference_input_shape_negative¶
View Source
def test_inference_input_shape_negative(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_model(input_shape=[None, 5])
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="WARNING") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(cm.output, [
"WARNING:django.request:Bad Request: /api/inference/",
])
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()[0], "Input shape does not match model input shape.")
test_inference_input_shape_positive¶
View Source
def test_inference_input_shape_positive(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_model(input_shape=[None, 3])
training = Dummy.create_training(actor=self.user, model=model)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
test_inference_json¶
View Source
def test_inference_json(self):
inp = torch.zeros(3, 3).tolist()
training = Dummy.create_training(actor=self.user)
response = self.client.post(
f"{BASE_URL}/inference/",
json.dumps({"model_id": str(training.model.id), "model_input": inp}),
content_type="application/json"
)
self.assertEqual(response.status_code, 200)
response_json = response.json()
self.assertEqual({}, response_json["uncertainty"])
inference = response_json["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
test_inference_json_binary_output¶
View Source
def test_inference_json_binary_output(self):
inp = torch.zeros(3, 3).tolist()
training = Dummy.create_training(actor=self.user)
response = self.client.post(
f"{BASE_URL}/inference/",
json.dumps({"model_id": str(training.model.id), "model_input": inp, "return_format": "binary"}),
content_type="application/json"
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
test_inference_result_normal_model¶
View Source
test_inference_result_torchscript_model¶
View Source
test_inference_success¶
View Source
def test_inference_success(self):
inp = from_torch_tensor(torch.zeros(3, 3))
training = Dummy.create_training(actor=self.user)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": str(training.model.id), "model_input": input_file}
)
self.assertEqual(response.status_code, 200)
results = pickle.loads(response.content)
self.assertEqual({}, results["uncertainty"])
inference = results["inference"]
self.assertIsNotNone(inference)
results = torch.as_tensor(inference)
self.assertTrue(torch.all(results <= 1))
self.assertTrue(torch.all(results >= 0))
test_inference_with_unknown_content_type¶
View Source
def test_inference_with_unknown_content_type(self):
with self.assertLogs("root", level="INFO") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": "not important", "model_input": "not important"},
"application/octet-stream"
)
self.assertEqual(cm.output, [
"ERROR:fl.server:Unknown Content-Type 'application/octet-stream'",
"WARNING:django.request:Unsupported Media Type: /api/inference/",
])
self.assertEqual(response.status_code, 415)
test_model_not_exist¶
View Source
def test_model_not_exist(self):
inp = from_torch_tensor(torch.zeros(3, 3))
Dummy.create_model()
unused_id = uuid4()
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="WARNING") as cm:
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": unused_id, "model_input": input_file},
# 'multipart/form-data; boundary=...' is set automatically (default)
)
self.assertEqual(cm.output, [
"WARNING:django.request:Bad Request: /api/inference/",
])
self.assertEqual(response.status_code, 400)
response_json = response.json()
self.assertIsNotNone(response_json)
self.assertEqual(f"Model {unused_id} not found.", response_json["detail"])
test_model_weights_corrupted¶
View Source
def test_model_weights_corrupted(self):
inp = from_torch_tensor(torch.zeros(3, 3))
model = Dummy.create_broken_model()
Dummy.create_training(model=model, actor=self.user)
input_file = SimpleUploadedFile(
"input.pt",
inp,
content_type="application/octet-stream"
)
with self.assertLogs("root", level="ERROR"):
response = self.client.post(
f"{BASE_URL}/inference/",
{"model_id": model.id, "model_input": input_file},
)
self.assertEqual(response.status_code, 500)
response_json = response.json()
self.assertIsNotNone(response_json)
self.assertEqual("Error loading torch object", response_json["detail"])
mxb¶
Base class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes::
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will have their
parameters converted too when you call :meth:to
, etc.
.. note::
As per the example above, an __init__()
call to the parent class
must be made before assignment on the child.
View Source
Ancestors (in MRO)¶
- torch.nn.modules.module.Module
Class variables¶
Methods¶
add_module¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name | str | name of the child module. The child module can be accessed from this module using the given name |
None |
module | Module | child module to be added to the module. | None |
View Source
def add_module(self, name: str, module: Optional["Module"]) -> None:
r"""Add a child module to the current module.
The module can be accessed as an attribute using the given name.
Args:
name (str): name of the child module. The child module can be
accessed from this module using the given name
module (Module): child module to be added to the module.
"""
if not isinstance(module, Module) and module is not None:
raise TypeError(f"{torch.typename(module)} is not a Module subclass")
elif not isinstance(name, str):
raise TypeError(
f"module name should be a string. Got {torch.typename(name)}"
)
elif hasattr(self, name) and name not in self._modules:
raise KeyError(f"attribute '{name}' already exists")
elif "." in name:
raise KeyError(f'module name can\'t contain ".", got: {name}')
elif name == "":
raise KeyError('module name can\'t be empty string ""')
for hook in _global_module_registration_hooks.values():
output = hook(self, name, module)
if output is not None:
module = output
self._modules[name] = module
apply¶
Apply fn
recursively to every submodule (as returned by .children()
) as well as self.
Typical use includes initializing the parameters of a model
(see also :ref:nn-init-doc
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn ( | None | class:Module -> None): function to be applied to each submodule |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def apply(self: T, fn: Callable[["Module"], None]) -> T:
r"""Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self.
Typical use includes initializing the parameters of a model
(see also :ref:`nn-init-doc`).
Args:
fn (:class:`Module` -> None): function to be applied to each submodule
Returns:
Module: self
Example::
>>> @torch.no_grad()
>>> def init_weights(m):
>>> print(m)
>>> if type(m) == 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)
)
"""
for module in self.children():
module.apply(fn)
fn(self)
return self
bfloat16¶
Casts all floating point parameters and buffers to bfloat16
datatype.
.. note:: This method modifies the module in-place.
Returns:
Type | Description |
---|---|
Module | self |
View Source
buffers¶
Return an iterator over module buffers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recurse | bool | if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. |
None |
Yields:
Type | Description |
---|---|
torch.Tensor | module buffer |
View Source
def buffers(self, recurse: bool = True) -> Iterator[Tensor]:
r"""Return an iterator over module buffers.
Args:
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)
"""
for _, buf in self.named_buffers(recurse=recurse):
yield buf
children¶
Return an iterator over immediate children modules.
Yields:
Type | Description |
---|---|
Module | a child module |
View Source
compile¶
Compile this Module's forward using :func:torch.compile
.
This Module's __call__
method is compiled and all arguments are passed as-is
to :func:torch.compile
.
See :func:torch.compile
for details on the arguments for this function.
View Source
def compile(self, *args, **kwargs):
"""
Compile this Module's forward using :func:`torch.compile`.
This Module's `__call__` method is compiled and all arguments are passed as-is
to :func:`torch.compile`.
See :func:`torch.compile` for details on the arguments for this function.
"""
self._compiled_call_impl = torch.compile(self._call_impl, *args, **kwargs)
cpu¶
Move all model parameters and buffers to the CPU.
.. note:: This method modifies the module in-place.
Returns:
Type | Description |
---|---|
Module | self |
View Source
cuda¶
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 optimizer if the module will live on GPU while being optimized.
.. note:: This method modifies the module in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device | int | if specified, all parameters will be copied to that device |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def cuda(self: T, device: Optional[Union[int, device]] = None) -> T:
r"""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 optimizer if the module will
live on GPU while being optimized.
.. note::
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
copied to that device
Returns:
Module: self
"""
return self._apply(lambda t: t.cuda(device))
double¶
Casts all floating point parameters and buffers to double
datatype.
.. note:: This method modifies the module in-place.
Returns:
Type | Description |
---|---|
Module | self |
View Source
eval¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:Dropout
, :class:BatchNorm
,
etc.
This is equivalent with :meth:self.train(False) <torch.nn.Module.train>
.
See :ref:locally-disable-grad-doc
for a comparison between
.eval()
and several similar mechanisms that may be confused with it.
Returns:
Type | Description |
---|---|
Module | self |
View Source
def eval(self: T) -> T:
r"""Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
etc.
This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.
See :ref:`locally-disable-grad-doc` for a comparison between
`.eval()` and several similar mechanisms that may be confused with it.
Returns:
Module: self
"""
return self.train(False)
extra_repr¶
Set 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.
View Source
float¶
Casts all floating point parameters and buffers to float
datatype.
.. note:: This method modifies the module in-place.
Returns:
Type | Description |
---|---|
Module | self |
View Source
forward¶
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 :class:Module
instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
get_buffer¶
Return the buffer given by target
if it exists, otherwise throw an error.
See the docstring for get_submodule
for a more detailed
explanation of this method's functionality as well as how to
correctly specify target
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target | None | The fully-qualified string name of the buffer to look for. (See get_submodule for how to specify afully-qualified string.) |
None |
Returns:
Type | Description |
---|---|
torch.Tensor | The buffer referenced by target |
Raises:
Type | Description |
---|---|
AttributeError | If the target string references an invalid path or resolves to something that is not a buffer |
View Source
def get_buffer(self, target: str) -> "Tensor":
"""Return the buffer given by ``target`` if it exists, otherwise throw an error.
See the docstring for ``get_submodule`` for a more detailed
explanation of this method's functionality as well as how to
correctly specify ``target``.
Args:
target: The fully-qualified string name of the buffer
to look for. (See ``get_submodule`` for how to specify a
fully-qualified string.)
Returns:
torch.Tensor: The buffer referenced by ``target``
Raises:
AttributeError: If the target string references an invalid
path or resolves to something that is not a
buffer
"""
module_path, _, buffer_name = target.rpartition(".")
mod: torch.nn.Module = self.get_submodule(module_path)
if not hasattr(mod, buffer_name):
raise AttributeError(
mod._get_name() + " has no attribute `" + buffer_name + "`"
)
buffer: torch.Tensor = getattr(mod, buffer_name)
if buffer_name not in mod._buffers:
raise AttributeError("`" + buffer_name + "` is not a buffer")
return buffer
get_extra_state¶
Return any extra state to include in the module's state_dict.
Implement this and a corresponding :func:set_extra_state
for your module
if you need to store extra state. This function is called when building the
module's state_dict()
.
Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
Returns:
Type | Description |
---|---|
object | Any extra state to store in the module's state_dict |
View Source
def get_extra_state(self) -> Any:
"""Return any extra state to include in the module's state_dict.
Implement this and a corresponding :func:`set_extra_state` for your module
if you need to store extra state. This function is called when building the
module's `state_dict()`.
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
Returns:
object: Any extra state to store in the module's state_dict
"""
raise RuntimeError(
"Reached a code path in Module.get_extra_state() that should never be called. "
"Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
"to report this bug."
)
get_parameter¶
Return the parameter given by target
if it exists, otherwise throw an error.
See the docstring for get_submodule
for a more detailed
explanation of this method's functionality as well as how to
correctly specify target
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target | None | The fully-qualified string name of the Parameter to look for. (See get_submodule for how to specify afully-qualified string.) |
None |
Returns:
Type | Description |
---|---|
torch.nn.Parameter | The Parameter referenced by target |
Raises:
Type | Description |
---|---|
AttributeError | If the target string references an invalid path or resolves to something that is not an nn.Parameter |
View Source
def get_parameter(self, target: str) -> "Parameter":
"""Return the parameter given by ``target`` if it exists, otherwise throw an error.
See the docstring for ``get_submodule`` for a more detailed
explanation of this method's functionality as well as how to
correctly specify ``target``.
Args:
target: The fully-qualified string name of the Parameter
to look for. (See ``get_submodule`` for how to specify a
fully-qualified string.)
Returns:
torch.nn.Parameter: The Parameter referenced by ``target``
Raises:
AttributeError: If the target string references an invalid
path or resolves to something that is not an
``nn.Parameter``
"""
module_path, _, param_name = target.rpartition(".")
mod: torch.nn.Module = self.get_submodule(module_path)
if not hasattr(mod, param_name):
raise AttributeError(
mod._get_name() + " has no attribute `" + param_name + "`"
)
param: torch.nn.Parameter = getattr(mod, param_name)
if not isinstance(param, torch.nn.Parameter):
raise AttributeError("`" + param_name + "` is not an " "nn.Parameter")
return param
get_submodule¶
Return the submodule given by target
if it exists, otherwise throw an error.
For example, let's say you have an nn.Module
A
that
looks like this:
.. code-block:: text
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.Module
A
. A
has a nested
submodule net_b
, which itself has two submodules net_c
and linear
. net_c
then has a submodule conv
.)
To check whether or not we have the linear
submodule, we
would call get_submodule("net_b.linear")
. To check whether
we have the conv
submodule, we would call
get_submodule("net_b.net_c.conv")
.
The runtime of get_submodule
is bounded by the degree
of module nesting in target
. A query against
named_modules
achieves 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_submodule
should always be
used.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target | None | The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.) |
None |
Returns:
Type | Description |
---|---|
torch.nn.Module | The submodule referenced by target |
Raises:
Type | Description |
---|---|
AttributeError | If the target string references an invalid path or resolves to something that is not an nn.Module |
View Source
def get_submodule(self, target: str) -> "Module":
"""Return the submodule given by ``target`` if it exists, otherwise throw an error.
For example, let's say you have an ``nn.Module`` ``A`` that
looks like this:
.. code-block:: text
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.Module`` ``A``. ``A`` has a nested
submodule ``net_b``, which itself has two submodules ``net_c``
and ``linear``. ``net_c`` then has a submodule ``conv``.)
To check whether or not we have the ``linear`` submodule, we
would call ``get_submodule("net_b.linear")``. To check whether
we have the ``conv`` submodule, we would call
``get_submodule("net_b.net_c.conv")``.
The runtime of ``get_submodule`` is bounded by the degree
of module nesting in ``target``. A query against
``named_modules`` achieves 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_submodule`` should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by ``target``
Raises:
AttributeError: If the target string references an invalid
path or resolves to something that is not an
``nn.Module``
"""
if target == "":
return self
atoms: List[str] = target.split(".")
mod: torch.nn.Module = self
for item in atoms:
if not hasattr(mod, item):
raise AttributeError(
mod._get_name() + " has no " "attribute `" + item + "`"
)
mod = getattr(mod, item)
if not isinstance(mod, torch.nn.Module):
raise AttributeError("`" + item + "` is not " "an nn.Module")
return mod
half¶
Casts all floating point parameters and buffers to half
datatype.
.. note:: This method modifies the module in-place.
Returns:
Type | Description |
---|---|
Module | self |
View Source
ipu¶
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 optimizer if the module will live on IPU while being optimized.
.. note:: This method modifies the module in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device | int | if specified, all parameters will be copied to that device |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def ipu(self: T, device: Optional[Union[int, device]] = None) -> T:
r"""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 optimizer if the module will
live on IPU while being optimized.
.. note::
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
copied to that device
Returns:
Module: self
"""
return self._apply(lambda t: t.ipu(device))
load_state_dict¶
def load_state_dict(
self,
state_dict: Mapping[str, Any],
strict: bool = True,
assign: bool = False
)
Copy parameters and buffers from :attr:state_dict
into this module and its descendants.
If :attr:strict
is True
, then
the keys of :attr:state_dict
must exactly match the keys returned
by this module's :meth:~torch.nn.Module.state_dict
function.
.. warning::
If :attr:assign
is True
the optimizer must be created after
the call to :attr:load_state_dict
unless
:func:~torch.__future__.get_swap_module_params_on_conversion
is True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_dict | dict | a dict containing parameters and persistent buffers. |
None |
strict | bool | whether to strictly enforce that the keys in :attr: state_dict match the keys returned by this module's:meth: ~torch.nn.Module.state_dict function. Default: True |
None |
assign | bool | When False , the properties of the tensorsin the current module are preserved while when True , theproperties of the Tensors in the state dict are preserved. The only exception is the requires_grad field of :class:~torch.nn.Parameter sfor which the value from the module is preserved. Default: False |
None |
Returns:
Type | Description |
---|---|
None | NamedTuple with missing_keys and unexpected_keys fields:missing_keys is a list of str containing any keys that are expected by this module but missing from the provided state_dict .unexpected_keys is a list of str containing the keys that are not expected by this module but present in the provided state_dict . |
View Source
def load_state_dict(
self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False
):
r"""Copy parameters and buffers from :attr:`state_dict` into this module and its descendants.
If :attr:`strict` is ``True``, then
the keys of :attr:`state_dict` must exactly match the keys returned
by this module's :meth:`~torch.nn.Module.state_dict` function.
.. warning::
If :attr:`assign` is ``True`` the optimizer must be created after
the call to :attr:`load_state_dict` unless
:func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.
Args:
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in :attr:`state_dict` match the keys returned by this module's
:meth:`~torch.nn.Module.state_dict` function. Default: ``True``
assign (bool, optional): When ``False``, the properties of the tensors
in the current module are preserved while when ``True``, the
properties of the Tensors in the state dict are preserved. The only
exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`s
for which the value from the module is preserved.
Default: ``False``
Returns:
``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
* **missing_keys** is a list of str containing any keys that are expected
by this module but missing from the provided ``state_dict``.
* **unexpected_keys** is a list of str containing the keys that are not
expected by this module but present in the provided ``state_dict``.
Note:
If a parameter or buffer is registered as ``None`` and its corresponding key
exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a
``RuntimeError``.
"""
if not isinstance(state_dict, Mapping):
raise TypeError(
f"Expected state_dict to be dict-like, got {type(state_dict)}."
)
missing_keys: List[str] = []
unexpected_keys: List[str] = []
error_msgs: List[str] = []
# copy state_dict so _load_from_state_dict can modify it
metadata = getattr(state_dict, "_metadata", None)
state_dict = OrderedDict(state_dict)
if metadata is not None:
# mypy isn't aware that "_metadata" exists in state_dict
state_dict._metadata = metadata # type: ignore[attr-defined]
def load(module, local_state_dict, prefix=""):
local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
if assign:
local_metadata["assign_to_params_buffers"] = assign
module._load_from_state_dict(
local_state_dict,
prefix,
local_metadata,
True,
missing_keys,
unexpected_keys,
error_msgs,
)
for name, child in module._modules.items():
if child is not None:
child_prefix = prefix + name + "."
child_state_dict = {
k: v
for k, v in local_state_dict.items()
if k.startswith(child_prefix)
}
load(child, child_state_dict, child_prefix) # noqa: F821
# Note that the hook can modify missing_keys and unexpected_keys.
incompatible_keys = _IncompatibleKeys(missing_keys, unexpected_keys)
for hook in module._load_state_dict_post_hooks.values():
out = hook(module, incompatible_keys)
assert out is None, (
"Hooks registered with ``register_load_state_dict_post_hook`` are not"
"expected to return new values, if incompatible_keys need to be modified,"
"it should be done inplace."
)
load(self, state_dict)
del load
if strict:
if len(unexpected_keys) > 0:
error_msgs.insert(
0,
"Unexpected key(s) in state_dict: {}. ".format(
", ".join(f'"{k}"' for k in unexpected_keys)
),
)
if len(missing_keys) > 0:
error_msgs.insert(
0,
"Missing key(s) in state_dict: {}. ".format(
", ".join(f'"{k}"' for k in missing_keys)
),
)
if len(error_msgs) > 0:
raise RuntimeError(
"Error(s) in loading state_dict for {}:\n\t{}".format(
self.__class__.__name__, "\n\t".join(error_msgs)
)
)
return _IncompatibleKeys(missing_keys, unexpected_keys)
modules¶
Return an iterator over all modules in the network.
Yields:
Type | Description |
---|---|
Module | a module in the network |
View Source
def modules(self) -> Iterator["Module"]:
r"""Return an iterator over all modules in the network.
Yields:
Module: a module in the network
Note:
Duplicate modules are returned only once. In the following
example, ``l`` will 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)
"""
for _, module in self.named_modules():
yield module
mtia¶
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 optimizer if the module will live on MTIA while being optimized.
.. note:: This method modifies the module in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device | int | if specified, all parameters will be copied to that device |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def mtia(self: T, device: Optional[Union[int, device]] = None) -> T:
r"""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 optimizer if the module will
live on MTIA while being optimized.
.. note::
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
copied to that device
Returns:
Module: self
"""
return self._apply(lambda t: t.mtia(device))
named_buffers¶
def named_buffers(
self,
prefix: str = '',
recurse: bool = True,
remove_duplicate: bool = True
) -> Iterator[Tuple[str, torch.Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix | str | prefix to prepend to all buffer names. | None |
recurse | bool | 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. |
None |
remove_duplicate | bool | whether to remove the duplicated buffers in the result. Defaults to True. | True |
Yields:
Type | Description |
---|---|
None | (str, torch.Tensor): Tuple containing the name and buffer |
View Source
def named_buffers(
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
) -> Iterator[Tuple[str, Tensor]]:
r"""Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Args:
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())
"""
gen = self._named_members(
lambda module: module._buffers.items(),
prefix=prefix,
recurse=recurse,
remove_duplicate=remove_duplicate,
)
yield from gen
named_children¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
Yields:
Type | Description |
---|---|
None | (str, Module): Tuple containing a name and child module |
View Source
def named_children(self) -> Iterator[Tuple[str, "Module"]]:
r"""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)
"""
memo = set()
for name, module in self._modules.items():
if module is not None and module not in memo:
memo.add(module)
yield name, module
named_modules¶
def named_modules(
self,
memo: Optional[Set[ForwardRef('Module')]] = None,
prefix: str = '',
remove_duplicate: bool = True
)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
memo | None | a memo to store the set of modules already added to the result | None |
prefix | None | a prefix that will be added to the name of the module | None |
remove_duplicate | None | whether to remove the duplicated module instances in the result or not |
None |
Yields:
Type | Description |
---|---|
None | (str, Module): Tuple of name and module |
View Source
def named_modules(
self,
memo: Optional[Set["Module"]] = None,
prefix: str = "",
remove_duplicate: bool = True,
):
r"""Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, ``l`` will 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))
"""
if memo is None:
memo = set()
if self not in memo:
if remove_duplicate:
memo.add(self)
yield prefix, self
for name, module in self._modules.items():
if module is None:
continue
submodule_prefix = prefix + ("." if prefix else "") + name
yield from module.named_modules(
memo, submodule_prefix, remove_duplicate
)
named_parameters¶
def named_parameters(
self,
prefix: str = '',
recurse: bool = True,
remove_duplicate: bool = True
) -> Iterator[Tuple[str, torch.nn.parameter.Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix | str | prefix to prepend to all parameter names. | None |
recurse | bool | if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module. |
None |
remove_duplicate | bool | whether to remove the duplicated parameters in the result. Defaults to True. |
None |
Yields:
Type | Description |
---|---|
None | (str, Parameter): Tuple containing the name and parameter |
View Source
def named_parameters(
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
) -> Iterator[Tuple[str, Parameter]]:
r"""Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Args:
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())
"""
gen = self._named_members(
lambda module: module._parameters.items(),
prefix=prefix,
recurse=recurse,
remove_duplicate=remove_duplicate,
)
yield from gen
parameters¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recurse | bool | if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module. |
None |
Yields:
Type | Description |
---|---|
Parameter | module parameter |
View Source
def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
r"""Return an iterator over module parameters.
This is typically passed to an optimizer.
Args:
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)
"""
for name, param in self.named_parameters(recurse=recurse):
yield param
register_backward_hook¶
def register_backward_hook(
self,
hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]]
) -> torch.utils.hooks.RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of :meth:~torch.nn.Module.register_full_backward_hook
and
the behavior of this function will change in future versions.
Returns:
Type | Description |
---|---|
None | :class:torch.utils.hooks.RemovableHandle :a handle that can be used to remove the added hook by calling handle.remove() |
View Source
def register_backward_hook(
self, hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]]
) -> RemovableHandle:
r"""Register a backward hook on the module.
This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and
the behavior of this function will change in future versions.
Returns:
:class:`torch.utils.hooks.RemovableHandle`:
a handle that can be used to remove the added hook by calling
``handle.remove()``
"""
if self._is_full_backward_hook is True:
raise RuntimeError(
"Cannot use both regular backward hooks and full backward hooks on a "
"single Module. Please use only one of them."
)
self._is_full_backward_hook = False
handle = RemovableHandle(self._backward_hooks)
self._backward_hooks[handle.id] = hook
return handle
register_buffer¶
def register_buffer(
self,
name: str,
tensor: Optional[torch.Tensor],
persistent: bool = True
) -> None
Add a buffer to the module.
This is typically used to register a buffer that should not to be
considered a model parameter. For example, BatchNorm's running_mean
is 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 setting :attr:persistent
to False
. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module's
:attr:state_dict
.
Buffers can be accessed as attributes using given names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name | str | name of the buffer. The buffer can be accessed from this module using the given name |
None |
tensor | Tensor or None | buffer to be registered. If None , then operationsthat run on buffers, such as :attr: cuda , are ignored. If None ,the buffer is not included in the module's :attr: state_dict . |
None |
persistent | bool | whether the buffer is part of this module's :attr: state_dict . |
None |
View Source
def register_buffer(
self, name: str, tensor: Optional[Tensor], persistent: bool = True
) -> None:
r"""Add a buffer to the module.
This is typically used to register a buffer that should not to be
considered a model parameter. For example, BatchNorm's ``running_mean``
is 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 setting :attr:`persistent` to ``False``. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module's
:attr:`state_dict`.
Buffers can be accessed as attributes using given names.
Args:
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 as :attr:`cuda`, are ignored. If ``None``,
the buffer is **not** included in the module's :attr:`state_dict`.
persistent (bool): whether the buffer is part of this module's
:attr:`state_dict`.
Example::
>>> # xdoctest: +SKIP("undefined vars")
>>> self.register_buffer('running_mean', torch.zeros(num_features))
"""
if persistent is False and isinstance(self, torch.jit.ScriptModule):
raise RuntimeError("ScriptModule does not support non-persistent buffers")
if "_buffers" not in self.__dict__:
raise AttributeError("cannot assign buffer before Module.__init__() call")
elif not isinstance(name, str):
raise TypeError(
f"buffer name should be a string. Got {torch.typename(name)}"
)
elif "." in name:
raise KeyError('buffer name can\'t contain "."')
elif name == "":
raise KeyError('buffer name can\'t be empty string ""')
elif hasattr(self, name) and name not in self._buffers:
raise KeyError(f"attribute '{name}' already exists")
elif tensor is not None and not isinstance(tensor, torch.Tensor):
raise TypeError(
f"cannot assign '{torch.typename(tensor)}' object to buffer '{name}' "
"(torch Tensor or None required)"
)
else:
for hook in _global_buffer_registration_hooks.values():
output = hook(self, name, tensor)
if output is not None:
tensor = output
self._buffers[name] = tensor
if persistent:
self._non_persistent_buffers_set.discard(name)
else:
self._non_persistent_buffers_set.add(name)
register_forward_hook¶
def register_forward_hook(
self,
hook: Union[Callable[[~T, Tuple[Any, ...], Any], Optional[Any]], Callable[[~T, Tuple[Any, ...], Dict[str, Any], Any], Optional[Any]]],
*,
prepend: bool = False,
with_kwargs: bool = False,
always_call: bool = False
) -> torch.utils.hooks.RemovableHandle
Register a forward hook on the module.
The hook will be called every time after :func:forward
has computed an output.
If with_kwargs
is 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 the forward
. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after :func:forward
is called. The hook
should have the following signature::
hook(module, args, output) -> None or modified output
If with_kwargs
is True
, the forward hook will be passed the
kwargs
given 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:
Name | Type | Description | Default |
---|---|---|---|
hook | Callable | The user defined hook to be registered. | None |
prepend | bool | If True , the provided hook will be firedbefore all existing forward hooks on this:class: torch.nn.modules.Module . Otherwise, the providedhook will be fired after all existing forward hooks onthis :class: torch.nn.modules.Module . Note that globalforward hooks registered with:func: register_module_forward_hook will fire before all hooksregistered by this method. Default: False |
None |
with_kwargs | bool | If True , the hook will be passed thekwargs given to the forward function. Default: False |
None |
always_call | bool | If True the hook will be run regardless ofwhether an exception is raised while calling the Module. Default: False |
None |
Returns:
Type | Description |
---|---|
None | :class:torch.utils.hooks.RemovableHandle :a handle that can be used to remove the added hook by calling handle.remove() |
View Source
def register_forward_hook(
self,
hook: Union[
Callable[[T, Tuple[Any, ...], Any], Optional[Any]],
Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Optional[Any]],
],
*,
prepend: bool = False,
with_kwargs: bool = False,
always_call: bool = False,
) -> RemovableHandle:
r"""Register a forward hook on the module.
The hook will be called every time after :func:`forward` has computed an output.
If ``with_kwargs`` is ``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 the ``forward``. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after :func:`forward` is called. The hook
should have the following signature::
hook(module, args, output) -> None or modified output
If ``with_kwargs`` is ``True``, the forward hook will be passed the
``kwargs`` given 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
Args:
hook (Callable): The user defined hook to be registered.
prepend (bool): If ``True``, the provided ``hook`` will be fired
before all existing ``forward`` hooks on this
:class:`torch.nn.modules.Module`. Otherwise, the provided
``hook`` will be fired after all existing ``forward`` hooks on
this :class:`torch.nn.modules.Module`. Note that global
``forward`` hooks registered with
:func:`register_module_forward_hook` will fire before all hooks
registered by this method.
Default: ``False``
with_kwargs (bool): If ``True``, the ``hook`` will be passed the
kwargs given to the forward function.
Default: ``False``
always_call (bool): If ``True`` the ``hook`` will be run regardless of
whether an exception is raised while calling the Module.
Default: ``False``
Returns:
:class:`torch.utils.hooks.RemovableHandle`:
a handle that can be used to remove the added hook by calling
``handle.remove()``
"""
handle = RemovableHandle(
self._forward_hooks,
extra_dict=[
self._forward_hooks_with_kwargs,
self._forward_hooks_always_called,
],
)
self._forward_hooks[handle.id] = hook
if with_kwargs:
self._forward_hooks_with_kwargs[handle.id] = True
if always_call:
self._forward_hooks_always_called[handle.id] = True
if prepend:
self._forward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
return handle
register_forward_pre_hook¶
def register_forward_pre_hook(
self,
hook: Union[Callable[[~T, Tuple[Any, ...]], Optional[Any]], Callable[[~T, Tuple[Any, ...], Dict[str, Any]], Optional[Tuple[Any, Dict[str, Any]]]]],
*,
prepend: bool = False,
with_kwargs: bool = False
) -> torch.utils.hooks.RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before :func:forward
is invoked.
If with_kwargs
is 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 the forward
. 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_kwargs
is 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:
Name | Type | Description | Default |
---|---|---|---|
hook | Callable | The user defined hook to be registered. | None |
prepend | bool | If true, the provided hook will be fired beforeall existing forward_pre hooks on this:class: torch.nn.modules.Module . Otherwise, the providedhook will be fired after all existing forward_pre hookson this :class: torch.nn.modules.Module . Note that globalforward_pre hooks registered with:func: register_module_forward_pre_hook will fire before allhooks registered by this method. Default: False |
None |
with_kwargs | bool | If true, the hook will be passed the kwargsgiven to the forward function. Default: False |
None |
Returns:
Type | Description |
---|---|
None | :class:torch.utils.hooks.RemovableHandle :a handle that can be used to remove the added hook by calling handle.remove() |
View Source
def register_forward_pre_hook(
self,
hook: Union[
Callable[[T, Tuple[Any, ...]], Optional[Any]],
Callable[
[T, Tuple[Any, ...], Dict[str, Any]],
Optional[Tuple[Any, Dict[str, Any]]],
],
],
*,
prepend: bool = False,
with_kwargs: bool = False,
) -> RemovableHandle:
r"""Register a forward pre-hook on the module.
The hook will be called every time before :func:`forward` is invoked.
If ``with_kwargs`` is 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 the ``forward``. 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_kwargs`` is 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
Args:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided ``hook`` will be fired before
all existing ``forward_pre`` hooks on this
:class:`torch.nn.modules.Module`. Otherwise, the provided
``hook`` will be fired after all existing ``forward_pre`` hooks
on this :class:`torch.nn.modules.Module`. Note that global
``forward_pre`` hooks registered with
:func:`register_module_forward_pre_hook` will fire before all
hooks registered by this method.
Default: ``False``
with_kwargs (bool): If true, the ``hook`` will be passed the kwargs
given to the forward function.
Default: ``False``
Returns:
:class:`torch.utils.hooks.RemovableHandle`:
a handle that can be used to remove the added hook by calling
``handle.remove()``
"""
handle = RemovableHandle(
self._forward_pre_hooks, extra_dict=self._forward_pre_hooks_with_kwargs
)
self._forward_pre_hooks[handle.id] = hook
if with_kwargs:
self._forward_pre_hooks_with_kwargs[handle.id] = True
if prepend:
self._forward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
return handle
register_full_backward_hook¶
def register_full_backward_hook(
self,
hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]],
prepend: bool = False
) -> torch.utils.hooks.RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature::
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The :attr:grad_input
and :attr:grad_output
are 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 of :attr:grad_input
in
subsequent computations. :attr:grad_input
will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in :attr:grad_input
and :attr:grad_output
will be None
for 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:
Name | Type | Description | Default |
---|---|---|---|
hook | Callable | The user-defined hook to be registered. | None |
prepend | bool | If true, the provided hook will be fired beforeall existing backward hooks on this:class: torch.nn.modules.Module . Otherwise, the providedhook will be fired after all existing backward hooks onthis :class: torch.nn.modules.Module . Note that globalbackward hooks registered with:func: register_module_full_backward_hook will fire beforeall hooks registered by this method. |
None |
Returns:
Type | Description |
---|---|
None | :class:torch.utils.hooks.RemovableHandle :a handle that can be used to remove the added hook by calling handle.remove() |
View Source
def register_full_backward_hook(
self,
hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]],
prepend: bool = False,
) -> RemovableHandle:
r"""Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module
are computed, i.e. the hook will execute if and only if the gradients with
respect to module outputs are computed. The hook should have the following
signature::
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The :attr:`grad_input` and :attr:`grad_output` are 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 of :attr:`grad_input` in
subsequent computations. :attr:`grad_input` will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for 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.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided ``hook`` will be fired before
all existing ``backward`` hooks on this
:class:`torch.nn.modules.Module`. Otherwise, the provided
``hook`` will be fired after all existing ``backward`` hooks on
this :class:`torch.nn.modules.Module`. Note that global
``backward`` hooks registered with
:func:`register_module_full_backward_hook` will fire before
all hooks registered by this method.
Returns:
:class:`torch.utils.hooks.RemovableHandle`:
a handle that can be used to remove the added hook by calling
``handle.remove()``
"""
if self._is_full_backward_hook is False:
raise RuntimeError(
"Cannot use both regular backward hooks and full backward hooks on a "
"single Module. Please use only one of them."
)
self._is_full_backward_hook = True
handle = RemovableHandle(self._backward_hooks)
self._backward_hooks[handle.id] = hook
if prepend:
self._backward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
return handle
register_full_backward_pre_hook¶
def register_full_backward_pre_hook(
self,
hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]],
prepend: bool = False
) -> torch.utils.hooks.RemovableHandle
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] or None
The :attr:grad_output
is 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 of :attr:grad_output
in
subsequent computations. Entries in :attr:grad_output
will be None
for
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:
Name | Type | Description | Default |
---|---|---|---|
hook | Callable | The user-defined hook to be registered. | None |
prepend | bool | If true, the provided hook will be fired beforeall existing backward_pre hooks on this:class: torch.nn.modules.Module . Otherwise, the providedhook will be fired after all existing backward_pre hookson this :class: torch.nn.modules.Module . Note that globalbackward_pre hooks registered with:func: register_module_full_backward_pre_hook will fire beforeall hooks registered by this method. |
None |
Returns:
Type | Description |
---|---|
None | :class:torch.utils.hooks.RemovableHandle :a handle that can be used to remove the added hook by calling handle.remove() |
View Source
def register_full_backward_pre_hook(
self,
hook: Callable[["Module", _grad_t], Union[None, _grad_t]],
prepend: bool = False,
) -> RemovableHandle:
r"""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] or None
The :attr:`grad_output` is 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 of :attr:`grad_output` in
subsequent computations. Entries in :attr:`grad_output` will be ``None`` for
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.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided ``hook`` will be fired before
all existing ``backward_pre`` hooks on this
:class:`torch.nn.modules.Module`. Otherwise, the provided
``hook`` will be fired after all existing ``backward_pre`` hooks
on this :class:`torch.nn.modules.Module`. Note that global
``backward_pre`` hooks registered with
:func:`register_module_full_backward_pre_hook` will fire before
all hooks registered by this method.
Returns:
:class:`torch.utils.hooks.RemovableHandle`:
a handle that can be used to remove the added hook by calling
``handle.remove()``
"""
handle = RemovableHandle(self._backward_pre_hooks)
self._backward_pre_hooks[handle.id] = hook
if prepend:
self._backward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
return handle
register_load_state_dict_post_hook¶
Register a post-hook to be run after module's :meth:~nn.Module.load_state_dict
is called.
It should have the following signature:: hook(module, incompatible_keys) -> None
The module
argument is the current module that this hook is registered
on, and the incompatible_keys
argument is a NamedTuple
consisting
of attributes missing_keys
and unexpected_keys
. missing_keys
is a list
of str
containing the missing keys and
unexpected_keys
is a list
of str
containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling :func:load_state_dict
with
strict=True
are affected by modifications the hook makes to
missing_keys
or unexpected_keys
, as expected. Additions to either
set of keys will result in an error being thrown when strict=True
, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
Type | Description |
---|---|
None | :class:torch.utils.hooks.RemovableHandle :a handle that can be used to remove the added hook by calling handle.remove() |
View Source
def register_load_state_dict_post_hook(self, hook):
r"""Register a post-hook to be run after module's :meth:`~nn.Module.load_state_dict` is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The ``module`` argument is the current module that this hook is registered
on, and the ``incompatible_keys`` argument is a ``NamedTuple`` consisting
of attributes ``missing_keys`` and ``unexpected_keys``. ``missing_keys``
is a ``list`` of ``str`` containing the missing keys and
``unexpected_keys`` is a ``list`` of ``str`` containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling :func:`load_state_dict` with
``strict=True`` are affected by modifications the hook makes to
``missing_keys`` or ``unexpected_keys``, as expected. Additions to either
set of keys will result in an error being thrown when ``strict=True``, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
:class:`torch.utils.hooks.RemovableHandle`:
a handle that can be used to remove the added hook by calling
``handle.remove()``
"""
handle = RemovableHandle(self._load_state_dict_post_hooks)
self._load_state_dict_post_hooks[handle.id] = hook
return handle
register_load_state_dict_pre_hook¶
Register a pre-hook to be run before module's :meth:~nn.Module.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:
Name | Type | Description | Default |
---|---|---|---|
hook | Callable | Callable hook that will be invoked before loading the state dict. |
None |
View Source
def register_load_state_dict_pre_hook(self, hook):
r"""Register a pre-hook to be run before module's :meth:`~nn.Module.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
Arguments:
hook (Callable): Callable hook that will be invoked before
loading the state dict.
"""
return self._register_load_state_dict_pre_hook(hook, with_module=True)
register_module¶
Alias for :func:add_module
.
View Source
register_parameter¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name | str | name of the parameter. The parameter can be accessed from this module using the given name |
None |
param | Parameter or None | parameter to be added to the module. IfNone , then operations that run on parameters, such as :attr:cuda ,are ignored. If None , the parameter is not included in themodule's :attr: state_dict . |
None |
View Source
def register_parameter(self, name: str, param: Optional[Parameter]) -> None:
r"""Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
Args:
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 as :attr:`cuda`,
are ignored. If ``None``, the parameter is **not** included in the
module's :attr:`state_dict`.
"""
if "_parameters" not in self.__dict__:
raise AttributeError(
"cannot assign parameter before Module.__init__() call"
)
elif not isinstance(name, str):
raise TypeError(
f"parameter name should be a string. Got {torch.typename(name)}"
)
elif "." in name:
raise KeyError('parameter name can\'t contain "."')
elif name == "":
raise KeyError('parameter name can\'t be empty string ""')
elif hasattr(self, name) and name not in self._parameters:
raise KeyError(f"attribute '{name}' already exists")
if param is None:
self._parameters[name] = None
elif not isinstance(param, Parameter):
raise TypeError(
f"cannot assign '{torch.typename(param)}' object to parameter '{name}' "
"(torch.nn.Parameter or None required)"
)
elif param.grad_fn:
raise ValueError(
f"Cannot assign non-leaf Tensor to parameter '{name}'. Model "
f"parameters must be created explicitly. To express '{name}' "
"as a function of another Tensor, compute the value in "
"the forward() method."
)
else:
for hook in _global_parameter_registration_hooks.values():
output = hook(self, name, param)
if output is not None:
param = output
self._parameters[name] = param
register_state_dict_post_hook¶
Register a post-hook for the :meth:~torch.nn.Module.state_dict
method.
It should have the following signature:: hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the state_dict
inplace.
View Source
def register_state_dict_post_hook(self, hook):
r"""Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method.
It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the ``state_dict`` inplace.
"""
# In _register_state_dict_hook there was a bug described in
# https://github.com/pytorch/pytorch/issues/117437 where the return value
# was only respected for the root module but not child submodules.
# We fix this in this public version by only allowing inplace modifications on
# the state_dict by the hook. However, since hooks registered via both these
# APIs will be added to `_state_dict_hooks` and the type of `_state_dict_hooks`
# cannot be changed due to many dependencies on it, we mark a hook
# as being registered via the public API by setting `_from_public_api` on it.
# In the implementation of `state_dict`, if the callable does not have this
# flag, the old behavior of respecting the return value will be preserved
# for the root module, otherwise, we ensure that the hook returns None.
hook._from_public_api = True
handle = RemovableHandle(self._state_dict_hooks)
self._state_dict_hooks[handle.id] = hook
return handle
register_state_dict_pre_hook¶
Register a pre-hook for the :meth:~torch.nn.Module.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_dict
call is made.
View Source
def register_state_dict_pre_hook(self, hook):
r"""Register a pre-hook for the :meth:`~torch.nn.Module.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_dict``
call is made.
"""
handle = RemovableHandle(self._state_dict_pre_hooks)
self._state_dict_pre_hooks[handle.id] = hook
return handle
requires_grad_¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters' :attr:requires_grad
attributes
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 :ref:locally-disable-grad-doc
for a comparison between
.requires_grad_()
and several similar mechanisms that may be confused with it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
requires_grad | bool | whether autograd should record operations on parameters in this module. Default: True . |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def requires_grad_(self: T, requires_grad: bool = True) -> T:
r"""Change if autograd should record operations on parameters in this module.
This method sets the parameters' :attr:`requires_grad` attributes
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 :ref:`locally-disable-grad-doc` for a comparison between
`.requires_grad_()` and several similar mechanisms that may be confused with it.
Args:
requires_grad (bool): whether autograd should record operations on
parameters in this module. Default: ``True``.
Returns:
Module: self
"""
for p in self.parameters():
p.requires_grad_(requires_grad)
return self
set_extra_state¶
Set extra state contained in the loaded state_dict
.
This function is called from :func:load_state_dict
to handle any extra state
found within the state_dict
. Implement this function and a corresponding
View Source
def set_extra_state(self, state: Any) -> None:
"""Set extra state contained in the loaded `state_dict`.
This function is called from :func:`load_state_dict` to handle any extra state
found within the `state_dict`. Implement this function and a corresponding
:func:`get_extra_state` for your module if you need to store extra state within its
`state_dict`.
Args:
state (dict): Extra state from the `state_dict`
"""
raise RuntimeError(
"Reached a code path in Module.set_extra_state() that should never be called. "
"Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
"to report this bug."
)
set_submodule¶
Set the submodule given by target
if it exists, otherwise throw an error.
For example, let's say you have an nn.Module
A
that
looks like this:
.. code-block:: text
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.Module
A
. A
has a nested
submodule net_b
, which itself has two submodules net_c
and linear
. net_c
then has a submodule conv
.)
To overide the Conv2d
with a new submodule Linear
, you
would call
set_submodule("net_b.net_c.conv", nn.Linear(33, 16))
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target | None | The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.) |
None |
module | None | The module to set the submodule to. | None |
Raises:
Type | Description |
---|---|
ValueError | If the target string is empty |
AttributeError | If the target string references an invalid path or resolves to something that is not an nn.Module |
View Source
def set_submodule(self, target: str, module: "Module") -> None:
"""
Set the submodule given by ``target`` if it exists, otherwise throw an error.
For example, let's say you have an ``nn.Module`` ``A`` that
looks like this:
.. code-block:: text
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.Module`` ``A``. ``A`` has a nested
submodule ``net_b``, which itself has two submodules ``net_c``
and ``linear``. ``net_c`` then has a submodule ``conv``.)
To overide the ``Conv2d`` with a new submodule ``Linear``, you
would call
``set_submodule("net_b.net_c.conv", nn.Linear(33, 16))``.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
Raises:
ValueError: If the target string is empty
AttributeError: If the target string references an invalid
path or resolves to something that is not an
``nn.Module``
"""
if target == "":
raise ValueError("Cannot set the submodule without a target name!")
atoms: List[str] = target.split(".")
name = atoms.pop(-1)
mod: torch.nn.Module = self
for item in atoms:
if not hasattr(mod, item):
raise AttributeError(
mod._get_name() + " has no attribute `" + item + "`"
)
mod = getattr(mod, item)
# Use isinstance instead of type here to also handle subclass of nn.Module
if not isinstance(mod, torch.nn.Module):
raise AttributeError("`" + item + "` is not an nn.Module")
setattr(mod, name, module)
share_memory¶
See :meth:torch.Tensor.share_memory_
.
View Source
state_dict¶
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 None
are 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 for
destination
, prefix
and keep_vars
in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
.. warning::
Please avoid the use of argument destination
as it is not
designed for end-users.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
destination | dict | If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an OrderedDict will be created and returned.Default: None . |
None |
prefix | str | a prefix added to parameter and buffer names to compose the keys in state_dict. Default: '' . |
None |
keep_vars | bool | by default the :class:~torch.Tensor sreturned in the state dict are detached from autograd. If it's set to True , detaching will not be performed.Default: False . |
None |
Returns:
Type | Description |
---|---|
dict | a dictionary containing a whole state of the module |
View Source
def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
r"""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 ``None`` are 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 for
``destination``, ``prefix`` and ``keep_vars`` in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
.. warning::
Please avoid the use of argument ``destination`` as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an ``OrderedDict`` will 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 :class:`~torch.Tensor` s
returned in the state dict are detached from autograd. If it's
set to ``True``, detaching will not be performed.
Default: ``False``.
Returns:
dict:
a dictionary containing a whole state of the module
Example::
>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
"""
# TODO: Remove `args` and the parsing logic when BC allows.
if len(args) > 0:
# DeprecationWarning is ignored by default
warnings.warn(
"Positional args are being deprecated, use kwargs instead. Refer to "
"https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.state_dict"
" for details.",
FutureWarning,
stacklevel=2,
)
if destination is None:
destination = args[0]
if len(args) > 1 and prefix == "":
prefix = args[1]
if len(args) > 2 and keep_vars is False:
keep_vars = args[2]
if destination is None:
destination = OrderedDict()
destination._metadata = OrderedDict()
local_metadata = dict(version=self._version)
if hasattr(destination, "_metadata"):
destination._metadata[prefix[:-1]] = local_metadata
for hook in self._state_dict_pre_hooks.values():
hook(self, prefix, keep_vars)
self._save_to_state_dict(destination, prefix, keep_vars)
for name, module in self._modules.items():
if module is not None:
module.state_dict(
destination=destination,
prefix=prefix + name + ".",
keep_vars=keep_vars,
)
for hook in self._state_dict_hooks.values():
hook_result = hook(self, destination, prefix, local_metadata)
if not getattr(hook, "_from_public_api", False):
if hook_result is not None:
destination = hook_result
else:
if hook_result is not None:
raise RuntimeError("state_dict post-hook must return None")
return destination
to¶
Move and/or cast the parameters and buffers.
This can be called as
.. function:: to(device=None, dtype=None, non_blocking=False) :noindex:
.. function:: to(dtype, non_blocking=False) :noindex:
.. function:: to(tensor, non_blocking=False) :noindex:
.. function:: to(memory_format=torch.channels_last) :noindex:
Its signature is similar to :meth:torch.Tensor.to
, but only accepts
floating point or complex :attr:dtype
\ s. In addition, this method will
only cast the floating point or complex parameters and buffers to :attr:dtype
(if given). The integral parameters and buffers will be moved
:attr:device
, if that is given, but with dtypes unchanged. When
:attr:non_blocking
is 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:
Name | Type | Description | Default |
---|---|---|---|
device ( | None | class:torch.device ): the desired device of the parametersand buffers in this module |
None |
dtype ( | None | class:torch.dtype ): the desired floating point or complex dtype ofthe parameters and buffers in this module |
None |
tensor | torch.Tensor | Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module |
None |
memory_format ( | None | class:torch.memory_format ): the desired memoryformat for 4D parameters and buffers in this module (keyword only argument) |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def to(self, *args, **kwargs):
r"""Move and/or cast the parameters and buffers.
This can be called as
.. function:: to(device=None, dtype=None, non_blocking=False)
:noindex:
.. function:: to(dtype, non_blocking=False)
:noindex:
.. function:: to(tensor, non_blocking=False)
:noindex:
.. function:: to(memory_format=torch.channels_last)
:noindex:
Its signature is similar to :meth:`torch.Tensor.to`, but only accepts
floating point or complex :attr:`dtype`\ s. In addition, this method will
only cast the floating point or complex parameters and buffers to :attr:`dtype`
(if given). The integral parameters and buffers will be moved
:attr:`device`, if that is given, but with dtypes unchanged. When
:attr:`non_blocking` is 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.
Args:
device (:class:`torch.device`): the desired device of the parameters
and buffers in this module
dtype (:class:`torch.dtype`): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
memory_format (:class:`torch.memory_format`): the desired memory
format for 4D parameters and buffers in this module (keyword
only argument)
Returns:
Module: self
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)
"""
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(
*args, **kwargs
)
if dtype is not None:
if not (dtype.is_floating_point or dtype.is_complex):
raise TypeError(
"nn.Module.to only accepts floating point or complex "
f"dtypes, but got desired dtype={dtype}"
)
if dtype.is_complex:
warnings.warn(
"Complex modules are a new feature under active development whose design may change, "
"and some modules might not work as expected when using complex tensors as parameters or buffers. "
"Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
"if a complex module does not work as expected."
)
def convert(t):
try:
if convert_to_format is not None and t.dim() in (4, 5):
return t.to(
device,
dtype if t.is_floating_point() or t.is_complex() else None,
non_blocking,
memory_format=convert_to_format,
)
return t.to(
device,
dtype if t.is_floating_point() or t.is_complex() else None,
non_blocking,
)
except NotImplementedError as e:
if str(e) == "Cannot copy out of meta tensor; no data!":
raise NotImplementedError(
f"{e} Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() "
f"when moving module from meta to a different device."
) from None
else:
raise
return self._apply(convert)
to_empty¶
def to_empty(
self: ~T,
*,
device: Union[int, str, torch.device, NoneType],
recurse: bool = True
) -> ~T
Move the parameters and buffers to the specified device without copying storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device ( | None | class:torch.device ): The desired device of the parametersand buffers in this module. |
None |
recurse | bool | Whether parameters and buffers of submodules should be recursively moved to the specified device. |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def to_empty(
self: T, *, device: Optional[DeviceLikeType], recurse: bool = True
) -> T:
r"""Move the parameters and buffers to the specified device without copying storage.
Args:
device (:class:`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:
Module: self
"""
return self._apply(
lambda t: torch.empty_like(t, device=device), recurse=recurse
)
train¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:Dropout
, :class:BatchNorm
,
etc.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode | bool | whether to set training mode (True ) or evaluationmode ( False ). Default: True . |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def train(self: T, mode: bool = True) -> T:
r"""Set the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
etc.
Args:
mode (bool): whether to set training mode (``True``) or evaluation
mode (``False``). Default: ``True``.
Returns:
Module: self
"""
if not isinstance(mode, bool):
raise ValueError("training mode is expected to be boolean")
self.training = mode
for module in self.children():
module.train(mode)
return self
type¶
Casts all parameters and buffers to :attr:dst_type
.
.. note:: This method modifies the module in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dst_type | type or string | the desired type | None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
xpu¶
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:
Name | Type | Description | Default |
---|---|---|---|
device | int | if specified, all parameters will be copied to that device |
None |
Returns:
Type | Description |
---|---|
Module | self |
View Source
def xpu(self: T, device: Optional[Union[int, device]] = None) -> T:
r"""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.
Arguments:
device (int, optional): if specified, all parameters will be
copied to that device
Returns:
Module: self
"""
return self._apply(lambda t: t.xpu(device))
zero_grad¶
Reset gradients of all model parameters.
See similar function under :class:torch.optim.Optimizer
for more context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
set_to_none | bool | instead of setting to zero, set the grads to None. See :meth: torch.optim.Optimizer.zero_grad for details. |
None |
View Source
def zero_grad(self, set_to_none: bool = True) -> None:
r"""Reset gradients of all model parameters.
See similar function under :class:`torch.optim.Optimizer` for more context.
Args:
set_to_none (bool): instead of setting to zero, set the grads to None.
See :meth:`torch.optim.Optimizer.zero_grad` for details.
"""
if getattr(self, "_is_replica", False):
warnings.warn(
"Calling .zero_grad() from a module created with nn.DataParallel() has no effect. "
"The parameters are copied (in a differentiable manner) from the original module. "
"This means they are not leaf nodes in autograd and so don't accumulate gradients. "
"If you need gradients in your forward method, consider using autograd.grad instead."
)
for p in self.parameters():
if p.grad is not None:
if set_to_none:
p.grad = None
else:
if p.grad.grad_fn is not None:
p.grad.detach_()
else:
p.grad.requires_grad_(False)
p.grad.zero_()