Build a 2-Layer nn.Sequential MLP

Basics
BasicsPyTorchMLPGoogleMetaAmazon

Problem

Implement build_two_layer_mlp(in_dim, hidden_dim, out_dim) returning a PyTorch nn.Sequential network with exact layer order: nn.Linear(in_dim, hidden_dim) -> nn.ReLU() -> nn.Linear(hidden_dim, out_dim).

Why It Matters: A 2-layer MLP (Feed-Forward Network) is the core building block of tabular neural nets, Transformer FFN sub-layers, and classification heads.

Function Signature

import torch.nn as nn

def build_two_layer_mlp(in_dim: int, hidden_dim: int, out_dim: int) -> nn.Sequential:
    """Return a Linear -> ReLU -> Linear nn.Sequential network."""

Sample Input & Output

Example 1: Standard MLP Forward Shape

Input:

model = build_two_layer_mlp(in_dim=8, hidden_dim=16, out_dim=3)
x = torch.randn(4, 8)
out = model(x)

Expected Output:

out.shape == torch.Size([4, 3])  # 3 layers: Linear(8,16), ReLU(), Linear(16,3)

Explanation: A batch of 4 samples with 8 features projects to 16 hidden units, applies ReLU, and outputs 3 logits per sample.

Example 2: Single-Output Regression MLP

Input:

model = build_two_layer_mlp(in_dim=5, hidden_dim=10, out_dim=1)
x = torch.randn(2, 5)
out = model(x)

Expected Output:

out.shape == torch.Size([2, 1])

Explanation: Setting out_dim=1 produces a scalar prediction per batch item with shape (B, 1).

Constraints & Edge Cases

  • Return an nn.Sequential module accepting [B, in_dim] and outputting [B, out_dim].
  • Do not add a final activation (like Softmax or Sigmoid) after the second nn.Linear—raw logits are expected.
  • Return an instance of torch.nn.Sequential with exactly 3 child modules.

Constraints & Evaluation Criteria

  • Return an `nn.Sequential` module accepting `[B, in_dim]` and outputting `[B, out_dim]`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
in=8, hidden=16, out=3
Expected Output / Criteria
shape (4, 3)