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.0.tar.gz (15.1 kB view details)

Uploaded Source

File details

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

File metadata

  • Download URL: dconstruct-1.0.0.tar.gz
  • Upload date:
  • Size: 15.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.11.7

File hashes

Hashes for dconstruct-1.0.0.tar.gz
Algorithm Hash digest
SHA256 6f0686a968d4bfeb97775e9cc90e883f075c542e5a6edfd91b12e03f12b576e5
MD5 75411daafc7c9a573abba0708e290ae9
BLAKE2b-256 71b5ad348bd9f61d3115c53e5ff34c86dee45830689830006e85746413dd5127

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