Module fl_server_core.models.model¶
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
from copy import copy
from django.contrib.postgres.fields import ArrayField
from django.db.models import (
BinaryField, CASCADE, CharField, ForeignKey, IntegerField, ManyToManyField, TextField, UUIDField
)
from polymorphic.models import PolymorphicModel
import torch
from torch import Tensor
from torch.nn import Module
from typing import List, Optional, Sequence, TypeVar
from uuid import uuid4
from ..utils.torch_serialization import (
from_torch_module, to_torch_module,
from_torch_tensor, to_torch_tensor,
is_torchscript_instance
)
from .. import models as models
from .user import User
class Model(PolymorphicModel):
"""
Base model class for all types of model models.
"""
id: UUIDField = UUIDField(primary_key=True, editable=False, default=uuid4)
"""Unique identifier for the model."""
owner: ForeignKey = ForeignKey(User, on_delete=CASCADE)
"""User who owns the model."""
round: IntegerField = IntegerField()
"""Round number of the model."""
weights: BinaryField = BinaryField()
"""Weights of the model."""
def is_global_model(self):
"""
Checks if the model is a global model.
Returns:
bool: True if the model is a global model, False otherwise.
"""
return isinstance(self, GlobalModel)
def is_local_model(self):
"""
Checks if the model is a local model.
Returns:
bool: True if the model is a local model, False otherwise.
"""
return isinstance(self, LocalModel)
def get_torch_model(self) -> torch.nn.Module:
"""
Converts the model weights to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
return to_torch_module(self.weights)
def set_torch_model(self, value: torch.nn.Module):
"""
Sets the model weights from a PyTorch model.
Args:
value (torch.nn.Module): The PyTorch model.
"""
self.weights = from_torch_module(value)
def get_training(self) -> Optional["models.Training"]:
"""
Gets the training associated with the model.
Returns:
models.Training: The training associated with the model.
"""
return models.Training.objects.filter(model=self).first()
class GlobalModel(Model):
"""
Model class for global models.
"""
name: CharField = CharField(max_length=256)
"""Name of the model."""
description: TextField = TextField()
"""Description of the model."""
# alternative to be postgres independent: create a new model for each nullable integer field
# and map the corresponding list of integers to the model (but pay attention to the order)
input_shape: ArrayField = ArrayField(IntegerField(null=True), null=True)
"""Input shape of the model."""
preprocessing: BinaryField = BinaryField(null=True)
"""Preprocessing of the model."""
def get_preprocessing_torch_model(self) -> torch.nn.Module:
"""
Converts the preprocessing to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
return to_torch_module(self.preprocessing)
def set_preprocessing_torch_model(self, value: torch.nn.Module):
"""
Sets the preprocessing from a PyTorch model.
Args:
value (torch.nn.Module): The PyTorch model.
"""
self.preprocessing = from_torch_module(value)
class SWAGModel(GlobalModel):
"""
Model class for SWAG models.
"""
swag_first_moment: BinaryField = BinaryField()
"""First moment of the SWAG model."""
swag_second_moment: BinaryField = BinaryField()
"""Second moment of the SWAG model."""
@property
def first_moment(self) -> Tensor:
"""
Gets the first moment of the SWAG model.
Returns:
Tensor: The first moment of the SWAG model.
"""
return to_torch_tensor(self.swag_first_moment)
@first_moment.setter
def first_moment(self, value: Tensor):
"""
Sets the first moment of the SWAG model.
Args:
value (Tensor): The first moment of the SWAG model.
"""
self.swag_first_moment = from_torch_tensor(value)
@property
def second_moment(self) -> Tensor:
"""
Gets the second moment of the SWAG model.
Returns:
Tensor: The second moment of the SWAG model.
"""
return to_torch_tensor(self.swag_second_moment)
@second_moment.setter
def second_moment(self, value: Tensor):
"""
Sets the second moment of the SWAG model.
Args:
value (Tensor): The second moment of the SWAG model.
"""
self.swag_second_moment = from_torch_tensor(value)
class MeanModel(GlobalModel):
"""
Model class for mean models.
"""
models: ManyToManyField = ManyToManyField(GlobalModel, related_name="mean_models")
"""Models of the mean model."""
def get_torch_model(self) -> torch.nn.Module:
"""
Converts the models to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
torch_models: List[torch.nn.Module] = [model.get_torch_model() for model in self.models.all()]
model = MeanModule(torch_models)
if all(is_torchscript_instance(m) for m in torch_models):
return torch.jit.script(model)
return model
def set_torch_model(self, value: torch.nn.Module):
"""
Sets the models from a PyTorch model.
Args:
value (torch.nn.Module): The PyTorch model.
"""
raise NotImplementedError()
class LocalModel(Model):
"""
Model class for local models.
"""
base_model: ForeignKey = ForeignKey(GlobalModel, on_delete=CASCADE)
"""Base model of the local model."""
sample_size: IntegerField = IntegerField()
"""Sample size of the local model."""
def get_training(self) -> Optional["models.Training"]:
"""
Gets the training associated with the base model.
Returns:
models.Training: The training associated with the base model.
"""
return models.Training.objects.filter(model=self.base_model).first()
TModel = TypeVar("TModel", bound=Model)
class MeanModule(Module):
"""
PyTorch module for mean models.
"""
def __init__(self, models: Sequence[torch.nn.Module]):
"""
Initializes the mean models.
Args:
models (Sequence[torch.nn.Module]): The models of the mean model.
"""
super().__init__()
self.models = models
"""Models of the mean model."""
def forward(self, input: Tensor) -> Tensor:
"""
Forward pass of the mean models.
Args:
input (Tensor): The input tensor.
Returns:
Tensor: The output tensor.
"""
return torch.stack([model(input) for model in self.models], dim=0).mean(dim=0)
def clone_model(model: Model) -> Model:
"""
Copies a model instance in the database
See https://docs.djangoproject.com/en/5.0/topics/db/queries/#copying-model-instances
and stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database
Args:
model (Model): the model to be copied
Returns:
Model: New Model instance that is a copy of the old one
"""
model.save()
new_model = copy(model)
new_model.pk = None
new_model.id = None
new_model._state.adding = True
try:
delattr(new_model, '_prefetched_objects_cache')
except AttributeError:
pass
new_model.save()
new_model.owner = model.owner
new_model.save()
return new_model
Variables¶
Functions¶
clone_model¶
Copies a model instance in the database
See https://docs.djangoproject.com/en/5.0/topics/db/queries/#copying-model-instances and stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model | Model | the model to be copied | None |
Returns:
Type | Description |
---|---|
Model | New Model instance that is a copy of the old one |
View Source
def clone_model(model: Model) -> Model:
"""
Copies a model instance in the database
See https://docs.djangoproject.com/en/5.0/topics/db/queries/#copying-model-instances
and stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database
Args:
model (Model): the model to be copied
Returns:
Model: New Model instance that is a copy of the old one
"""
model.save()
new_model = copy(model)
new_model.pk = None
new_model.id = None
new_model._state.adding = True
try:
delattr(new_model, '_prefetched_objects_cache')
except AttributeError:
pass
new_model.save()
new_model.owner = model.owner
new_model.save()
return new_model
Classes¶
GlobalModel¶
Model class for global models.
View Source
class GlobalModel(Model):
"""
Model class for global models.
"""
name: CharField = CharField(max_length=256)
"""Name of the model."""
description: TextField = TextField()
"""Description of the model."""
# alternative to be postgres independent: create a new model for each nullable integer field
# and map the corresponding list of integers to the model (but pay attention to the order)
input_shape: ArrayField = ArrayField(IntegerField(null=True), null=True)
"""Input shape of the model."""
preprocessing: BinaryField = BinaryField(null=True)
"""Preprocessing of the model."""
def get_preprocessing_torch_model(self) -> torch.nn.Module:
"""
Converts the preprocessing to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
return to_torch_module(self.preprocessing)
def set_preprocessing_torch_model(self, value: torch.nn.Module):
"""
Sets the preprocessing from a PyTorch model.
Args:
value (torch.nn.Module): The PyTorch model.
"""
self.preprocessing = from_torch_module(value)
Ancestors (in MRO)¶
- fl_server_core.models.model.Model
- polymorphic.models.PolymorphicModel
- django.db.models.base.Model
Descendants¶
- fl_server_core.models.model.SWAGModel
- fl_server_core.models.model.MeanModel
Class variables¶
Static methods¶
check¶
View Source
@classmethod
def check(cls, **kwargs):
errors = [
*cls._check_swappable(),
*cls._check_model(),
*cls._check_managers(**kwargs),
]
if not cls._meta.swapped:
databases = kwargs.get("databases") or []
errors += [
*cls._check_fields(**kwargs),
*cls._check_m2m_through_same_relationship(),
*cls._check_long_column_names(databases),
]
clash_errors = (
*cls._check_id_field(),
*cls._check_field_name_clashes(),
*cls._check_model_name_db_lookup_clashes(),
*cls._check_property_name_related_field_accessor_clashes(),
*cls._check_single_primary_key(),
)
errors.extend(clash_errors)
# If there are field name clashes, hide consequent column name
# clashes.
if not clash_errors:
errors.extend(cls._check_column_name_clashes())
errors += [
*cls._check_index_together(),
*cls._check_unique_together(),
*cls._check_indexes(databases),
*cls._check_ordering(),
*cls._check_constraints(databases),
*cls._check_default_pk(),
]
return errors
from_db¶
View Source
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
translate_polymorphic_Q_object¶
View Source
Instance variables¶
Methods¶
clean¶
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
View Source
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
clean_fields¶
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
View Source
def clean_fields(self, exclude=None):
"""
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in f.empty_values:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.error_list
if errors:
raise ValidationError(errors)
date_error_message¶
View Source
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages["unique_for_date"],
code="unique_for_date",
params={
"model": self,
"model_name": capfirst(opts.verbose_name),
"lookup_type": lookup_type,
"field": field_name,
"field_label": capfirst(field.verbose_name),
"date_field": unique_for,
"date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
},
)
delete¶
View Source
def delete(self, using=None, keep_parents=False):
if self.pk is None:
raise ValueError(
"%s object can't be deleted because its %s attribute is set "
"to None." % (self._meta.object_name, self._meta.pk.attname)
)
using = using or router.db_for_write(self.__class__, instance=self)
collector = Collector(using=using)
collector.collect([self], keep_parents=keep_parents)
return collector.delete()
description¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
full_clean¶
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
View Source
def full_clean(self, exclude=None, validate_unique=True):
"""
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
"""
errors = {}
if exclude is None:
exclude = []
else:
exclude = list(exclude)
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
get_deferred_fields¶
Return a set containing names of deferred fields for this instance.
View Source
get_preprocessing_torch_model¶
Converts the preprocessing to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_real_concrete_instance_class¶
View Source
get_real_concrete_instance_class_id¶
View Source
get_real_instance¶
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it's real class/type and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:~polymorphic.managers.PolymorphicQuerySet.get_real_instances
to upcast a complete list in a single efficient query.
View Source
def get_real_instance(self):
"""
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the complete object with it's real class/type
and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
to upcast a complete list in a single efficient query.
"""
real_model = self.get_real_instance_class()
if real_model == self.__class__:
return self
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
get_real_instance_class¶
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.
View Source
def get_real_instance_class(self):
"""
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the real class/type of these objects may be
determined using this method.
"""
if self.polymorphic_ctype_id is None:
raise PolymorphicTypeUndefined(
(
"The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
"If you created models outside polymorphic, e.g. through an import or migration, "
"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
).format(self.__class__.__name__, self.pk)
)
# the following line would be the easiest way to do this, but it produces sql queries
# return self.polymorphic_ctype.model_class()
# so we use the following version, which uses the ContentType manager cache.
# Note that model_class() can return None for stale content types;
# when the content type record still exists but no longer refers to an existing model.
model = (
ContentType.objects.db_manager(self._state.db)
.get_for_id(self.polymorphic_ctype_id)
.model_class()
)
# Protect against bad imports (dumpdata without --natural) or other
# issues missing with the ContentType models.
if (
model is not None
and not issubclass(model, self.__class__)
and (
self.__class__._meta.proxy_for_model is None
or not issubclass(model, self.__class__._meta.proxy_for_model)
)
):
raise PolymorphicTypeInvalid(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
)
return model
get_torch_model¶
Converts the model weights to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_training¶
Gets the training associated with the model.
Returns:
Type | Description |
---|---|
models.Training | The training associated with the model. |
View Source
id¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
input_shape¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
is_global_model¶
Checks if the model is a global model.
Returns:
Type | Description |
---|---|
bool | True if the model is a global model, False otherwise. |
View Source
is_local_model¶
Checks if the model is a local model.
Returns:
Type | Description |
---|---|
bool | True if the model is a local model, False otherwise. |
View Source
name¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
pre_save_polymorphic¶
Make sure the polymorphic_ctype
value is correctly set on this model.
View Source
def pre_save_polymorphic(self, using=DEFAULT_DB_ALIAS):
"""
Make sure the ``polymorphic_ctype`` value is correctly set on this model.
"""
# This function may be called manually in special use-cases. When the object
# is saved for the first time, we store its real class in polymorphic_ctype.
# When the object later is retrieved by PolymorphicQuerySet, it uses this
# field to figure out the real class of this object
# (used by PolymorphicQuerySet._get_real_instances)
if not self.polymorphic_ctype_id:
self.polymorphic_ctype = ContentType.objects.db_manager(using).get_for_model(
self, for_concrete_model=False
)
prepare_database_save¶
View Source
preprocessing¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
refresh_from_db¶
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
View Source
def refresh_from_db(self, using=None, fields=None):
"""
Reload field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields
should be an iterable of field attnames. If fields is None, then
all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading
of the field will call this method.
"""
if fields is None:
self._prefetched_objects_cache = {}
else:
prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
for field in fields:
if field in prefetched_objects_cache:
del prefetched_objects_cache[field]
fields.remove(field)
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
"are not allowed in fields." % LOOKUP_SEP
)
hints = {"instance": self}
db_instance_qs = self.__class__._base_manager.db_manager(
using, hints=hints
).filter(pk=self.pk)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [
f.attname
for f in self._meta.concrete_fields
if f.attname not in deferred_fields
]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
round¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
save¶
Calls :meth:pre_save_polymorphic
and saves the model.
View Source
save_base¶
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None
)
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
View Source
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before save. This
is used by fixture loading.
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or update_fields
cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy:
cls = cls._meta.concrete_model
meta = cls._meta
if not meta.auto_created:
pre_save.send(
sender=origin,
instance=self,
raw=raw,
using=using,
update_fields=update_fields,
)
# A transaction isn't needed if one query is issued.
if meta.parents:
context_manager = transaction.atomic(using=using, savepoint=False)
else:
context_manager = transaction.mark_for_rollback_on_error(using=using)
with context_manager:
parent_inserted = False
if not raw:
parent_inserted = self._save_parents(cls, using, update_fields)
updated = self._save_table(
raw,
cls,
force_insert or parent_inserted,
force_update,
using,
update_fields,
)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin,
instance=self,
created=(not updated),
update_fields=update_fields,
raw=raw,
using=using,
)
serializable_value¶
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value.
Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
View Source
def serializable_value(self, field_name):
"""
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's
no Field object with this name on the model, return the model
attribute's value.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
set_preprocessing_torch_model¶
Sets the preprocessing from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
set_torch_model¶
Sets the model weights from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
unique_error_message¶
View Source
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
params = {
"model": self,
"model_class": model_class,
"model_name": capfirst(opts.verbose_name),
"unique_check": unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
params["field_label"] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages["unique"],
code="unique",
params=params,
)
# unique_together
else:
field_labels = [
capfirst(opts.get_field(f).verbose_name) for f in unique_check
]
params["field_labels"] = get_text_list(field_labels, _("and"))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code="unique_together",
params=params,
)
validate_unique¶
Check unique constraints on the model and raise ValidationError if any
failed.
View Source
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
weights¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
LocalModel¶
Model class for local models.
View Source
class LocalModel(Model):
"""
Model class for local models.
"""
base_model: ForeignKey = ForeignKey(GlobalModel, on_delete=CASCADE)
"""Base model of the local model."""
sample_size: IntegerField = IntegerField()
"""Sample size of the local model."""
def get_training(self) -> Optional["models.Training"]:
"""
Gets the training associated with the base model.
Returns:
models.Training: The training associated with the base model.
"""
return models.Training.objects.filter(model=self.base_model).first()
Ancestors (in MRO)¶
- fl_server_core.models.model.Model
- polymorphic.models.PolymorphicModel
- django.db.models.base.Model
Class variables¶
Static methods¶
check¶
View Source
@classmethod
def check(cls, **kwargs):
errors = [
*cls._check_swappable(),
*cls._check_model(),
*cls._check_managers(**kwargs),
]
if not cls._meta.swapped:
databases = kwargs.get("databases") or []
errors += [
*cls._check_fields(**kwargs),
*cls._check_m2m_through_same_relationship(),
*cls._check_long_column_names(databases),
]
clash_errors = (
*cls._check_id_field(),
*cls._check_field_name_clashes(),
*cls._check_model_name_db_lookup_clashes(),
*cls._check_property_name_related_field_accessor_clashes(),
*cls._check_single_primary_key(),
)
errors.extend(clash_errors)
# If there are field name clashes, hide consequent column name
# clashes.
if not clash_errors:
errors.extend(cls._check_column_name_clashes())
errors += [
*cls._check_index_together(),
*cls._check_unique_together(),
*cls._check_indexes(databases),
*cls._check_ordering(),
*cls._check_constraints(databases),
*cls._check_default_pk(),
]
return errors
from_db¶
View Source
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
translate_polymorphic_Q_object¶
View Source
Instance variables¶
Methods¶
clean¶
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
View Source
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
clean_fields¶
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
View Source
def clean_fields(self, exclude=None):
"""
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in f.empty_values:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.error_list
if errors:
raise ValidationError(errors)
date_error_message¶
View Source
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages["unique_for_date"],
code="unique_for_date",
params={
"model": self,
"model_name": capfirst(opts.verbose_name),
"lookup_type": lookup_type,
"field": field_name,
"field_label": capfirst(field.verbose_name),
"date_field": unique_for,
"date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
},
)
delete¶
View Source
def delete(self, using=None, keep_parents=False):
if self.pk is None:
raise ValueError(
"%s object can't be deleted because its %s attribute is set "
"to None." % (self._meta.object_name, self._meta.pk.attname)
)
using = using or router.db_for_write(self.__class__, instance=self)
collector = Collector(using=using)
collector.collect([self], keep_parents=keep_parents)
return collector.delete()
full_clean¶
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
View Source
def full_clean(self, exclude=None, validate_unique=True):
"""
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
"""
errors = {}
if exclude is None:
exclude = []
else:
exclude = list(exclude)
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
get_deferred_fields¶
Return a set containing names of deferred fields for this instance.
View Source
get_real_concrete_instance_class¶
View Source
get_real_concrete_instance_class_id¶
View Source
get_real_instance¶
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it's real class/type and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:~polymorphic.managers.PolymorphicQuerySet.get_real_instances
to upcast a complete list in a single efficient query.
View Source
def get_real_instance(self):
"""
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the complete object with it's real class/type
and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
to upcast a complete list in a single efficient query.
"""
real_model = self.get_real_instance_class()
if real_model == self.__class__:
return self
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
get_real_instance_class¶
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.
View Source
def get_real_instance_class(self):
"""
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the real class/type of these objects may be
determined using this method.
"""
if self.polymorphic_ctype_id is None:
raise PolymorphicTypeUndefined(
(
"The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
"If you created models outside polymorphic, e.g. through an import or migration, "
"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
).format(self.__class__.__name__, self.pk)
)
# the following line would be the easiest way to do this, but it produces sql queries
# return self.polymorphic_ctype.model_class()
# so we use the following version, which uses the ContentType manager cache.
# Note that model_class() can return None for stale content types;
# when the content type record still exists but no longer refers to an existing model.
model = (
ContentType.objects.db_manager(self._state.db)
.get_for_id(self.polymorphic_ctype_id)
.model_class()
)
# Protect against bad imports (dumpdata without --natural) or other
# issues missing with the ContentType models.
if (
model is not None
and not issubclass(model, self.__class__)
and (
self.__class__._meta.proxy_for_model is None
or not issubclass(model, self.__class__._meta.proxy_for_model)
)
):
raise PolymorphicTypeInvalid(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
)
return model
get_torch_model¶
Converts the model weights to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_training¶
Gets the training associated with the base model.
Returns:
Type | Description |
---|---|
models.Training | The training associated with the base model. |
View Source
id¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
is_global_model¶
Checks if the model is a global model.
Returns:
Type | Description |
---|---|
bool | True if the model is a global model, False otherwise. |
View Source
is_local_model¶
Checks if the model is a local model.
Returns:
Type | Description |
---|---|
bool | True if the model is a local model, False otherwise. |
View Source
pre_save_polymorphic¶
Make sure the polymorphic_ctype
value is correctly set on this model.
View Source
def pre_save_polymorphic(self, using=DEFAULT_DB_ALIAS):
"""
Make sure the ``polymorphic_ctype`` value is correctly set on this model.
"""
# This function may be called manually in special use-cases. When the object
# is saved for the first time, we store its real class in polymorphic_ctype.
# When the object later is retrieved by PolymorphicQuerySet, it uses this
# field to figure out the real class of this object
# (used by PolymorphicQuerySet._get_real_instances)
if not self.polymorphic_ctype_id:
self.polymorphic_ctype = ContentType.objects.db_manager(using).get_for_model(
self, for_concrete_model=False
)
prepare_database_save¶
View Source
refresh_from_db¶
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
View Source
def refresh_from_db(self, using=None, fields=None):
"""
Reload field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields
should be an iterable of field attnames. If fields is None, then
all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading
of the field will call this method.
"""
if fields is None:
self._prefetched_objects_cache = {}
else:
prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
for field in fields:
if field in prefetched_objects_cache:
del prefetched_objects_cache[field]
fields.remove(field)
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
"are not allowed in fields." % LOOKUP_SEP
)
hints = {"instance": self}
db_instance_qs = self.__class__._base_manager.db_manager(
using, hints=hints
).filter(pk=self.pk)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [
f.attname
for f in self._meta.concrete_fields
if f.attname not in deferred_fields
]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
round¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
sample_size¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
save¶
Calls :meth:pre_save_polymorphic
and saves the model.
View Source
save_base¶
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None
)
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
View Source
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before save. This
is used by fixture loading.
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or update_fields
cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy:
cls = cls._meta.concrete_model
meta = cls._meta
if not meta.auto_created:
pre_save.send(
sender=origin,
instance=self,
raw=raw,
using=using,
update_fields=update_fields,
)
# A transaction isn't needed if one query is issued.
if meta.parents:
context_manager = transaction.atomic(using=using, savepoint=False)
else:
context_manager = transaction.mark_for_rollback_on_error(using=using)
with context_manager:
parent_inserted = False
if not raw:
parent_inserted = self._save_parents(cls, using, update_fields)
updated = self._save_table(
raw,
cls,
force_insert or parent_inserted,
force_update,
using,
update_fields,
)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin,
instance=self,
created=(not updated),
update_fields=update_fields,
raw=raw,
using=using,
)
serializable_value¶
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value.
Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
View Source
def serializable_value(self, field_name):
"""
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's
no Field object with this name on the model, return the model
attribute's value.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
set_torch_model¶
Sets the model weights from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
unique_error_message¶
View Source
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
params = {
"model": self,
"model_class": model_class,
"model_name": capfirst(opts.verbose_name),
"unique_check": unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
params["field_label"] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages["unique"],
code="unique",
params=params,
)
# unique_together
else:
field_labels = [
capfirst(opts.get_field(f).verbose_name) for f in unique_check
]
params["field_labels"] = get_text_list(field_labels, _("and"))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code="unique_together",
params=params,
)
validate_unique¶
Check unique constraints on the model and raise ValidationError if any
failed.
View Source
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
weights¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
MeanModel¶
Model class for mean models.
View Source
class MeanModel(GlobalModel):
"""
Model class for mean models.
"""
models: ManyToManyField = ManyToManyField(GlobalModel, related_name="mean_models")
"""Models of the mean model."""
def get_torch_model(self) -> torch.nn.Module:
"""
Converts the models to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
torch_models: List[torch.nn.Module] = [model.get_torch_model() for model in self.models.all()]
model = MeanModule(torch_models)
if all(is_torchscript_instance(m) for m in torch_models):
return torch.jit.script(model)
return model
def set_torch_model(self, value: torch.nn.Module):
"""
Sets the models from a PyTorch model.
Args:
value (torch.nn.Module): The PyTorch model.
"""
raise NotImplementedError()
Ancestors (in MRO)¶
- fl_server_core.models.model.GlobalModel
- fl_server_core.models.model.Model
- polymorphic.models.PolymorphicModel
- django.db.models.base.Model
Class variables¶
Static methods¶
check¶
View Source
@classmethod
def check(cls, **kwargs):
errors = [
*cls._check_swappable(),
*cls._check_model(),
*cls._check_managers(**kwargs),
]
if not cls._meta.swapped:
databases = kwargs.get("databases") or []
errors += [
*cls._check_fields(**kwargs),
*cls._check_m2m_through_same_relationship(),
*cls._check_long_column_names(databases),
]
clash_errors = (
*cls._check_id_field(),
*cls._check_field_name_clashes(),
*cls._check_model_name_db_lookup_clashes(),
*cls._check_property_name_related_field_accessor_clashes(),
*cls._check_single_primary_key(),
)
errors.extend(clash_errors)
# If there are field name clashes, hide consequent column name
# clashes.
if not clash_errors:
errors.extend(cls._check_column_name_clashes())
errors += [
*cls._check_index_together(),
*cls._check_unique_together(),
*cls._check_indexes(databases),
*cls._check_ordering(),
*cls._check_constraints(databases),
*cls._check_default_pk(),
]
return errors
from_db¶
View Source
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
translate_polymorphic_Q_object¶
View Source
Instance variables¶
Methods¶
clean¶
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
View Source
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
clean_fields¶
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
View Source
def clean_fields(self, exclude=None):
"""
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in f.empty_values:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.error_list
if errors:
raise ValidationError(errors)
date_error_message¶
View Source
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages["unique_for_date"],
code="unique_for_date",
params={
"model": self,
"model_name": capfirst(opts.verbose_name),
"lookup_type": lookup_type,
"field": field_name,
"field_label": capfirst(field.verbose_name),
"date_field": unique_for,
"date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
},
)
delete¶
View Source
def delete(self, using=None, keep_parents=False):
if self.pk is None:
raise ValueError(
"%s object can't be deleted because its %s attribute is set "
"to None." % (self._meta.object_name, self._meta.pk.attname)
)
using = using or router.db_for_write(self.__class__, instance=self)
collector = Collector(using=using)
collector.collect([self], keep_parents=keep_parents)
return collector.delete()
description¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
full_clean¶
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
View Source
def full_clean(self, exclude=None, validate_unique=True):
"""
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
"""
errors = {}
if exclude is None:
exclude = []
else:
exclude = list(exclude)
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
get_deferred_fields¶
Return a set containing names of deferred fields for this instance.
View Source
get_preprocessing_torch_model¶
Converts the preprocessing to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_real_concrete_instance_class¶
View Source
get_real_concrete_instance_class_id¶
View Source
get_real_instance¶
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it's real class/type and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:~polymorphic.managers.PolymorphicQuerySet.get_real_instances
to upcast a complete list in a single efficient query.
View Source
def get_real_instance(self):
"""
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the complete object with it's real class/type
and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
to upcast a complete list in a single efficient query.
"""
real_model = self.get_real_instance_class()
if real_model == self.__class__:
return self
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
get_real_instance_class¶
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.
View Source
def get_real_instance_class(self):
"""
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the real class/type of these objects may be
determined using this method.
"""
if self.polymorphic_ctype_id is None:
raise PolymorphicTypeUndefined(
(
"The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
"If you created models outside polymorphic, e.g. through an import or migration, "
"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
).format(self.__class__.__name__, self.pk)
)
# the following line would be the easiest way to do this, but it produces sql queries
# return self.polymorphic_ctype.model_class()
# so we use the following version, which uses the ContentType manager cache.
# Note that model_class() can return None for stale content types;
# when the content type record still exists but no longer refers to an existing model.
model = (
ContentType.objects.db_manager(self._state.db)
.get_for_id(self.polymorphic_ctype_id)
.model_class()
)
# Protect against bad imports (dumpdata without --natural) or other
# issues missing with the ContentType models.
if (
model is not None
and not issubclass(model, self.__class__)
and (
self.__class__._meta.proxy_for_model is None
or not issubclass(model, self.__class__._meta.proxy_for_model)
)
):
raise PolymorphicTypeInvalid(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
)
return model
get_torch_model¶
Converts the models to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
def get_torch_model(self) -> torch.nn.Module:
"""
Converts the models to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
torch_models: List[torch.nn.Module] = [model.get_torch_model() for model in self.models.all()]
model = MeanModule(torch_models)
if all(is_torchscript_instance(m) for m in torch_models):
return torch.jit.script(model)
return model
get_training¶
Gets the training associated with the model.
Returns:
Type | Description |
---|---|
models.Training | The training associated with the model. |
View Source
id¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
input_shape¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
is_global_model¶
Checks if the model is a global model.
Returns:
Type | Description |
---|---|
bool | True if the model is a global model, False otherwise. |
View Source
is_local_model¶
Checks if the model is a local model.
Returns:
Type | Description |
---|---|
bool | True if the model is a local model, False otherwise. |
View Source
name¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
pre_save_polymorphic¶
Make sure the polymorphic_ctype
value is correctly set on this model.
View Source
def pre_save_polymorphic(self, using=DEFAULT_DB_ALIAS):
"""
Make sure the ``polymorphic_ctype`` value is correctly set on this model.
"""
# This function may be called manually in special use-cases. When the object
# is saved for the first time, we store its real class in polymorphic_ctype.
# When the object later is retrieved by PolymorphicQuerySet, it uses this
# field to figure out the real class of this object
# (used by PolymorphicQuerySet._get_real_instances)
if not self.polymorphic_ctype_id:
self.polymorphic_ctype = ContentType.objects.db_manager(using).get_for_model(
self, for_concrete_model=False
)
prepare_database_save¶
View Source
preprocessing¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
refresh_from_db¶
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
View Source
def refresh_from_db(self, using=None, fields=None):
"""
Reload field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields
should be an iterable of field attnames. If fields is None, then
all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading
of the field will call this method.
"""
if fields is None:
self._prefetched_objects_cache = {}
else:
prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
for field in fields:
if field in prefetched_objects_cache:
del prefetched_objects_cache[field]
fields.remove(field)
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
"are not allowed in fields." % LOOKUP_SEP
)
hints = {"instance": self}
db_instance_qs = self.__class__._base_manager.db_manager(
using, hints=hints
).filter(pk=self.pk)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [
f.attname
for f in self._meta.concrete_fields
if f.attname not in deferred_fields
]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
round¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
save¶
Calls :meth:pre_save_polymorphic
and saves the model.
View Source
save_base¶
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None
)
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
View Source
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before save. This
is used by fixture loading.
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or update_fields
cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy:
cls = cls._meta.concrete_model
meta = cls._meta
if not meta.auto_created:
pre_save.send(
sender=origin,
instance=self,
raw=raw,
using=using,
update_fields=update_fields,
)
# A transaction isn't needed if one query is issued.
if meta.parents:
context_manager = transaction.atomic(using=using, savepoint=False)
else:
context_manager = transaction.mark_for_rollback_on_error(using=using)
with context_manager:
parent_inserted = False
if not raw:
parent_inserted = self._save_parents(cls, using, update_fields)
updated = self._save_table(
raw,
cls,
force_insert or parent_inserted,
force_update,
using,
update_fields,
)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin,
instance=self,
created=(not updated),
update_fields=update_fields,
raw=raw,
using=using,
)
serializable_value¶
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value.
Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
View Source
def serializable_value(self, field_name):
"""
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's
no Field object with this name on the model, return the model
attribute's value.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
set_preprocessing_torch_model¶
Sets the preprocessing from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
set_torch_model¶
Sets the models from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
unique_error_message¶
View Source
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
params = {
"model": self,
"model_class": model_class,
"model_name": capfirst(opts.verbose_name),
"unique_check": unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
params["field_label"] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages["unique"],
code="unique",
params=params,
)
# unique_together
else:
field_labels = [
capfirst(opts.get_field(f).verbose_name) for f in unique_check
]
params["field_labels"] = get_text_list(field_labels, _("and"))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code="unique_together",
params=params,
)
validate_unique¶
Check unique constraints on the model and raise ValidationError if any
failed.
View Source
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
weights¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
MeanModule¶
PyTorch module for mean models.
View Source
class MeanModule(Module):
"""
PyTorch module for mean models.
"""
def __init__(self, models: Sequence[torch.nn.Module]):
"""
Initializes the mean models.
Args:
models (Sequence[torch.nn.Module]): The models of the mean model.
"""
super().__init__()
self.models = models
"""Models of the mean model."""
def forward(self, input: Tensor) -> Tensor:
"""
Forward pass of the mean models.
Args:
input (Tensor): The input tensor.
Returns:
Tensor: The output tensor.
"""
return torch.stack([model(input) for model in self.models], dim=0).mean(dim=0)
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¶
Forward pass of the mean models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input | Tensor | The input tensor. | None |
Returns:
Type | Description |
---|---|
Tensor | The output tensor. |
View Source
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_()
Model¶
Base model class for all types of model models.
View Source
class Model(PolymorphicModel):
"""
Base model class for all types of model models.
"""
id: UUIDField = UUIDField(primary_key=True, editable=False, default=uuid4)
"""Unique identifier for the model."""
owner: ForeignKey = ForeignKey(User, on_delete=CASCADE)
"""User who owns the model."""
round: IntegerField = IntegerField()
"""Round number of the model."""
weights: BinaryField = BinaryField()
"""Weights of the model."""
def is_global_model(self):
"""
Checks if the model is a global model.
Returns:
bool: True if the model is a global model, False otherwise.
"""
return isinstance(self, GlobalModel)
def is_local_model(self):
"""
Checks if the model is a local model.
Returns:
bool: True if the model is a local model, False otherwise.
"""
return isinstance(self, LocalModel)
def get_torch_model(self) -> torch.nn.Module:
"""
Converts the model weights to a PyTorch model.
Returns:
torch.nn.Module: The PyTorch model.
"""
return to_torch_module(self.weights)
def set_torch_model(self, value: torch.nn.Module):
"""
Sets the model weights from a PyTorch model.
Args:
value (torch.nn.Module): The PyTorch model.
"""
self.weights = from_torch_module(value)
def get_training(self) -> Optional["models.Training"]:
"""
Gets the training associated with the model.
Returns:
models.Training: The training associated with the model.
"""
return models.Training.objects.filter(model=self).first()
Ancestors (in MRO)¶
- polymorphic.models.PolymorphicModel
- django.db.models.base.Model
Descendants¶
- fl_server_core.models.model.GlobalModel
- fl_server_core.models.model.LocalModel
Class variables¶
Static methods¶
check¶
View Source
@classmethod
def check(cls, **kwargs):
errors = [
*cls._check_swappable(),
*cls._check_model(),
*cls._check_managers(**kwargs),
]
if not cls._meta.swapped:
databases = kwargs.get("databases") or []
errors += [
*cls._check_fields(**kwargs),
*cls._check_m2m_through_same_relationship(),
*cls._check_long_column_names(databases),
]
clash_errors = (
*cls._check_id_field(),
*cls._check_field_name_clashes(),
*cls._check_model_name_db_lookup_clashes(),
*cls._check_property_name_related_field_accessor_clashes(),
*cls._check_single_primary_key(),
)
errors.extend(clash_errors)
# If there are field name clashes, hide consequent column name
# clashes.
if not clash_errors:
errors.extend(cls._check_column_name_clashes())
errors += [
*cls._check_index_together(),
*cls._check_unique_together(),
*cls._check_indexes(databases),
*cls._check_ordering(),
*cls._check_constraints(databases),
*cls._check_default_pk(),
]
return errors
from_db¶
View Source
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
translate_polymorphic_Q_object¶
View Source
Instance variables¶
Methods¶
clean¶
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
View Source
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
clean_fields¶
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
View Source
def clean_fields(self, exclude=None):
"""
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in f.empty_values:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.error_list
if errors:
raise ValidationError(errors)
date_error_message¶
View Source
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages["unique_for_date"],
code="unique_for_date",
params={
"model": self,
"model_name": capfirst(opts.verbose_name),
"lookup_type": lookup_type,
"field": field_name,
"field_label": capfirst(field.verbose_name),
"date_field": unique_for,
"date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
},
)
delete¶
View Source
def delete(self, using=None, keep_parents=False):
if self.pk is None:
raise ValueError(
"%s object can't be deleted because its %s attribute is set "
"to None." % (self._meta.object_name, self._meta.pk.attname)
)
using = using or router.db_for_write(self.__class__, instance=self)
collector = Collector(using=using)
collector.collect([self], keep_parents=keep_parents)
return collector.delete()
full_clean¶
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
View Source
def full_clean(self, exclude=None, validate_unique=True):
"""
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
"""
errors = {}
if exclude is None:
exclude = []
else:
exclude = list(exclude)
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
get_deferred_fields¶
Return a set containing names of deferred fields for this instance.
View Source
get_real_concrete_instance_class¶
View Source
get_real_concrete_instance_class_id¶
View Source
get_real_instance¶
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it's real class/type and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:~polymorphic.managers.PolymorphicQuerySet.get_real_instances
to upcast a complete list in a single efficient query.
View Source
def get_real_instance(self):
"""
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the complete object with it's real class/type
and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
to upcast a complete list in a single efficient query.
"""
real_model = self.get_real_instance_class()
if real_model == self.__class__:
return self
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
get_real_instance_class¶
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.
View Source
def get_real_instance_class(self):
"""
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the real class/type of these objects may be
determined using this method.
"""
if self.polymorphic_ctype_id is None:
raise PolymorphicTypeUndefined(
(
"The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
"If you created models outside polymorphic, e.g. through an import or migration, "
"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
).format(self.__class__.__name__, self.pk)
)
# the following line would be the easiest way to do this, but it produces sql queries
# return self.polymorphic_ctype.model_class()
# so we use the following version, which uses the ContentType manager cache.
# Note that model_class() can return None for stale content types;
# when the content type record still exists but no longer refers to an existing model.
model = (
ContentType.objects.db_manager(self._state.db)
.get_for_id(self.polymorphic_ctype_id)
.model_class()
)
# Protect against bad imports (dumpdata without --natural) or other
# issues missing with the ContentType models.
if (
model is not None
and not issubclass(model, self.__class__)
and (
self.__class__._meta.proxy_for_model is None
or not issubclass(model, self.__class__._meta.proxy_for_model)
)
):
raise PolymorphicTypeInvalid(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
)
return model
get_torch_model¶
Converts the model weights to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_training¶
Gets the training associated with the model.
Returns:
Type | Description |
---|---|
models.Training | The training associated with the model. |
View Source
id¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
is_global_model¶
Checks if the model is a global model.
Returns:
Type | Description |
---|---|
bool | True if the model is a global model, False otherwise. |
View Source
is_local_model¶
Checks if the model is a local model.
Returns:
Type | Description |
---|---|
bool | True if the model is a local model, False otherwise. |
View Source
pre_save_polymorphic¶
Make sure the polymorphic_ctype
value is correctly set on this model.
View Source
def pre_save_polymorphic(self, using=DEFAULT_DB_ALIAS):
"""
Make sure the ``polymorphic_ctype`` value is correctly set on this model.
"""
# This function may be called manually in special use-cases. When the object
# is saved for the first time, we store its real class in polymorphic_ctype.
# When the object later is retrieved by PolymorphicQuerySet, it uses this
# field to figure out the real class of this object
# (used by PolymorphicQuerySet._get_real_instances)
if not self.polymorphic_ctype_id:
self.polymorphic_ctype = ContentType.objects.db_manager(using).get_for_model(
self, for_concrete_model=False
)
prepare_database_save¶
View Source
refresh_from_db¶
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
View Source
def refresh_from_db(self, using=None, fields=None):
"""
Reload field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields
should be an iterable of field attnames. If fields is None, then
all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading
of the field will call this method.
"""
if fields is None:
self._prefetched_objects_cache = {}
else:
prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
for field in fields:
if field in prefetched_objects_cache:
del prefetched_objects_cache[field]
fields.remove(field)
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
"are not allowed in fields." % LOOKUP_SEP
)
hints = {"instance": self}
db_instance_qs = self.__class__._base_manager.db_manager(
using, hints=hints
).filter(pk=self.pk)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [
f.attname
for f in self._meta.concrete_fields
if f.attname not in deferred_fields
]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
round¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
save¶
Calls :meth:pre_save_polymorphic
and saves the model.
View Source
save_base¶
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None
)
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
View Source
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before save. This
is used by fixture loading.
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or update_fields
cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy:
cls = cls._meta.concrete_model
meta = cls._meta
if not meta.auto_created:
pre_save.send(
sender=origin,
instance=self,
raw=raw,
using=using,
update_fields=update_fields,
)
# A transaction isn't needed if one query is issued.
if meta.parents:
context_manager = transaction.atomic(using=using, savepoint=False)
else:
context_manager = transaction.mark_for_rollback_on_error(using=using)
with context_manager:
parent_inserted = False
if not raw:
parent_inserted = self._save_parents(cls, using, update_fields)
updated = self._save_table(
raw,
cls,
force_insert or parent_inserted,
force_update,
using,
update_fields,
)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin,
instance=self,
created=(not updated),
update_fields=update_fields,
raw=raw,
using=using,
)
serializable_value¶
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value.
Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
View Source
def serializable_value(self, field_name):
"""
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's
no Field object with this name on the model, return the model
attribute's value.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
set_torch_model¶
Sets the model weights from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
unique_error_message¶
View Source
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
params = {
"model": self,
"model_class": model_class,
"model_name": capfirst(opts.verbose_name),
"unique_check": unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
params["field_label"] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages["unique"],
code="unique",
params=params,
)
# unique_together
else:
field_labels = [
capfirst(opts.get_field(f).verbose_name) for f in unique_check
]
params["field_labels"] = get_text_list(field_labels, _("and"))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code="unique_together",
params=params,
)
validate_unique¶
Check unique constraints on the model and raise ValidationError if any
failed.
View Source
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
weights¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
SWAGModel¶
Model class for SWAG models.
View Source
class SWAGModel(GlobalModel):
"""
Model class for SWAG models.
"""
swag_first_moment: BinaryField = BinaryField()
"""First moment of the SWAG model."""
swag_second_moment: BinaryField = BinaryField()
"""Second moment of the SWAG model."""
@property
def first_moment(self) -> Tensor:
"""
Gets the first moment of the SWAG model.
Returns:
Tensor: The first moment of the SWAG model.
"""
return to_torch_tensor(self.swag_first_moment)
@first_moment.setter
def first_moment(self, value: Tensor):
"""
Sets the first moment of the SWAG model.
Args:
value (Tensor): The first moment of the SWAG model.
"""
self.swag_first_moment = from_torch_tensor(value)
@property
def second_moment(self) -> Tensor:
"""
Gets the second moment of the SWAG model.
Returns:
Tensor: The second moment of the SWAG model.
"""
return to_torch_tensor(self.swag_second_moment)
@second_moment.setter
def second_moment(self, value: Tensor):
"""
Sets the second moment of the SWAG model.
Args:
value (Tensor): The second moment of the SWAG model.
"""
self.swag_second_moment = from_torch_tensor(value)
Ancestors (in MRO)¶
- fl_server_core.models.model.GlobalModel
- fl_server_core.models.model.Model
- polymorphic.models.PolymorphicModel
- django.db.models.base.Model
Class variables¶
Static methods¶
check¶
View Source
@classmethod
def check(cls, **kwargs):
errors = [
*cls._check_swappable(),
*cls._check_model(),
*cls._check_managers(**kwargs),
]
if not cls._meta.swapped:
databases = kwargs.get("databases") or []
errors += [
*cls._check_fields(**kwargs),
*cls._check_m2m_through_same_relationship(),
*cls._check_long_column_names(databases),
]
clash_errors = (
*cls._check_id_field(),
*cls._check_field_name_clashes(),
*cls._check_model_name_db_lookup_clashes(),
*cls._check_property_name_related_field_accessor_clashes(),
*cls._check_single_primary_key(),
)
errors.extend(clash_errors)
# If there are field name clashes, hide consequent column name
# clashes.
if not clash_errors:
errors.extend(cls._check_column_name_clashes())
errors += [
*cls._check_index_together(),
*cls._check_unique_together(),
*cls._check_indexes(databases),
*cls._check_ordering(),
*cls._check_constraints(databases),
*cls._check_default_pk(),
]
return errors
from_db¶
View Source
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
translate_polymorphic_Q_object¶
View Source
Instance variables¶
Gets the first moment of the SWAG model.
Gets the second moment of the SWAG model.
Methods¶
clean¶
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
View Source
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
clean_fields¶
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
View Source
def clean_fields(self, exclude=None):
"""
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in f.empty_values:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.error_list
if errors:
raise ValidationError(errors)
date_error_message¶
View Source
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages["unique_for_date"],
code="unique_for_date",
params={
"model": self,
"model_name": capfirst(opts.verbose_name),
"lookup_type": lookup_type,
"field": field_name,
"field_label": capfirst(field.verbose_name),
"date_field": unique_for,
"date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
},
)
delete¶
View Source
def delete(self, using=None, keep_parents=False):
if self.pk is None:
raise ValueError(
"%s object can't be deleted because its %s attribute is set "
"to None." % (self._meta.object_name, self._meta.pk.attname)
)
using = using or router.db_for_write(self.__class__, instance=self)
collector = Collector(using=using)
collector.collect([self], keep_parents=keep_parents)
return collector.delete()
description¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
full_clean¶
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
View Source
def full_clean(self, exclude=None, validate_unique=True):
"""
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
"""
errors = {}
if exclude is None:
exclude = []
else:
exclude = list(exclude)
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
get_deferred_fields¶
Return a set containing names of deferred fields for this instance.
View Source
get_preprocessing_torch_model¶
Converts the preprocessing to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_real_concrete_instance_class¶
View Source
get_real_concrete_instance_class_id¶
View Source
get_real_instance¶
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it's real class/type and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:~polymorphic.managers.PolymorphicQuerySet.get_real_instances
to upcast a complete list in a single efficient query.
View Source
def get_real_instance(self):
"""
Upcast an object to it's actual type.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the complete object with it's real class/type
and all fields may be retrieved with this method.
.. note::
Each method call executes one db query (if necessary).
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
to upcast a complete list in a single efficient query.
"""
real_model = self.get_real_instance_class()
if real_model == self.__class__:
return self
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
get_real_instance_class¶
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.
View Source
def get_real_instance_class(self):
"""
Return the actual model type of the object.
If a non-polymorphic manager (like base_objects) has been used to
retrieve objects, then the real class/type of these objects may be
determined using this method.
"""
if self.polymorphic_ctype_id is None:
raise PolymorphicTypeUndefined(
(
"The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
"If you created models outside polymorphic, e.g. through an import or migration, "
"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
).format(self.__class__.__name__, self.pk)
)
# the following line would be the easiest way to do this, but it produces sql queries
# return self.polymorphic_ctype.model_class()
# so we use the following version, which uses the ContentType manager cache.
# Note that model_class() can return None for stale content types;
# when the content type record still exists but no longer refers to an existing model.
model = (
ContentType.objects.db_manager(self._state.db)
.get_for_id(self.polymorphic_ctype_id)
.model_class()
)
# Protect against bad imports (dumpdata without --natural) or other
# issues missing with the ContentType models.
if (
model is not None
and not issubclass(model, self.__class__)
and (
self.__class__._meta.proxy_for_model is None
or not issubclass(model, self.__class__._meta.proxy_for_model)
)
):
raise PolymorphicTypeInvalid(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
)
return model
get_torch_model¶
Converts the model weights to a PyTorch model.
Returns:
Type | Description |
---|---|
torch.nn.Module | The PyTorch model. |
View Source
get_training¶
Gets the training associated with the model.
Returns:
Type | Description |
---|---|
models.Training | The training associated with the model. |
View Source
id¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
input_shape¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
is_global_model¶
Checks if the model is a global model.
Returns:
Type | Description |
---|---|
bool | True if the model is a global model, False otherwise. |
View Source
is_local_model¶
Checks if the model is a local model.
Returns:
Type | Description |
---|---|
bool | True if the model is a local model, False otherwise. |
View Source
name¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
pre_save_polymorphic¶
Make sure the polymorphic_ctype
value is correctly set on this model.
View Source
def pre_save_polymorphic(self, using=DEFAULT_DB_ALIAS):
"""
Make sure the ``polymorphic_ctype`` value is correctly set on this model.
"""
# This function may be called manually in special use-cases. When the object
# is saved for the first time, we store its real class in polymorphic_ctype.
# When the object later is retrieved by PolymorphicQuerySet, it uses this
# field to figure out the real class of this object
# (used by PolymorphicQuerySet._get_real_instances)
if not self.polymorphic_ctype_id:
self.polymorphic_ctype = ContentType.objects.db_manager(using).get_for_model(
self, for_concrete_model=False
)
prepare_database_save¶
View Source
preprocessing¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
refresh_from_db¶
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
View Source
def refresh_from_db(self, using=None, fields=None):
"""
Reload field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields
should be an iterable of field attnames. If fields is None, then
all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading
of the field will call this method.
"""
if fields is None:
self._prefetched_objects_cache = {}
else:
prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
for field in fields:
if field in prefetched_objects_cache:
del prefetched_objects_cache[field]
fields.remove(field)
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
"are not allowed in fields." % LOOKUP_SEP
)
hints = {"instance": self}
db_instance_qs = self.__class__._base_manager.db_manager(
using, hints=hints
).filter(pk=self.pk)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [
f.attname
for f in self._meta.concrete_fields
if f.attname not in deferred_fields
]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
round¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
save¶
Calls :meth:pre_save_polymorphic
and saves the model.
View Source
save_base¶
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None
)
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
View Source
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before save. This
is used by fixture loading.
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or update_fields
cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy:
cls = cls._meta.concrete_model
meta = cls._meta
if not meta.auto_created:
pre_save.send(
sender=origin,
instance=self,
raw=raw,
using=using,
update_fields=update_fields,
)
# A transaction isn't needed if one query is issued.
if meta.parents:
context_manager = transaction.atomic(using=using, savepoint=False)
else:
context_manager = transaction.mark_for_rollback_on_error(using=using)
with context_manager:
parent_inserted = False
if not raw:
parent_inserted = self._save_parents(cls, using, update_fields)
updated = self._save_table(
raw,
cls,
force_insert or parent_inserted,
force_update,
using,
update_fields,
)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin,
instance=self,
created=(not updated),
update_fields=update_fields,
raw=raw,
using=using,
)
serializable_value¶
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value.
Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
View Source
def serializable_value(self, field_name):
"""
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's
no Field object with this name on the model, return the model
attribute's value.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
set_preprocessing_torch_model¶
Sets the preprocessing from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
set_torch_model¶
Sets the model weights from a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value | torch.nn.Module | The PyTorch model. | None |
View Source
swag_first_moment¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
swag_second_moment¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
unique_error_message¶
View Source
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
params = {
"model": self,
"model_class": model_class,
"model_name": capfirst(opts.verbose_name),
"unique_check": unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
params["field_label"] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages["unique"],
code="unique",
params=params,
)
# unique_together
else:
field_labels = [
capfirst(opts.get_field(f).verbose_name) for f in unique_check
]
params["field_labels"] = get_text_list(field_labels, _("and"))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code="unique_together",
params=params,
)
validate_unique¶
Check unique constraints on the model and raise ValidationError if any
failed.
View Source
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
weights¶
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.