Coverage for /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/equine/architectures.py: 100%

45 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-20 23:10 +0000

1# Copyright 2024, MASSACHUSETTS INSTITUTE OF TECHNOLOGY 

2# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014). 

3# SPDX-License-Identifier: MIT 

4""" 

5Embedding architectures that ship with EQUINE. 

6 

7They are registered on import. A model file that names one loads anywhere EQUINE is 

8installed, without the user defining a class. Their constructor signatures are part of 

9the model-file format: change them only additively, with defaults. 

10 

11``MLP`` enforces ``MAX_HIDDEN_LAYERS`` and ``MAX_PARAMETERS`` caps on its constructor 

12arguments. Raising either cap later is a compatible change; lowering one is not. 

13 

14``MLP``'s ``state_dict()`` layout is also part of the model-file format: the 

15parameter names and their order (``net.0.weight``, ``net.0.bias``, ...) must 

16not change, and any new constructor option must not shift the indices of the 

17existing ``torch.nn.Sequential`` layers. 

18""" 

19 

20from __future__ import annotations 

21 

22import reprlib 

23from collections.abc import Sequence 

24 

25import torch 

26 

27from .registry import _positive_int, embedding_architecture 

28 

29__all__ = ["MLP"] 

30 

31_ACTIVATIONS = { 

32 "relu": torch.nn.ReLU, 

33 "gelu": torch.nn.GELU, 

34 "tanh": torch.nn.Tanh, 

35 "sigmoid": torch.nn.Sigmoid, 

36} 

37 

38#: Most hidden layers a recipe may request. 

39MAX_HIDDEN_LAYERS = 64 

40 

41#: Most parameters a recipe may request. 

42MAX_PARAMETERS = 10**9 

43 

44 

45def _mlp_parameter_count( 

46 in_features: int, hidden_sizes: Sequence[int], out_features: int 

47) -> int: 

48 """Count ``MLP``'s parameters (weights + biases) from plain sizes, no allocation.""" 

49 count = 0 

50 width = in_features 

51 for hidden in hidden_sizes: 

52 count += width * hidden + hidden 

53 width = hidden 

54 count += width * out_features + out_features 

55 return count 

56 

57 

58@embedding_architecture("equine.mlp") 

59class MLP(torch.nn.Module): 

60 """ 

61 A plain multilayer perceptron for tabular features. 

62 

63 Parameters 

64 ---------- 

65 in_features : int 

66 Number of input features. Must be >= 1. 

67 hidden_sizes : list[int] or tuple[int, ...] 

68 Width of each hidden layer, in order. An empty list gives a single 

69 linear map. Must have at most ``MAX_HIDDEN_LAYERS`` entries, each 

70 >= 1. 

71 out_features : int 

72 Embedding dimension (``emb_out_dim`` for the EQUINE model). Must be 

73 >= 1. 

74 activation : str, optional 

75 One of ``"relu"``, ``"gelu"``, ``"tanh"``, ``"sigmoid"``, by default 

76 ``"relu"``. 

77 

78 Raises 

79 ------ 

80 TypeError 

81 If an argument is not a plain value (for example a numpy integer or 

82 a set), which a recipe could not store; raised when the instance 

83 records its recipe, before the checks below. 

84 ValueError 

85 If ``in_features``, ``out_features``, or any entry of 

86 ``hidden_sizes`` is not exactly an ``int`` (``bool`` is rejected) or 

87 is < 1; if ``hidden_sizes`` is not exactly a ``list`` or ``tuple``; 

88 if ``hidden_sizes`` has more than ``MAX_HIDDEN_LAYERS`` entries; if 

89 the resulting parameter count exceeds ``MAX_PARAMETERS``; or if 

90 ``activation`` is not exactly a ``str`` naming a known activation. 

91 """ 

92 

93 def __init__( 

94 self, 

95 in_features: int, 

96 hidden_sizes: list[int] | tuple[int, ...], 

97 out_features: int, 

98 activation: str = "relu", 

99 ) -> None: 

100 super().__init__() 

101 

102 _positive_int(in_features, "in_features") 

103 _positive_int(out_features, "out_features") 

104 

105 if type(hidden_sizes) not in (list, tuple): 

106 raise ValueError( 

107 "hidden_sizes must be a list or tuple (not " 

108 f"{type(hidden_sizes).__name__}); got {reprlib.repr(hidden_sizes)}." 

109 ) 

110 for index, hidden in enumerate(hidden_sizes): 

111 _positive_int(hidden, f"hidden_sizes[{index}]") 

112 if len(hidden_sizes) > MAX_HIDDEN_LAYERS: 

113 raise ValueError( 

114 f"hidden_sizes has {len(hidden_sizes)} entries, exceeding the " 

115 f"MAX_HIDDEN_LAYERS cap of {MAX_HIDDEN_LAYERS}." 

116 ) 

117 

118 if type(activation) is not str: 

119 raise ValueError( 

120 f"activation must be a str (not {type(activation).__name__}); " 

121 f"got {reprlib.repr(activation)}." 

122 ) 

123 if activation not in _ACTIVATIONS: 

124 raise ValueError( 

125 f"Unknown activation {reprlib.repr(activation)}; choose from " 

126 f"{sorted(_ACTIVATIONS)}." 

127 ) 

128 

129 parameter_count = _mlp_parameter_count(in_features, hidden_sizes, out_features) 

130 if parameter_count > MAX_PARAMETERS: 

131 raise ValueError( 

132 f"This MLP would have {reprlib.repr(parameter_count)} parameters, " 

133 f"exceeding the MAX_PARAMETERS cap of {MAX_PARAMETERS}." 

134 ) 

135 

136 layers: list[torch.nn.Module] = [] 

137 width = in_features 

138 for hidden in hidden_sizes: 

139 layers += [torch.nn.Linear(width, hidden), _ACTIVATIONS[activation]()] 

140 width = hidden 

141 layers.append(torch.nn.Linear(width, out_features)) 

142 self.net: torch.nn.Sequential = torch.nn.Sequential(*layers) 

143 

144 def forward(self, x: torch.Tensor) -> torch.Tensor: 

145 """Embed ``x`` by applying the linear/activation stack in ``self.net``.""" 

146 return self.net(x)