Homework · Runs in your browser
Attention with a causal mask, multi-head attention, sampling filters and LoRA from scratch
Build the core pieces of a decoder-only language model with nothing but the standard library: a stable softmax, scaled dot-product attention with a causal mask and an offset, multi-head attention, sinusoidal positions, temperature, top-k and top-p filters, inverse-CDF sampling, a LoRA layer and its merge, and three size calculators plus the GELU and SiLU activations. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest. Matrices are lists of rows, and starter.py already gives you matmul and transpose.
Hints:
- softmax: subtract the largest entry before exponentiating. A -inf entry must come out as exactly 0.
- attention: scores are Q K^T divided by the square root of d_k, which is the length of a query row (not d_v and not the number of keys). Apply the mask by setting scores to -inf before the softmax, never after. Query i may see key j when j <= i + offset. With a KV cache the queries are the last n_q positions, so offset = n_k - n_q.
- multi_head_attention: project once with each full matrix, then slice columns per head. Head h reads columns h*d_k to (h+1)d_k of the query and key projections and columns hd_v to (h+1)*d_v of the value projection. Concatenate heads in order, then multiply by Wo.
- sinusoidal_positions: the angle is position / 10000^(2i/d). Put the sine of the angle in column 2i and the cosine of the same angle in column 2i+1.
- top_k_filter and top_p_filter: sort by probability, largest first, with ties going to the lower index. Keep the set, zero the rest, and renormalise so the kept values sum to 1. For top-p keep tokens until the running total reaches p, and include the token that reaches it (the comparison is at least p, with a tolerance of 1e-12 for rounding).
- sample_index: walk the cumulative sum and return the first index where it is strictly greater than u. That way a token with probability 0 is never picked, even for u = 0. If rounding leaves the loop without a result, return the last token whose probability is above 0.
- lora_forward: y = W x + (alpha / r) * B (A x), with r the number of rows of A. merge_lora returns W + (alpha / r) * B A. The two must agree.
- Sizes: per layer the attention matrices have 4 * d_model^2 weights and the MLP has 2 * d_model * d_ff. The KV cache holds keys and values, so there is a factor of 2.
- silu: x times the sigmoid of x, written so that exp never receives a large positive number (silu(-800) must not raise an error). gelu uses math.erf.
Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.
Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.
Show a solution
Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.
import math
def matmul(A, B):
"""Matrix product of A (n x k) and B (k x m), both lists of rows."""
return [[sum(a * b for a, b in zip(row, col)) for col in zip(*B)] for row in A]
def transpose(A):
return [list(r) for r in zip(*A)]
def softmax(xs):
"""Numerically stable softmax. Entries equal to -inf get weight 0."""
m = max(xs)
es = [math.exp(x - m) for x in xs]
s = sum(es)
return [e / s for e in es]
def attention(Q, K, V, causal=False, offset=0):
"""Scaled dot-product attention. Returns (output, weights).
Q is n_q x d_k, K is n_k x d_k, V is n_k x d_v, so the score matrix is n_q x n_k.
Scores are Q K^T / sqrt(d_k). With causal=True, query i may see key j only if j <= i + offset;
every other score is set to -inf before the softmax. offset=n_k - n_q aligns the queries
with the LAST n_q positions, which is the situation when a KV cache holds the earlier keys.
"""
d_k = len(Q[0])
scores = matmul(Q, transpose(K))
scores = [[s / math.sqrt(d_k) for s in row] for row in scores]
if causal:
scores = [[s if j <= i + offset else -math.inf for j, s in enumerate(row)] for i, row in enumerate(scores)]
weights = [softmax(row) for row in scores]
return matmul(weights, V), weights
def multi_head_attention(X, Wq, Wk, Wv, Wo, heads, causal=False):
"""Multi-head self-attention on X (n x d_model).
Wq and Wk are d_model x (heads * d_k), Wv is d_model x (heads * d_v), Wo is (heads * d_v) x d_model.
Head h uses columns h*d_k..(h+1)*d_k of Wq and Wk and columns h*d_v..(h+1)*d_v of Wv.
The head outputs are concatenated in head order and multiplied by Wo. Returns an n x d_model matrix.
"""
Q, K, V = matmul(X, Wq), matmul(X, Wk), matmul(X, Wv)
d_k, d_v = len(Q[0]) // heads, len(V[0]) // heads
outs = []
for h in range(heads):
q = [row[h * d_k:(h + 1) * d_k] for row in Q]
k = [row[h * d_k:(h + 1) * d_k] for row in K]
v = [row[h * d_v:(h + 1) * d_v] for row in V]
outs.append(attention(q, k, v, causal=causal)[0])
concat = [sum((outs[h][i] for h in range(heads)), []) for i in range(len(X))]
return matmul(concat, Wo)
def sinusoidal_positions(n, d):
"""Sinusoidal position encodings (n x d, d even): PE[p][2i] = sin(p / 10000^(2i/d)), PE[p][2i+1] = cos(same angle)."""
rows = []
for p in range(n):
row = []
for i in range(d // 2):
angle = p / 10000 ** (2 * i / d)
row += [math.sin(angle), math.cos(angle)]
rows.append(row)
return rows
def temperature_softmax(logits, temperature):
"""Softmax of logits / temperature (temperature > 0)."""
return softmax([x / temperature for x in logits])
def top_k_filter(probs, k):
"""Keep the k most probable tokens (ties go to the lower index), set the rest to 0 and renormalise."""
order = sorted(range(len(probs)), key=lambda i: (-probs[i], i))
keep = set(order[:k])
z = sum(probs[i] for i in keep)
return [probs[i] / z if i in keep else 0.0 for i in range(len(probs))]
def top_p_filter(probs, p):
"""Nucleus filter: keep the smallest set of most probable tokens whose total probability is at least p
(ties go to the lower index), set the rest to 0 and renormalise."""
order = sorted(range(len(probs)), key=lambda i: (-probs[i], i))
keep, total = set(), 0.0
for i in order:
keep.add(i)
total += probs[i]
if total >= p - 1e-12:
break
z = sum(probs[i] for i in keep)
return [probs[i] / z if i in keep else 0.0 for i in range(len(probs))]
def sample_index(probs, u):
"""Inverse-CDF sampling: the smallest index i whose cumulative probability is strictly greater than u (0 <= u < 1)."""
total = 0.0
last = 0
for i, pr in enumerate(probs):
if pr > 0:
last = i
total += pr
if total > u:
return i
return last
def lora_forward(W, A, B, x, alpha):
"""Output of a LoRA-adapted linear layer for one input vector x: W x + (alpha / r) * B (A x).
W is d_out x d_in, A is r x d_in, B is d_out x r, and r = len(A). Returns a list of length d_out.
"""
r = len(A)
base = [sum(w * v for w, v in zip(row, x)) for row in W]
low = [sum(a * v for a, v in zip(row, x)) for row in A]
up = [sum(b * v for b, v in zip(row, low)) for row in B]
return [y + (alpha / r) * u for y, u in zip(base, up)]
def merge_lora(W, A, B, alpha):
"""Merged weight W + (alpha / r) * B A, a d_out x d_in matrix."""
r = len(A)
delta = matmul(B, A)
return [[w + (alpha / r) * d for w, d in zip(wr, dr)] for wr, dr in zip(W, delta)]
def lora_param_count(d_out, d_in, r):
"""Trainable parameters of one LoRA adapter (A and B, no bias)."""
return r * (d_in + d_out)
def transformer_param_count(layers, d_model, d_ff):
"""Weights of the attention and MLP blocks of a transformer, ignoring biases, norms and embeddings.
Per layer: four d_model x d_model attention matrices plus an MLP with d_model x d_ff and d_ff x d_model.
"""
return layers * (4 * d_model * d_model + 2 * d_model * d_ff)
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, batch=1, bytes_per_value=2):
"""Bytes of the key-value cache: keys and values (2) for every layer, KV head, head dimension, token and sequence."""
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per_value
def gelu(x):
"""Exact GELU: x * Phi(x), with Phi the standard normal CDF (use math.erf)."""
return 0.5 * x * (1 + math.erf(x / math.sqrt(2)))
def silu(x):
"""SiLU (swish): x * sigmoid(x). Must not overflow for large negative x such as -800."""
if x >= 0:
sig = 1 / (1 + math.exp(-x))
else:
e = math.exp(x)
sig = e / (1 + e)
return x * sig
Show the tests (test_starter.py)
import math
from starter import (
attention,
gelu,
kv_cache_bytes,
lora_forward,
lora_param_count,
merge_lora,
multi_head_attention,
sample_index,
sinusoidal_positions,
silu,
softmax,
temperature_softmax,
top_k_filter,
top_p_filter,
transformer_param_count,
)
# 2 queries, 4 keys, d_k = 3, d_v = 2: no two of n_q, n_k, d_k, d_v are equal in the useful places.
Q = [[1, 0, 2], [0, 1, -1]]
K = [[1, 1, 0], [0, 2, 1], [3, 0, 1], [1, -1, 2]]
V = [[1, 0], [0, 1], [2, 2], [-1, 3]]
def close(a, b, tol=1e-9):
if isinstance(a, (list, tuple)):
assert isinstance(b, (list, tuple)) and len(a) == len(b), f"shape mismatch: {a} vs {b}"
for x, y in zip(a, b):
close(x, y, tol)
else:
assert math.isclose(a, b, rel_tol=tol, abs_tol=tol), f"{a} != {b}"
def shape(m):
return (len(m), len(m[0]))
# --- softmax ---------------------------------------------------------------
def test_softmax_known_values_and_sum():
close(softmax([1, 2, 3]), [0.09003057317038046, 0.24472847105479764, 0.6652409557748219])
assert math.isclose(sum(softmax([0.3, -2, 5, 1])), 1.0)
def test_softmax_is_shift_invariant_and_stable():
close(softmax([1000, 1001]), softmax([0, 1]))
close(softmax([-1000, -1001, -1002]), softmax([0, -1, -2]))
def test_softmax_gives_minus_infinity_zero_weight():
close(softmax([0.0, -math.inf, 0.0]), [0.5, 0.0, 0.5])
# --- attention -------------------------------------------------------------
def test_attention_shapes_with_all_sizes_different():
out, w = attention(Q, K, V)
assert shape(out) == (2, 2), "output is n_q x d_v"
assert shape(w) == (2, 4), "weights are n_q x n_k"
for row in w:
assert math.isclose(sum(row), 1.0)
def test_attention_known_values():
out, w = attention(Q, K, V)
close(w[0], [0.043633639342839654, 0.07772513296216035, 0.43932061384750004, 0.43932061384750004])
close(w[1], [0.41416912023880004, 0.41416912023880004, 0.13052618461465348, 0.041135574907746456])
close(out, [[0.4829542531903397, 2.2743282021996607], [0.6340859145603606, 0.7986282141913463]])
def test_scale_is_one_over_root_of_d_k_not_d_v_or_n():
# Scores for query 0 are 1, 2, 5, 5 before scaling, so weights depend on the scale.
_, w = attention(Q, K, V)
scale = 1 / math.sqrt(3)
e = [math.exp(s * scale) for s in (1, 2, 5, 5)]
close(w[0], [x / sum(e) for x in e])
def test_zero_queries_average_the_values():
out, w = attention([[0, 0, 0]], K, V)
close(w[0], [0.25] * 4)
close(out, [[0.5, 1.5]])
def test_output_is_weights_times_values():
out, w = attention(Q, K, V)
for i in range(2):
for c in range(2):
assert math.isclose(out[i][c], sum(w[i][j] * V[j][c] for j in range(4)))
def test_causal_square_is_lower_triangular():
X = [[1, 2], [0, -1], [3, 1]]
_, w = attention(X, X, [[1], [2], [3]], causal=True)
assert w[0] == [1.0, 0.0, 0.0]
assert w[1][2] == 0.0 and w[1][0] > 0 and w[1][1] > 0
assert all(w[2][j] > 0 for j in range(3))
def test_causal_default_offset_zero_on_non_square():
_, w = attention(Q, K, V, causal=True)
close(w, [[1.0, 0.0, 0.0, 0.0], [0.5, 0.5, 0.0, 0.0]])
def test_causal_offset_aligns_queries_with_the_last_positions():
out, w = attention(Q, K, V, causal=True, offset=2)
assert w[0][3] == 0.0, "query 0 sits at position 2 and cannot see key 3"
close(w[0], [0.07782279930472007, 0.13862669982487955, 0.7835505008704003, 0.0])
close(w[1], [0.41416912023880004, 0.41416912023880004, 0.13052618461465348, 0.041135574907746456])
close(out[0], [1.6449238010455207, 1.7057277015656802])
def test_cached_decoding_matches_full_causal_attention():
X = [[1, 2, 0], [0, -1, 1], [3, 1, 2], [1, 1, -1], [2, 0, 1]]
full, _ = attention(X, X, [[i, -i] for i in range(5)], causal=True)
Vv = [[i, -i] for i in range(5)]
last, _ = attention([X[4]], X, Vv, causal=True, offset=4)
close(last[0], full[4])
last2, _ = attention(X[3:], X, Vv, causal=True, offset=3)
close(last2, full[3:])
def test_future_tokens_do_not_change_earlier_outputs():
X = [[1, 2], [0, -1], [3, 1], [2, 2]]
Vv = [[1, 0], [0, 1], [2, 2], [5, 5]]
base, _ = attention(X, X, Vv, causal=True)
X2 = [row[:] for row in X]
V2 = [row[:] for row in Vv]
X2[3] = [9, -9]
V2[3] = [-50, 50]
changed, _ = attention(X2, X2, V2, causal=True)
close(base[:3], changed[:3])
assert base[3] != changed[3]
def test_attention_without_mask_ignores_order_of_keys():
out, _ = attention(Q, K, V)
perm = [2, 0, 3, 1]
out2, _ = attention(Q, [K[i] for i in perm], [V[i] for i in perm])
close(out, out2)
# --- multi-head attention --------------------------------------------------
X = [[1, 0, 2, -1], [0, 1, 1, 2], [2, -1, 0, 1]]
WQ = [[1, 0, 0, 1, 0, 2], [0, 1, 1, 0, 1, 0], [1, 1, 0, 0, -1, 1], [0, 0, 1, 1, 0, 1]]
WK = [[0, 1, 1, 0, 0, 1], [1, 0, 0, 1, 1, 0], [0, 1, 0, 1, 0, -1], [1, 0, 1, 0, 1, 0]]
WV = [[1, 0, 0, 1], [0, 1, 1, 0], [1, 0, -1, 0], [0, 1, 0, 2]]
WO = [[1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 2]]
EYE = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
def mm(A, B):
return [[sum(a * b for a, b in zip(r, c)) for c in zip(*B)] for r in A]
def test_multi_head_known_values():
out = multi_head_attention(X, WQ, WK, WV, WO, 2)
assert shape(out) == (3, 4)
close(out, [[4.983273834391521, 2.85132216126972, -1.0170952413199843, 8.896946038157953],
[5.116193377359252, 0.7060976885673113, -1.0, 8.462789389322893],
[4.760623539612177, 2.9361688577814613, -1.0473188216500855, 8.49793945960323]])
def test_multi_head_is_per_head_attention_concatenated_in_order():
out = multi_head_attention(X, WQ, WK, WV, EYE, 2)
Qf, Kf, Vf = mm(X, WQ), mm(X, WK), mm(X, WV)
heads = []
for h in range(2):
q = [r[3 * h:3 * h + 3] for r in Qf]
k = [r[3 * h:3 * h + 3] for r in Kf]
v = [r[2 * h:2 * h + 2] for r in Vf]
heads.append(attention(q, k, v)[0])
expected = [heads[0][i] + heads[1][i] for i in range(3)]
close(out, expected)
def test_multi_head_one_head_is_plain_attention():
Wq1 = [[1, 0], [0, 1], [1, 1], [0, 2]]
Wk1 = [[0, 1], [1, 0], [1, 1], [2, 0]]
out = multi_head_attention(X, Wq1, Wk1, WV, EYE, 1)
close(out, attention(mm(X, Wq1), mm(X, Wk1), mm(X, WV))[0])
def test_multi_head_causal_flag_and_output_projection():
out = multi_head_attention(X, WQ, WK, WV, WO, 2, causal=True)
close(out[0], [2.0, -1.0, -2.0, 1.0])
close(out[1], [2.560702180658849, 2.878595638682303, -1.0, 4.060702180658849])
close(out[2], [4.760623539612177, 2.9361688577814613, -1.0473188216500855, 8.49793945960323])
# --- positions -------------------------------------------------------------
def test_sinusoidal_known_rows():
P = sinusoidal_positions(3, 4)
close(P[0], [0.0, 1.0, 0.0, 1.0])
close(P[1], [0.8414709848078965, 0.5403023058681398, 0.009999833334166664, 0.9999500004166653])
close(P[2], [0.9092974268256817, -0.4161468365471424, 0.01999866669333308, 0.9998000066665778])
def test_sinusoidal_shape_and_frequency_for_longer_encoding():
P = sinusoidal_positions(5, 6)
assert shape(P) == (5, 6)
for pos in range(5):
for i in range(3):
angle = pos / 10000 ** (2 * i / 6)
assert math.isclose(P[pos][2 * i], math.sin(angle), abs_tol=1e-12)
assert math.isclose(P[pos][2 * i + 1], math.cos(angle), abs_tol=1e-12)
# --- decoding --------------------------------------------------------------
def test_temperature_softmax_values():
close(temperature_softmax([2, 1, 0], 1.0), softmax([2, 1, 0]))
close(temperature_softmax([2, 1, 0], 0.5), softmax([4, 2, 0]))
close(temperature_softmax([2, 1, 0], 2.0), softmax([1, 0.5, 0]))
def test_temperature_changes_sharpness_and_stays_finite():
cold = temperature_softmax([2.0, 1.0, 0.0], 0.1)
warm = temperature_softmax([2.0, 1.0, 0.0], 10.0)
assert cold[0] > 0.99 and warm[0] < 0.4 and warm[2] > 0.3
close(temperature_softmax([1000, 0], 1.0), [1.0, 0.0])
close(temperature_softmax([1000, 999], 0.001), [1.0, 0.0])
def test_top_k_filter():
close(top_k_filter([0.1, 0.4, 0.2, 0.3], 2), [0.0, 4 / 7, 0.0, 3 / 7])
close(top_k_filter([0.1, 0.4, 0.2, 0.3], 1), [0.0, 1.0, 0.0, 0.0])
close(top_k_filter([0.1, 0.4, 0.2, 0.3], 3), [0.0, 4 / 9, 2 / 9, 3 / 9])
close(top_k_filter([0.1, 0.4, 0.2, 0.3], 10), [0.1, 0.4, 0.2, 0.3])
def test_top_k_ties_go_to_lower_index():
close(top_k_filter([0.25, 0.25, 0.25, 0.25], 2), [0.5, 0.5, 0.0, 0.0])
close(top_k_filter([0.2, 0.4, 0.2, 0.2], 2), [1 / 3, 2 / 3, 0.0, 0.0])
def test_top_p_filter_keeps_smallest_set_reaching_p():
p = [0.5, 0.25, 0.15, 0.1]
close(top_p_filter(p, 0.7), [2 / 3, 1 / 3, 0.0, 0.0])
close(top_p_filter(p, 0.76), [0.5 / 0.9, 0.25 / 0.9, 0.15 / 0.9, 0.0])
close(top_p_filter(p, 1.0), p)
def test_top_p_boundary_is_inclusive():
p = [0.5, 0.25, 0.15, 0.1]
close(top_p_filter(p, 0.5), [1.0, 0.0, 0.0, 0.0])
close(top_p_filter(p, 0.75), [2 / 3, 1 / 3, 0.0, 0.0])
def test_top_p_sorts_and_keeps_original_positions():
p = [0.1, 0.4, 0.2, 0.3]
close(top_p_filter(p, 0.6), [0.0, 4 / 7, 0.0, 3 / 7])
close(top_p_filter(p, 0.9), [0.0, 4 / 9, 2 / 9, 3 / 9])
close(top_p_filter(p, 0.01), [0.0, 1.0, 0.0, 0.0])
def test_top_p_ties_go_to_lower_index():
close(top_p_filter([0.25, 0.25, 0.25, 0.25], 0.5), [0.5, 0.5, 0.0, 0.0])
def test_sample_index_inverse_cdf():
p = [0.25, 0.5, 0.25]
assert [sample_index(p, u) for u in (0.0, 0.2499, 0.25, 0.7499, 0.75, 0.999)] == [0, 0, 1, 1, 2, 2]
def test_sample_index_skips_zero_probability_tokens():
assert sample_index([0.0, 0.5, 0.5, 0.0], 0.0) == 1
assert sample_index([0.0, 0.5, 0.5, 0.0], 0.9999) == 2
assert sample_index([0.5, 0.5, 0.0], 0.99999999) == 1
def test_sample_index_rounding_falls_back_to_last_possible_token():
assert sample_index([0.3, 0.3, 0.3, 0.0], 0.95) == 2
def test_sampling_frequencies_follow_the_distribution():
p = [0.25, 0.5, 0.125, 0.125]
counts = [0] * 4
for k in range(1000):
counts[sample_index(p, (k + 0.5) / 1000)] += 1
assert counts == [250, 500, 125, 125]
def test_filtered_sampling_never_picks_removed_tokens():
p = temperature_softmax([2.0, 1.0, 0.5, 0.0, -1.0], 1.0)
f = top_p_filter(p, 0.9)
seen = {sample_index(f, (k + 0.5) / 400) for k in range(400)}
assert seen == {0, 1, 2, 3}
# --- LoRA ------------------------------------------------------------------
W = [[1, 0, 2, -1], [0, 1, 1, 0], [2, 1, 0, 1]]
A = [[1, 0, 1, 0], [0, 1, 0, -1]]
B = [[1, 0], [0, 2], [1, 1]]
XV = [1, 2, 3, 4]
def test_lora_forward_known_values():
close(lora_forward(W, A, B, XV, 6), [15.0, -7.0, 14.0])
close(lora_forward(W, A, B, XV, 2), [7.0, 1.0, 10.0])
def test_lora_scale_is_alpha_over_rank():
close(lora_forward(W, A, B, XV, 2), [7.0, 1.0, 10.0]) # alpha = r gives scale 1
close(lora_forward(W, [A[0]], [[r[0]] for r in B], XV, 1), [1 * 3 + 4 * 1, 5 + 0, 8 + 4])
def test_lora_with_zero_b_equals_frozen_layer():
zero_b = [[0, 0], [0, 0], [0, 0]]
close(lora_forward(W, A, zero_b, XV, 16), [3.0, 5.0, 8.0])
def test_merge_lora_matches_forward_and_shape():
M = merge_lora(W, A, B, 6)
assert shape(M) == (3, 4)
close(M, [[4.0, 0.0, 5.0, -1.0], [0.0, 7.0, 1.0, -6.0], [5.0, 4.0, 3.0, -2.0]])
close([sum(m * v for m, v in zip(row, XV)) for row in M], lora_forward(W, A, B, XV, 6))
def test_lora_param_count():
assert lora_param_count(4096, 4096, 8) == 65536
assert lora_param_count(11008, 4096, 8) == 120832, "d_out and d_in are different"
assert lora_param_count(3, 4, 2) == 14
# --- sizes -----------------------------------------------------------------
def test_transformer_param_count():
assert transformer_param_count(32, 4096, 16384) == 6442450944
assert transformer_param_count(24, 1024, 4096) == 301989888
assert transformer_param_count(2, 10, 30) == 2000, "d_ff is not always 4 d_model"
assert transformer_param_count(1, 8, 12) == 448
def test_kv_cache_bytes():
assert kv_cache_bytes(32, 32, 128, 4096) == 2147483648
assert kv_cache_bytes(32, 8, 128, 4096) == 536870912, "fewer KV heads shrink the cache"
assert kv_cache_bytes(2, 3, 4, 5) == 480
assert kv_cache_bytes(2, 3, 4, 5, batch=2) == 960
assert kv_cache_bytes(2, 3, 4, 5, batch=6, bytes_per_value=1) == 1440
assert kv_cache_bytes(2, 3, 4, 5, bytes_per_value=4) == 960
# --- activations -----------------------------------------------------------
def test_gelu_is_the_exact_erf_form():
close(gelu(0.0), 0.0)
close(gelu(1.0), 0.8413447460685429)
close(gelu(-1.0), -0.15865525393145707)
close(gelu(-3.0), -0.00404969409489031)
close(gelu(10.0), 10.0)
def test_silu_values_and_overflow():
close(silu(0.0), 0.0)
close(silu(1.0), 0.7310585786300049)
close(silu(-1.0), -0.2689414213699951)
close(silu(2.0), 1.7615941559557646)
assert silu(-800.0) == 0.0 or abs(silu(-800.0)) < 1e-300
close(silu(800.0), 800.0)