"""Work through fixed dense network shapes and compare the linear layer with PyTorch."""
import argparse
import json
import platform
import numpy as np
CASES = []
def record(name, operation, inputs, expected, actual):
assert actual == expected, (name, expected, actual)
CASES.append(dict(name=name, operation=operation, inputs=inputs,
expected=expected, actual=actual, passed=True))
def dense(samples, weights, bias, activation="linear"):
if bias.shape != (weights.shape[1],):
raise ValueError("Provide one bias value per output feature")
result = samples @ weights + bias
if activation == "linear":
return result
if activation == "relu":
return np.maximum(result, 0)
if activation == "sigmoid":
# exp(-abs(x)) stays in [0, 1], even for large negative logits.
decay = np.exp(-np.abs(result))
return np.where(result >= 0, 1 / (1 + decay), decay / (1 + decay))
raise ValueError(f"Unknown activation: {activation}")
def rejected(run):
try:
run()
except ValueError as error:
return type(error).__name__
return "accepted"
def main():
cli = argparse.ArgumentParser()
cli.add_argument("--torch", action="store_true")
args = cli.parse_args()
versions = {"numpy": np.__version__}
first = np.array([[2., -1., 3., 1.]])
w = np.array([[1., 0., -1.], [2., 1., 0.], [0., -1., 1.], [1., 2., -1.]])
b = np.array([.5, 1., -2.])
single = dense(first, w, b)
relu = dense(first, w, b, "relu")
record("single_row_relu", "compute one sample before and after activation",
{"sample": first.tolist(), "weights": w.tolist(), "bias": b.tolist()},
[[[1.5, -1., -2.]], [[1.5, 0., 0.]]], [single.tolist(), relu.tolist()])
samples = np.concatenate((first, np.arange(28).reshape(7, 4) / 10))
batch = dense(samples, w, b, "relu")
record("batch_preserves_row_count", "compare batched and per-row results",
{"shape": list(samples.shape)}, [[8, 3], True],
[list(batch.shape), bool(np.allclose(batch, np.vstack([dense(samples[j:j+1], w, b, "relu") for j in range(8)])))])
w1 = np.column_stack((np.eye(4), [-1, 0, 0, 0], np.ones(4)))
w2 = np.array([[1., 0.], [0., 1.], [0., 1.], [0., 0.], [0., 0.], [0., -1.]])
hidden = dense(samples, w1, np.zeros(6), "relu")
prediction = dense(hidden, w2, np.array([-1., 1.]), "sigmoid")
record("stack_two_layers", "pass an 8 by 4 batch through ReLU and sigmoid layers",
{"weight_shapes": [list(w1.shape), list(w2.shape)]},
[[8, 6], [8, 2], [2, 0, 3, 1, 0, 5], [.731059, .268941]],
[list(hidden.shape), list(prediction.shape), hidden[0].tolist(), np.round(prediction[0], 6).tolist()])
record("incompatible_feature_dimensions", "multiply four columns by a matrix of five rows",
[[8, 4], [5, 3]], "ValueError", rejected(lambda: dense(samples, np.ones((5, 3)), b)))
record("bias_and_activation_validation", "reject a scalar bias and an unknown activation",
["scalar", "unknown"], ["ValueError", "ValueError"],
[rejected(lambda: dense(samples, w, np.array(.5))), rejected(lambda: dense(samples, w, b, "unknown"))])
qkv = np.ones((2, 3, 4)) @ np.ones((4, 12))
ids = np.array([[0, 1, 0], [2, 2, 1]])
lookup = np.arange(12).reshape(3, 4)
shapes = [np.ones((32, 784)) @ np.ones((784, 128)), *np.split(qkv, 3, axis=-1),
lookup[ids], np.ones((2, 768)) @ np.ones((768, 10))]
record("network_layer_shapes", "compute dense, Q/K/V, embedding and classifier output shapes",
{"layers": 6}, [[32, 128], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 10]],
[list(tensor.shape) for tensor in shapes])
two = dense(np.ones((1, 1)), np.array([[800., -800.]]), np.zeros(2), "sigmoid")
record("sigmoid_float_range", "verify saturating extremes and an ordinary multi-label row",
[800, -800, 1, 1], [[[1., 0.]], 1.462117],
[two.tolist(), round(float(dense(np.ones((1, 1)), np.ones((1, 2)), np.zeros(2), "sigmoid").sum()), 6)])
if args.torch:
import torch
versions["torch"] = torch.__version__
layer = torch.nn.Linear(4, 3, dtype=torch.float64)
with torch.no_grad():
layer.weight.copy_(torch.from_numpy(w.T))
layer.bias.copy_(torch.from_numpy(b))
observed = layer(torch.from_numpy(samples)).numpy()
record("pytorch_linear_weight_layout", "transpose NumPy weights before loading torch Linear",
{"numpy": list(w.shape), "torch": list(layer.weight.shape)}, [[3, 4], True],
[list(layer.weight.shape), bool(np.allclose(observed, dense(samples, w, b)))])
print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=CASES)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。
入口文件:projects/ai-math-forward-pass-lab/dense-forward.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
dense-forward.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a55.zip