Architecture Recipes

Architecture Recipes: Declarative model definitions.

Recipes allow defining model architectures using human-readable strings and dictionaries, similar to a “cooking recipe”.

v2.1 Features:
  • YAML recipe loading with validation

  • Recipe inheritance (extends)

  • Macro expansion (@macro)

  • Hybrid backbone support

Example

>>> from torchvision_customizer.recipe import Recipe, build_recipe
>>> my_recipe = Recipe(
...     stem="conv(64, kernel=7, stride=2)",
...     stages=[
...         "residual(64) x 2",
...         "residual(128) x 2 | downsample",
...         "residual(256) x 2 | downsample",
...     ],
...     head="linear(1000)"
... )
>>> model = build_recipe(my_recipe)

# v2.1: Load from YAML >>> from torchvision_customizer.recipe import load_yaml_recipe >>> model = load_yaml_recipe(“my_model.yaml”)

class Recipe(stem: str | Dict[str, Any], stages: List[str | Dict[str, Any]], head: str | Dict[str, Any], name: str = 'CustomModel', input_shape: tuple = (3, 224, 224))[source]

Bases: object

Architecture Recipe definition.

A declarative blueprint for a neural network architecture.

Parameters:
  • stem – Stem definition string or dict (e.g., “conv(64, k=7, s=2)”)

  • stages – List of stage definitions (e.g., [“residual(64) x 3”])

  • head – Head definition string or dict (e.g., “linear(1000)”)

  • name – Optional name for the architecture

  • input_shape – Expected input shape (C, H, W)

classmethod from_dict(data: Dict[str, Any]) Recipe[source]

Create from dictionary.

classmethod from_yaml(path: str) Recipe[source]

Load from YAML file.

input_shape: tuple = (3, 224, 224)
name: str = 'CustomModel'
to_dict() Dict[str, Any][source]

Convert to dictionary.

stem: str | Dict[str, Any]
stages: List[str | Dict[str, Any]]
head: str | Dict[str, Any]
build_recipe(recipe: Recipe) VisionModel[source]

Build a model from a Recipe object.

Parameters:

recipe – Recipe definition

Returns:

Built VisionModel

build_from_config(config: Dict[str, Any]) VisionModel[source]

Build a model from a raw configuration dictionary.

parse_recipe(recipe: Recipe) Dict[str, Any][source]

Parse entire recipe into build configuration.

parse_definition(def_str: str) Dict[str, Any][source]

Parse a single component definition string.

Format: “name(args) modifiers” Example: “residual(64, stride=2) x 3 | downsample”

Returns:

Dictionary with parsed parameters

validate_recipe_config(config: Dict[str, Any], strict: bool = True) List[str][source]

Validate a recipe configuration against the schema.

Parameters:
  • config – Recipe configuration dictionary

  • strict – If True, raise on errors; if False, return warnings

Returns:

List of warning messages (empty if all OK)

Raises:

ValidationError – If strict and validation fails

expand_macros(config: Dict[str, Any]) Dict[str, Any][source]

Expand macros in recipe configuration.

Replaces @macro patterns with their definitions.

Parameters:

config – Recipe configuration with macros

Returns:

Configuration with macros expanded

Example

>>> config = {
...     'macros': {'attention': 'SEBlock'},
...     'stages': [{'attention': '@attention'}]
... }
>>> expanded = expand_macros(config)
>>> # expanded['stages'][0]['attention'] == 'SEBlock'
merge_recipes(base: Dict[str, Any], override: Dict[str, Any]) Dict[str, Any][source]

Merge two recipe configurations (for inheritance).

Parameters:
  • base – Base recipe configuration

  • override – Recipe to merge on top

Returns:

Merged configuration

get_template(name: str) Dict[str, Any][source]

Get a recipe template by name.

Parameters:

name – Template name

Returns:

Template configuration dictionary

exception ValidationError(message: str, path: str = '', suggestion: str = '')[source]

Bases: Exception

Recipe validation error with detailed information.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

load_yaml_config(path: str | Path, validate: bool = True, expand: bool = True) Dict[str, Any][source]

Load and process a YAML recipe configuration.

Parameters:
  • path – Path to YAML file

  • validate – Whether to validate against schema

  • expand – Whether to expand macros

Returns:

Processed recipe configuration

Raises:
  • RecipeLoadError – If file cannot be loaded

  • ValidationError – If validation fails

load_yaml_recipe(path: str | Path, num_classes: int | None = None, **kwargs) Module[source]

Load a YAML recipe and build the model.

Parameters:
  • path – Path to YAML recipe file

  • num_classes – Override number of classes

  • **kwargs – Additional build arguments

Returns:

Built PyTorch model

Example

>>> model = load_yaml_recipe("resnet_cifar.yaml", num_classes=10)
save_yaml_recipe(config: Dict[str, Any], path: str | Path, include_metadata: bool = True) None[source]

Save a recipe configuration to YAML file.

Parameters:
  • config – Recipe configuration

  • path – Output file path

  • include_metadata – Whether to include schema version comment

list_templates() List[str][source]

List available recipe templates.

create_recipe_from_template(template_name: str, output_path: str | Path | None = None, **overrides) Dict[str, Any][source]

Create a new recipe from a template.

Parameters:
  • template_name – Name of the template

  • output_path – Optional path to save the recipe

  • **overrides – Values to override in the template

Returns:

Recipe configuration

create_example_recipe(output_path: str | Path) None[source]

Create an example recipe file for reference.

Parameters:

output_path – Where to save the example

Classes

class Recipe(stem: str | Dict[str, Any], stages: List[str | Dict[str, Any]], head: str | Dict[str, Any], name: str = 'CustomModel', input_shape: tuple = (3, 224, 224))[source]

Bases: object

Architecture Recipe definition.

A declarative blueprint for a neural network architecture.

Parameters:
  • stem – Stem definition string or dict (e.g., “conv(64, k=7, s=2)”)

  • stages – List of stage definitions (e.g., [“residual(64) x 3”])

  • head – Head definition string or dict (e.g., “linear(1000)”)

  • name – Optional name for the architecture

  • input_shape – Expected input shape (C, H, W)

stem: str | Dict[str, Any]
stages: List[str | Dict[str, Any]]
head: str | Dict[str, Any]
name: str = 'CustomModel'
input_shape: tuple = (3, 224, 224)
to_dict() Dict[str, Any][source]

Convert to dictionary.

classmethod from_dict(data: Dict[str, Any]) Recipe[source]

Create from dictionary.

classmethod from_yaml(path: str) Recipe[source]

Load from YAML file.

Functions

build_recipe(recipe: Recipe) VisionModel[source]

Build a model from a Recipe object.

Parameters:

recipe – Recipe definition

Returns:

Built VisionModel

parse_recipe(recipe: Recipe) Dict[str, Any][source]

Parse entire recipe into build configuration.