Última actualización: 2026-12-02

DAY 026 OF 1600 · 2026-10-29

Day 026 — A saturated sigmoid is not the failure; the loss on top of it is

A student's private learning log · one concept at a time. Date: 2026-10-29 · Day: 26 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #26 — A dead gradient is a decision the loss makes, not the activation

MA04, Deep Learning. The mock test has this question: L = ½(y − t)² , y = σ(z) , z = w·x + b , with w = −2 , x = −3 , b = 6000000 , t = 1 . Compute ∂L/∂w . The forward pass gives z = 6000006 , σ(6000006) = 1 , and then ∂L/∂y = y − t = 0 and ∂y/∂z = y(1 − y) = 0 . Answer: 0 . The mock answer says 0 and it is correct. What it does not say is the part that matters to me now: **it would still be 0 if the label were wrong**. Put t = 0 on the same neuron — a confidently incorrect prediction, p = 1 when the truth is 0 — and the squared error still hands back 0.0 . The neuron is wrong, the loss agrees that there is nothing to fix, and training stops on a mistake. That is not a property of the sigmoid. It is a property of a squared error sitting on top of a squashed output. The chain rule puts σ'(z) = p(1 − p) in the path, and once p rounds to 1.0 that factor is not small, it is exactly zero in floating point . Binary cross-entropy on the same neuron gives ∂L/∂z = p − t , which is 1.0 out there, because the p(1−p) cancels against the derivative of the log instead of being multiplied by it. Same neuron, same saturation, one loss transmits nothing and the other transmits a full unit of error. What I tried today: one script, stdlib only, five measurements. Where sigmoid(z) stops being a probability in float64 and in float32; the exam case with the right and the wrong label; analytic gradients against central differences at a healthy z and at a saturated one; a 500-step training run on a deliberately wrong, saturated neuron under both losses; and the stable logit form of BCE against the naive one. # saturation.py - MA04 (Deep Learning). The loss decides whether a saturated # neuron still learns. stdlib only, no numpy. # # Five measurements: # 1. the z at which sigmoid(z) rounds to exactly 1.0, in float64 and float32 # 2. the exam case (z = 6e6 + 6): the same neuron, right label and wrong label # 3. analytic gradients against finite differences, healthy and saturated # 4. a confidently WRONG neuron, trained 500 steps, MSE vs BCE # 5. the stable form of BCE at saturation, against the naive one import math import struct LR = 0.5 STEPS = 500 def sigmoid(z): if z >= 0.0: return 1.0 / (1.0 + math.exp(-z)) e = math.exp(z) return e / (1.0 + e) def f32(x): """Round a float64 to the nearest float32 (emulates one float32 step).""" return struct.unpack("f", struct.pack("f", x))[0] def sigmoid32(z): """Same sigmoid, but the addition and the division rounded to float32.""" e = f32(math.exp(-f32(z))) return f32(1.0 / f32(1.0 + e)) def mse(loss_z, t): """L = 0.5*(sigmoid(z) - t)**2 where loss_z is z. Also used as dL/dz below.""" p = sigmoid(loss_z) return 0.5 * (p - t) ** 2 def mse_dz(z, t): p = sigmoid(z) return (p - t) * p * (1.0 - p) def bce_dz(z, t): """dL/dz for BCE(sigmoid(z), t): it collapses to (p - t).""" return sigmoid(z) - t def bce_stable(z, t): """BCE straight from the logit: no sigmoid of z is ever formed.""" return max(z, 0.0) - z * t + math.log1p(math.exp(-abs(z))) def bce_naive(z, t): p = sigmoid(z) return -(t * math.log(p) + (1.0 - t) * math.log(1.0 - p)) def first_saturated(fn, hi=200.0, grid=0.05): """Smallest z on a grid where fn(z) returns exactly 1.0.""" z = 0.0 while z <= hi: if fn(z) == 1.0: return z z += grid return None def numeric_dz(z, t, loss, h=1e-6): return (loss(z + h, t) - loss(z - h, t)) / (2.0 * h) print("== 1. where sigmoid stops being a probability ==") z64 = first_saturated(sigmoid) z32 = first_saturated(sigmoid32) print(f"float64: first z with sigmoid(z) == 1.0 exactly : z = {z64:.2f}") print(f"float32: first z with sigmoid(z) == 1.0 exactly : z = {z32:.2f}") for z in (10.0, 16.0, 20.0, 36.0, 40.0): print(f" z={z:5.1f} float64={sigmoid(z):.17f} float32={sigmoid32(z):.9f}") print() print("== 2. the exam case: z = 6*10^6 + 6, w=-2 x=-3 b=6000000 ==") w, x, b = -2.0, -3.0, 6000000.0 z = w * x + b p = sigmoid(z) print(f"z = {z:.1f} p = {p!r} p*(1-p) = {p * (1.0 - p)!r}") for t in (1.0, 0.0): print(f" t={t:.0f} (label {'right' if t == 1.0 else 'WRONG'}): " f"dL/dz MSE = {mse_dz(z, t)!r} dL/dz BCE = {bce_dz(z, t)!r}") print() print("== 3. analytic vs finite differences ==") for zz in (0.0, 1.5, 2.0): print(f" z={zz:4.1f} MSE analytic={mse_dz(zz, 0.0): .8f} numeric={numeric_dz(zz, 0.0, mse): .8f}" f" BCE analytic={bce_dz(zz, 0.0): .8f} numeric={numeric_dz(zz, 0.0, bce_stable): .8f}") print(f" z=71.0 MSE analytic={mse_dz(71.0, 0.0)!r} numeric={numeric_dz(71.0, 0.0, mse)!r}" f" BCE analytic={bce_dz(71.0, 0.0)!r} numeric={numeric_dz(71.0, 0.0, bce_stable):.10f}") print() print("== 4. a confidently WRONG neuron (t=0), 500 steps, lr=0.5 ==") for name, grad in (("MSE", mse_dz), ("BCE", bce_dz)): w1, b1 = 30.0, 50.0 crossing = None for step in range(1, STEPS + 1): g = grad(w1 * 0.7 + b1, 0.0) w1 -= LR * g * 0.7 b1 -= LR * g if crossing is None and sigmoid(w1 * 0.7 + b1) < 0.5: crossing = step p1 = sigmoid(w1 * 0.7 + b1) where = f"step {crossing}" if crossing else f"never in {STEPS} steps" print(f" {name}: z {71.0:7.1f} -> {w1 * 0.7 + b1:8.3f} w {30.0:7.4f} -> {w1:8.4f}" f" p {sigmoid(71.0):.3e} -> {p1:.6f} loss {0.5 * (sigmoid(71.0)) ** 2:.3f} -> {mse(w1 * 0.7 + b1, 0.0):.6f}" f" p<0.5 at {where}") print() print("== 5. the stable form at z = +800, t = 0 ==") print(f" stable BCE(800, 0) = {bce_stable(800.0, 0.0)!r}") try: print(f" naive BCE(800, 0) = {bce_naive(800.0, 0.0)!r}") except (ValueError, ZeroDivisionError) as exc: print(f" naive BCE(800, 0) raises {type(exc).__name__}: {exc}") print() print(f"conclusion: sigmoid(z) == 1.0 from z ~ {z64:.1f} in float64 and ~ {z32:.1f} in float32.") print("p*(1-p) is then exactly 0.0, so MSE returns a zero gradient on a") print("confidently wrong answer, and finite differences agree with the zero.") print("The BCE gradient is (p - t), which stays 1.0 out there.") Real output: == 1. where sigmoid stops being a probability == float64: first z with sigmoid(z) == 1.0 exactly : z = 36.75 float32: first z with sigmoid(z) == 1.0 exactly : z = 16.65 z= 10.0 float64=0.99995460213129761 float32=0.999954581 z= 16.0 float64=0.99999988746483792 float32=0.999999881 z= 20.0 float64=0.99999999793884631 float32=1.000000000 z= 36.0 float64=0.99999999999999978 float32=1.000000000 z= 40.0 float64=1.00000000000000000 float32=1.000000000 == 2. the exam case: z = 6*10^6 + 6, w=-2 x=-3 b=6000000 == z = 6000006.0 p = 1.0 p*(1-p) = 0.0 t=1 (label right): dL/dz MSE = 0.0 dL/dz BCE = 0.0 t=0 (label WRONG): dL/dz MSE = 0.0 dL/dz BCE = 1.0 == 3. analytic vs finite differences == z= 0.0 MSE analytic= 0.12500000 numeric= 0.12500000 BCE analytic= 0.50000000 numeric= 0.50000000 z= 1.5 MSE analytic= 0.12193833 numeric= 0.12193833 BCE analytic= 0.81757448 numeric= 0.81757448 z= 2.0 MSE analytic= 0.09247804 numeric= 0.09247804 BCE analytic= 0.88079708 numeric= 0.88079708 z=71.0 MSE analytic=0.0 numeric=0.0 BCE analytic=1.0 numeric=0.9999999975 == 4. a confidently WRONG neuron (t=0), 500 steps, lr=0.5 == MSE: z 71.0 -> 71.000 w 30.0000 -> 30.0000 p 1.000e+00 -> 1.000000 loss 0.500 -> 0.500000 p<0.5 at never in 500 steps BCE: z 71.0 -> -5.697 w 30.0000 -> -6.0321 p 1.000e+00 -> 0.003345 loss 0.500 -> 0.000006 p<0.5 at step 97 == 5. the stable form at z = +800, t = 0 == stable BCE(800, 0) = 800.0 naive BCE(800, 0) raises ValueError: expected a positive input, got 0.0 conclusion: sigmoid(z) == 1.0 from z ~ 36.8 in float64 and ~ 16.7 in float32. p*(1-p) is then exactly 0.0, so MSE returns a zero gradient on a confidently wrong answer, and finite differences agree with the zero. The BCE gradient is (p - t), which stays 1.0 out there. What I understood from it: four things, and the numbers are the lesson. 1. The wall is much closer than the sigmoid looks. sigmoid(z) == 1.0 exactly from z = 36.75 in float64 and from z = 16.65 in float32 — I found those by walking a 0.05 grid. Float32 is what every GPU uses, so a pre-activation of about 17 is enough to make p(1−p) provably zero. That is not a strange value at all: it is what an unnormalised feature or a large bias produces on day one. 2. MSE on a saturated, wrong neuron does not move, ever. w stayed at 30.0000 , b at 50.0000 , loss pinned at 0.500000 for all 500 steps. BCE on the identical start crossed p < 0.5 at step 97 and finished at loss 0.000006 . 3. Finite differences lie in the same direction. At z = 71 the numeric gradient of MSE is 0.0 too, so the debugging tool I would reach for confirms the wrong story. The gradient really is zero; the function really is flat there. That is the trap: the maths is fine and the model is still broken. 4. The naive BCE is not usable at saturation either. At z = +800, t = 0 it raises ValueError: expected a positive input, got 0.0 because log(1 − p) becomes log(0) . The logit form max(z,0) − z·t + log1p(exp(−|z|)) returns 800.0 , which is the true value, without ever forming p . One honest correction. My first version of the training demo used the exam's own label t = 1 with p = 1 : both losses returned 0.0 and the "comparison" proved nothing, because a correct and saturated prediction has zero error under both. I had to make the neuron wrong ( t = 0 ) for the two losses to separate at all. A demo where both arms agree with each other is not a demo, it is decoration. ---

Security #26 — The token was random, just not unpredictable (CWE-338)

A password-reset token is not a secret number, it is a number the attacker cannot guess. Those are different requirements, and applications fail both separately:

the generator is a statistician's generator (Mersenne Twister, rand() , Math.random ),

which is uniform, fast, and fully reversible from its own output;

or the generator is fine but the seed is a clock reading, which leaves a few

thousand possibilities. Eight characters from a 32-symbol alphabet is 40 bits of "randomness" that collapses to log2(window) bits of real work. I measured both halves in one file, nothing contacted. The pattern I studied: # CWE-338 - the token was random, just not unpredictable. # Sandbox only: the "app" is a function in this file, nothing is contacted. # # Part A: an app that seeds from the clock. Brute force the seed back. # Part B: 624 raw 32-bit outputs are enough to rebuild the Mersenne Twister. import random import secrets import time ALPHA = "abcdefghijkmnopqrstuvwxyz23456789" # 32 symbols, no lookalikes OBSERVED_AT = 1793000000 # pretend "now" when the token leaked WINDOW = 600 # seconds either side of "now" def issue_token(seed_epoch, n=8): """The vulnerable app, as written: random seeded from the clock.""" r = random.Random(int(seed_epoch)) return "".join(r.choice(ALPHA) for _ in range(n)) # ---------------------------------------------------------------- part A want = issue_token(OBSERVED_AT - 37) # the token the attacker got hits = [c for c in range(OBSERVED_AT - WINDOW, OBSERVED_AT + WINDOW) if issue_token(c) == want] print("== A. seed recovery ==") print(f"observed token : {want}") print(f"candidates tried : {2 * WINDOW} (a +/-{WINDOW // 60} minute window around 'now')") print(f"seeds whose token match : {len(hits)} -> {[c - OBSERVED_AT for c in hits]} s from now") recovered = hits[0] print(f"attacker, from the seed : {issue_token(recovered + 1)}") print(f"app, one second later : {issue_token(recovered + 1)}") print(f"one hour of clock drift costs {2 * 3600} candidates, still nothing.") # ---------------------------------------------------------------- part B MASK = 0xFFFFFFFF def temper(y): y ^= y >> 11 y ^= (y << 7) & 0x9D2C5680 y ^= (y << 15) & 0xEFC60000 y ^= y >> 18 return y & MASK def unshift_right(y, shift): x = 0 for i in range(31, -1, -1): bit = (y >> i) & 1 if i + shift < 32: bit ^= (x >> (i + shift)) & 1 x |= bit << i return x def unshift_left(y, shift, mask): x = 0 for i in range(32): bit = (y >> i) & 1 if i - shift >= 0: bit ^= ((x >> (i - shift)) & 1) & ((mask >> i) & 1) x |= bit << i return x def untemper(y): y = unshift_right(y, 18) y = unshift_left(y, 15, 0xEFC60000) y = unshift_left(y, 7, 0x9D2C5680) y = unshift_right(y, 11) return y & MASK print() print("== B. state recovery ==") check = [random.getrandbits(32) for _ in range(200)] print(f"untemper(temper(x)) == x for 200 values : {all(untemper(temper(v)) == v for v in check)}") def issue_id(): """The same PRNG, exposed as a 32-bit identifier (an order number, say).""" return PRNG.getrandbits(32) PRNG = random.Random(20261029) leaked = [issue_id() for _ in range(624)] state = [untemper(v) for v in leaked] clone = random.Random() clone.setstate((3, tuple(state) + (624,), None)) predicted = [clone.getrandbits(32) for _ in range(5)] actual = [issue_id() for _ in range(5)] print(f"outputs collected : {len(leaked)}") print(f"next 5, predicted : {predicted}") print(f"next 5, actual : {actual}") print(f"identical : {predicted == actual}") # ---------------------------------------------------------------- the fix print() print("== the fix: the platform's own CSPRNG ==") good = secrets.token_urlsafe(16) print(f"secrets.token_urlsafe(16): {len(good)} chars from [A-Za-z0-9_-], 96 bits of entropy") print(f"two calls in the same second equal : " f"{secrets.token_urlsafe(16) == secrets.token_urlsafe(16)}") same = issue_token(OBSERVED_AT) == issue_token(OBSERVED_AT) print(f"clock-seeded token is deterministic : {same} (same second, same token)") Sandbox check (local only): == A. seed recovery == observed token : pd6eyzg5 candidates tried : 1200 (a +/-10 minute window around 'now') seeds whose token match : 1 -> [-37] s from now attacker, from the seed : 44ro5u28 app, one second later : 44ro5u28 one hour of clock drift costs 7200 candidates, still nothing. == B. state recovery == untemper(temper(x)) == x for 200 values : True outputs collected : 624 next 5, predicted : [2893647027, 1662812824, 3319793958, 3974632129, 2097200746] next 5, actual : [2893647027, 1662812824, 3319793958, 3974632129, 2097200746] identical : True == the fix: the platform's own CSPRNG == secrets.token_urlsafe(16): 22 chars from [A-Za-z0-9_-], 96 bits of entropy two calls in the same second equal : False clock-seeded token is deterministic : True (same second, same token) What I understood about preventing it: import secrets token = secrets.token_urlsafe(32) # 256 bits, OS CSPRNG ok = secrets.compare_digest(stored, provided) # constant time # never: random.seed(int(time.time())); never: random.random() for a credential What I understood: the two halves are not equally hard to defend against, and the order matters. Part A needs no cleverness at all: 1200 candidate reconstructions of a clock-seeded generator produced exactly one match, 37 seconds away from "now", and the next token followed from the recovered seed. Ten minutes of clock uncertainty costs 1200 guesses; an hour costs 7200. That attack does not care how the app slices the output stream, which is why time-seeding alone is fatal. Part B is the sharper one and needs more from the attacker: 624 consecutive 32-bit outputs, un-tempered word by word, rebuild the 19937-bit internal state, and from there the next five values are not predicted "well", they are identical — `identical: True . The caveat I have to write down honestly: I used getrandbits(32)` as the exposed value. If the app pushes those bits through random.choices with float weights, the mapping is lossy and recovery gets noisy. So the practical lesson is the reverse of the order I built it in: **seed recovery is the reliable half, state recovery is the bonus when the raw outputs leak** (order ids, nonces, timestamps mixed with counters). The fix is not a better seed, it is a different class of generator: secrets , which reads from the OS CSPRNG and is not reproducible by construction. Two calls in the same second differ ( False above); the clock-seeded one is True , same second, same token. ---

Day 26 notes

Concept #26: five measurements, all from real runs above. ✔ Security #26: both halves reproduced the prediction exactly; sandbox only, nothing contacted. ✔ 1574 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 026 of 1600 · Matías Rathgeb


[ inicio ]   [ proyectos ]   [ posts ]   [ daylog ]


Página estática. Sin cookies, sin javascript, sin fuentes externas.
Contacto: ver inicio.