Skip to main content

Extremely simple way to build objects from a dictionary specification, recursively.

Project description

dconstruct

Extremely simple way to build objects from a dictionary specification, recursively.

Contains one main function, construct, which takes a type dispatch dictionary and a dictionary to construct an object from, and returns the object.

Basic Example

from dconstruct import construct

def create_model(spec):
    return construct(
        dict(Conv1d=torch.nn.Conv1d, Linear=torch.nn.Linear),
        spec,
        device='cpu'
    )

This function creates a model from a specification dictionary. For example, the following specification:

spec = {
    'type': 'Conv1d',
    'in_channels': 1,
    'out_channels': 16,
    'kernel_size': 3
}
create_model(spec)

Will create a torch.nn.Conv1d object with the specified parameters. The device='cpu' argument is passed to the constructor, but the specification dictionary can override it.

Recursive Example

If we want to support Sequential models, we can use the construct function recursively:

def create_model(spec):
    return construct(
        dict(
            Conv1d=torch.nn.Conv1d,
            Linear=torch.nn.Linear,
            Sequential=lambda subspecs: torch.nn.Sequential(*[
                create_model(subspec) for subspec in subspecs
            ]),
        ),
        spec,
        device='cpu'
    )

Now we can create a model like this:

spec = {
    'type': 'Sequential',
    'subspecs': [
        {
            'type': 'Conv1d',
            'in_channels': 1,
            'out_channels': 16,
            'kernel_size': 3
        },
        {
            'type': 'Linear',
            'in_features': 16,
            'out_features': 10
        }
    ]
}
create_model(spec)

This will create a torch.nn.Sequential object with the specified submodules.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dconstruct-1.0.1.tar.gz (15.2 kB view details)

Uploaded Source

File details

Details for the file dconstruct-1.0.1.tar.gz.

File metadata

  • Download URL: dconstruct-1.0.1.tar.gz
  • Upload date:
  • Size: 15.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for dconstruct-1.0.1.tar.gz
Algorithm Hash digest
SHA256 a3e40ba902ce959d5dffea010b4bf162be53ef066be87d27bcc9d49798636559
MD5 169b3ce16131c5f48c6a50ef94e2036e
BLAKE2b-256 a6cc1eda5de10e75f1e3a73636e1b984e974e5406469a4a72dbe4603c62efee0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page