|
Última actualización: 2026-12-02
DAY 027 OF 1600 · 2026-10-30 Day 027 — The shape was right and the picture was gone; and the lock was on the wrong lineA student's private learning log · one concept at a time. Date: 2026-10-30 · Day: 27 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #27 — A pooling layer can return the right shape and the wrong pictureMA04, Deep Learning, mock question 9. Input 5x5, filter 3x3, output 3x3, and the formula m = (n − l + 2p)/s + 1 . Find s and p . The answer sheet says stride 1, padding 0, and then adds one sentence that I read four times: *other options can be valid, as long as the equality is kept.* That sentence is the whole question. It is true, and it is worse than the answer sheet lets on. I enumerated s from 1 to 8 and p from 0 to 8 for n = 5 , l = 3 , m = 3 and got 17 pairs that satisfy the equation. I did not stop at the arithmetic: I ran a real 3x3 max-pool for every one of them. All 17 return a 3x3 output. The shape check passes 17 times out of 17 and it is the only check the formula gives you. Then I marked, for each one, which input cells no window ever touches. Four pairs read all 25 cells. The rest leave 9, 16 or 21 cells unread. I put a 9 in the cell that the most of them miss — (0, 3) — and **13 of the 17 return a 3x3 picture whose maximum is 1**. The answer that scores full marks can be the configuration that throws away the brightest pixel in the image, and the output shape is identical. The other half of the same arithmetic is the truncation. With n = 6 , l = 3 , s = 2 , p = 0 the formula gives (6 − 3)/2 + 1 = 2.5 , and integer division makes it 2. That .5 is not a rounding detail: it is one entire column and one entire row that never enter a window. 11 of the 36 cells are never read — row 5 and column 5, counting the corner once. The grid's maximum is 9, and it sits in four cells; two of them, (0, 5) and (5, 0) , are in the discarded strip. The output still shows 9 only because a different copy of 9 was inside a window. On a real image, the one cell that mattered does not need a duplicate. What I tried today: one script, stdlib only: a real max-pool that also counts how many windows read each cell, the same formula over n = 4..12 to see exactly where truncation eats input, and the full enumeration of the inverse — every solution verified by running the pooling, not by trusting the algebra. # pool_shape.py - MA04 (Deep Learning), mock question 9: the shape formula # m = (n - l + 2p)/s + 1. stdlib only. # # Three measurements: # 1. real 3x3 max-pooling on a 6x6 grid with s=2, p=0: which input cells # actually reach the output, and which ones are never read at all # 2. the same formula over a table of n: when the division is not exact, # integer division truncates and input is silently dropped # 3. the inverse is not a function: every (s, p) pair that gives the SAME m # for n=5, l=3, m=3, each one verified by running the pooling for real, # then the same grid with its brightest cell placed where some of them # never look W = H = 6 GRID = [ [ 3, 1, 4, 1, 5, 9], [ 2, 6, 5, 3, 5, 8], [ 9, 7, 9, 3, 2, 3], [ 8, 4, 6, 2, 6, 4], [ 3, 3, 8, 3, 2, 7], [ 9, 5, 0, 2, 8, 4], ] def out_size(n, l, p, s): """The mock's formula, with the division made explicit (and truncating).""" return (n - l + 2 * p) // s + 1 def maxpool(img, l, p, s): """Real max-pooling. Returns (output, cover, padded) where cover[y][x] is how many windows read the padded input cell (y, x).""" n = len(img) m = out_size(n, l, p, s) padded = [[0] * (n + 2 * p) for _ in range(n + 2 * p)] for y in range(n): for x in range(n): padded[y + p][x + p] = img[y][x] cover = [[0] * (n + 2 * p) for _ in range(n + 2 * p)] out = [[0] * m for _ in range(m)] for oy in range(m): for ox in range(m): best = None for dy in range(l): for dx in range(l): y, x = oy * s + dy, ox * s + dx cover[y][x] += 1 v = padded[y][x] best = v if best is None else max(best, v) out[oy][ox] = best return out, cover, padded def unread_input(img, l, p, s): """Input cells (original coordinates) that no window ever touches.""" n = len(img) _, cover, _ = maxpool(img, l, p, s) return [(y, x) for y in range(n) for x in range(n) if cover[y + p][x + p] == 0] print("== 1. real pooling, 6x6 input, l=3, s=2, p=0 ==") out, cover, padded = maxpool(GRID, 3, 0, 2) print("formula m = (6 - 3 + 0)//2 + 1 =", out_size(W, 3, 0, 2)) print("output size %dx%d" % (len(out), len(out[0]))) print("output %s" % out) never = unread_input(GRID, 3, 0, 2) print("input cells never read %d of %d" % (len(never), W * H)) print("they are exactly row 5 (%d cells) + column 5 (%d cells) - the corner = %d" % (H, W, H + W - 1)) print("values that never reached out %s" % [GRID[y][x] for y, x in never]) print("max of the discarded values %d" % max(GRID[y][x] for y, x in never)) top = max(max(r) for r in GRID) locs = [(y, x) for y in range(H) for x in range(W) if GRID[y][x] == top] print("grid max is %d at %s" % (top, locs)) print("of those, never read: %s" % [c for c in locs if c in never]) print("output max is %d, and it survives only because another 9 was read" % max(max(r) for r in out)) print() print("== 2. exact division vs truncation (l=3, s=2, p=0) ==") print(" n (n-l)/s exact? m input cells cells inside windows dropped") for n in range(4, 13): m = out_size(n, 3, 0, 2) span = (m - 1) * 2 + 3 # last padded index a window touches + 1 dropped = n - span exact = (n - 3) % 2 == 0 print(" %2d %4.1f %-5s %2d %2d %2d %d" % (n, (n - 3) / 2, exact, m, n, span, dropped)) print() print("== 3. the inverse is a set, not a value (n=5, l=3, m=3) ==") INPUT5 = [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] sols = [(s, p) for s in range(1, 9) for p in range(0, 9) if out_size(5, 3, p, s) == 3] print("solutions for n=5, l=3, m=3: %d" % len(sols)) print("s,p pairs: %s" % sols) for s, p in sols: o, _, _ = maxpool(INPUT5, 3, p, s) print(" s=%d p=%d real output %dx%d input cells never read: %2d" % (s, p, len(o), len(o[0]), len(unread_input(INPUT5, 3, p, s)))) print("all give 3x3: %s" % all(maxpool(INPUT5, 3, p, s)[0].__len__() == 3 for s, p in sols)) # where is the cell that the most solutions never look at? miss = {} for s, p in sols: for cell in unread_input(INPUT5, 3, p, s): miss[cell] = miss.get(cell, 0) + 1 worst, count = max(miss.items(), key=lambda kv: kv[1]) HOT = [row[:] for row in INPUT5] HOT[worst[0]][worst[1]] = 9 print() print("brightest cell placed at %s (missed by %d of %d solutions):" % (worst, count, len(sols))) for s, p in sols: o, _, _ = maxpool(HOT, 3, p, s) print(" s=%d p=%d output max = %d %s" % (s, p, max(max(r) for r in o), "DISCARDED" if (worst in unread_input(HOT, 3, p, s)) else "seen")) lost = [sp for sp in sols if max(max(r) for r in maxpool(HOT, 3, sp[1], sp[0])[0]) < 9] print("solutions that return the same 3x3 shape and lose the 9: %d of %d" % (len(lost), len(sols))) print("the shape check cannot tell them apart: every one of them returns 3x3") Real output: == 1. real pooling, 6x6 input, l=3, s=2, p=0 == formula m = (6 - 3 + 0)//2 + 1 = 2 output size 2x2 output [[9, 9], [9, 9]] input cells never read 11 of 36 they are exactly row 5 (6 cells) + column 5 (6 cells) - the corner = 11 values that never reached out [9, 8, 3, 4, 7, 9, 5, 0, 2, 8, 4] max of the discarded values 9 grid max is 9 at [(0, 5), (2, 0), (2, 2), (5, 0)] of those, never read: [(0, 5), (5, 0)] output max is 9, and it survives only because another 9 was read == 2. exact division vs truncation (l=3, s=2, p=0) == n (n-l)/s exact? m input cells cells inside windows dropped 4 0.5 False 1 4 3 1 5 1.0 True 2 5 5 0 6 1.5 False 2 6 5 1 7 2.0 True 3 7 7 0 8 2.5 False 3 8 7 1 9 3.0 True 4 9 9 0 10 3.5 False 4 10 9 1 11 4.0 True 5 11 11 0 12 4.5 False 5 12 11 1 == 3. the inverse is a set, not a value (n=5, l=3, m=3) == solutions for n=5, l=3, m=3: 17 s,p pairs: [(1, 0), (2, 1), (3, 2), (3, 3), (4, 3), (4, 4), (5, 4), (5, 5), (5, 6), (6, 5), (6, 6), (6, 7), (7, 6), (7, 7), (7, 8), (8, 7), (8, 8)] s=1 p=0 real output 3x3 input cells never read: 0 s=2 p=1 real output 3x3 input cells never read: 0 s=3 p=2 real output 3x3 input cells never read: 0 s=3 p=3 real output 3x3 input cells never read: 0 s=4 p=3 real output 3x3 input cells never read: 16 s=4 p=4 real output 3x3 input cells never read: 9 s=5 p=4 real output 3x3 input cells never read: 16 s=5 p=5 real output 3x3 input cells never read: 16 s=5 p=6 real output 3x3 input cells never read: 16 s=6 p=5 real output 3x3 input cells never read: 16 s=6 p=6 real output 3x3 input cells never read: 16 s=6 p=7 real output 3x3 input cells never read: 21 s=7 p=6 real output 3x3 input cells never read: 16 s=7 p=7 real output 3x3 input cells never read: 16 s=7 p=8 real output 3x3 input cells never read: 21 s=8 p=7 real output 3x3 input cells never read: 16 s=8 p=8 real output 3x3 input cells never read: 16 all give 3x3: True brightest cell placed at (0, 3) (missed by 13 of 17 solutions): s=1 p=0 output max = 9 seen s=2 p=1 output max = 9 seen s=3 p=2 output max = 9 seen s=3 p=3 output max = 9 seen s=4 p=3 output max = 1 DISCARDED s=4 p=4 output max = 1 DISCARDED s=5 p=4 output max = 1 DISCARDED s=5 p=5 output max = 1 DISCARDED s=5 p=6 output max = 1 DISCARDED s=6 p=5 output max = 1 DISCARDED s=6 p=6 output max = 1 DISCARDED s=6 p=7 output max = 1 DISCARDED s=7 p=6 output max = 1 DISCARDED s=7 p=7 output max = 1 DISCARDED s=7 p=8 output max = 1 DISCARDED s=8 p=7 output max = 1 DISCARDED s=8 p=8 output max = 1 DISCARDED solutions that return the same 3x3 shape and lose the 9: 13 of 17 the shape check cannot tell them apart: every one of them returns 3x3 What I understood from it: the formula is a **necessary condition on the shape, not a definition of the layer**. It tells me which (n, l, p, s) are legal; it says nothing about whether the layer sees the data. The dropped cells are not a rounding error to be forgotten, they are (n − l) mod s — one column here, one row there, and a table is enough to see that every odd n loses one. When a shape formula divides, the remainder is the part of the input that silently stops existing, so the honest question is not "does m match" but "for which (s, p) is the division exact"; if none is, the input size or the filter has to change. And for the exam question itself: 17 answers satisfy the equation, 4 of them see every pixel, and the split is not luck — the 4 have s ≤ l = 3 , so consecutive windows still touch. All 13 that lose data have s > l : the windows step further than they reach, the gaps between them are input no window ever reads, and no amount of padding closes a gap in the middle. "Correct" and "equivalent" are different words and this question measures the first one only. --- Security #27 — Twenty withdrawals, one balance, and a lock on the wrong line (CWE-362)The bug class is check-then-act: the code reads a value, decides on it, and writes later. If anything can happen between the read and the write — another thread, another request, another worker process — the decision was made on a value that is no longer true. The classic form is a balance. The pattern is not "missing lock", and that is why it survives review: this code usually has a lock. I built a loopback-only sandbox: one ThreadingHTTPServer on 127.0.0.1:8761 , one toy account holding 100, and 20 concurrent requests each asking to withdraw 100. A barrier releases all 20 handlers together after parsing and before the read, so what gets measured is the defect and not my laptop's scheduler. Three implementations of the same function: naive — read, work 50 ms (one database round-trip), check, write. No lock. write_lock — the same, but the write is wrapped in threading.Lock . This is the version someone adds after the bug is reported. atomic — the lock contains the read, the check and the write. Result: naive approves 20 of 20 and write_lock approves 20 of 20. Both report the same balance to the application — [100] , every single request — and both end with a final balance of 0 after 2000 left an account that held 100. That last number is the part I did not expect to be the interesting one: the balance does not go negative, because all 20 computed 100 − 100 = 0 from the stale read and wrote the same value; it is a lost update. So a reconciliation that looks at the balance sees 0 , which is exactly what a correct system would show after one legitimate withdrawal. The damage is 1900 and the balance column cannot distinguish it from no damage at all. Only the third version approves 1 of 20. The lock was never missing in version two; it was in the wrong place — around the assignment instead of around the decision. This is where the fix gets uncomfortable, because the single-process lock is the answer only if there is exactly one process. Two app workers, two replicas, or the same code run as a cron job next to the web server, and each one holds its own lock over its own copy of the state — the race is back, unchanged. The lock has to be the one the storage engine owns: a conditional update that reports whether it applied ( UPDATE … SET balance = balance − ? WHERE balance >= ? and then read the row count), a SELECT … FOR UPDATE inside a transaction, or a unique constraint on an idempotency key so a retried request cannot be paid twice. And the check must be part of the same statement as the write. If the answer is two statements, it is not a fix, it is the bug with extra steps. The pattern I studied — the difference between the two functions is the position of one line, and it is not the line that writes. In withdraw_naive the sequence is bal = state["balance"] … if bal >= amount: … state["balance"] = bal - amount . In withdraw_atomic the exact same three steps sit inside with guard: . Nothing else changes — not the arithmetic, not the amount, not the HTTP handler. The lock moved up two lines and the result went from 20/20 to 1/20. What I understood about preventing it: the unit of protection is not the write, it is the decision . Whatever line makes the choice has to be inside the same exclusive region as the line that acts on it, and in a networked system that region has to be the database's, not the process's. A lock that only orders the writes removes the corrupted interleaving and keeps the wrong one: 20 requests that each believe they were the first. The whole sandbox, one file, so the measurement can be repeated: # race.py - CWE-362/CWE-367: check-then-act on a shared balance. # Sandbox only: one loopback server on 127.0.0.1, one toy account, no real data. # # Three implementations of the same withdraw(): # naive read, (pause), check, write -> the check inspects a stale copy # write_lock lock ONLY around the write -> a lock, and still useless # atomic lock around read+check+write -> one winner # # Each is hit with 20 concurrent requests for 100 against an opening balance of 100. # The 20 handlers are released together AFTER parsing and BEFORE the read, so what # is measured is the defect itself and not this machine's scheduler. import json import threading import time import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse, parse_qs PORT = 8761 OPENING = 100 AMOUNT = 100 N = 20 WINDOW = 0.05 # the read-modify-write window, i.e. one DB round-trip state = {"balance": OPENING} guard = threading.Lock() gate = threading.Barrier(N, timeout=10) def withdraw_naive(amount): bal = state["balance"] # read time.sleep(WINDOW) # the round-trip if bal >= amount: # check a value that may be stale time.sleep(WINDOW) # more work before the write state["balance"] = bal - amount # write what was computed from the stale read return True, bal return False, state["balance"] def withdraw_write_lock(amount): bal = state["balance"] # read time.sleep(WINDOW) if bal >= amount: with guard: # the lock only protects the assignment state["balance"] = bal - amount return True, bal return False, state["balance"] def withdraw_atomic(amount): with guard: # read, check and write in one critical section bal = state["balance"] time.sleep(WINDOW) if bal < amount: return False, bal state["balance"] = bal - amount return True, bal MODES = {"naive": withdraw_naive, "write_lock": withdraw_write_lock, "atomic": withdraw_atomic} class Handler(BaseHTTPRequestHandler): def do_GET(self): q = parse_qs(urlparse(self.path).query) mode = (q.get("mode") or ["naive"])[0] amount = int((q.get("amount") or [str(AMOUNT)])[0]) try: gate.wait() # all 20 requests are in flight at once except threading.BrokenBarrierError: pass ok, seen = MODES[mode](amount) body = json.dumps({"approved": ok, "balance_seen": seen, "balance_after": state["balance"]}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *a): pass def run(mode): global gate state["balance"] = OPENING gate = threading.Barrier(N, timeout=10) results = [] lock = threading.Lock() def one(): url = "http://127.0.0.1:%d/withdraw?mode=%s&amount=%d" % (PORT, mode, AMOUNT) with urllib.request.urlopen(url, timeout=20) as r: d = json.loads(r.read()) with lock: results.append(d) threads = [threading.Thread(target=one) for _ in range(N)] for t in threads: t.start() for t in threads: t.join() approved = [r for r in results if r["approved"]] print("-- %s --" % mode) print(" approved %d of %d" % (len(approved), N)) print(" rejected %d of %d" % (N - len(approved), N)) print(" balance the app checked %s" % sorted({r["balance_seen"] for r in results})) print(" opening balance %d" % OPENING) print(" approved total %d" % (len(approved) * AMOUNT)) print(" booked against balance %d" % (len(approved) * AMOUNT - OPENING)) print(" final balance %d" % state["balance"]) print() srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler) threading.Thread(target=srv.serve_forever, daemon=True).start() print("sandbox server on 127.0.0.1:%d, account balance %d, %d concurrent requests of %d" % (PORT, OPENING, N, AMOUNT)) print("read-modify-write window: %.0f ms" % (WINDOW * 1000)) print() try: for m in ("naive", "write_lock", "atomic"): run(m) finally: srv.shutdown() print("Two of the three approve every request. The one that does not is the one") print("whose critical section contains the read.") Sandbox check (local only): sandbox server on 127.0.0.1:8761, account balance 100, 20 concurrent requests of 100 read-modify-write window: 50 ms -- naive -- approved 20 of 20 rejected 0 of 20 balance the app checked [100] opening balance 100 approved total 2000 booked against balance 1900 final balance 0 -- write_lock -- approved 20 of 20 rejected 0 of 20 balance the app checked [100] opening balance 100 approved total 2000 booked against balance 1900 final balance 0 -- atomic -- approved 1 of 20 rejected 19 of 20 balance the app checked [0, 100] opening balance 100 approved total 100 booked against balance 0 final balance 0 Two of the three approve every request. The one that does not is the one whose critical section contains the read. What I understood: two of the three versions approve every request, and I would have shipped the second one believing it was fixed, because it has a lock in it and the lock is real. The measurement that separates them is not "is there a lock" but "what does the app think the balance was when it said yes". All 20 got 100 . A balance of 0 at the end, in every single run, for all three versions — the number that looks healthy is the number that hides 1900. --- Day 27 notesConcept #27: real 3x3 max-pool on a 6x6 grid with s=2, p=0 → 2x2 output, 11 of 36 input cells never read; (n − l) mod s is exactly the dropped strip; for n=5, l=3, m=3 there are 17 legal (s, p) pairs, 13 of them lose a 9 placed at (0, 3), and every one of the 17 returns 3x3. Code ran, output above. ✔ Security #27: check-then-act on a shared balance (CWE-362 / CWE-367). 20/20 approved with no lock, 20/20 with the lock around the write only, 1/20 when the lock contains the read. 2000 out of 100, final balance 0 in all three cases. Sandbox only, 127.0.0.1. ✔ Both scripts run twice with an empty diff : the numbers above are not one lucky interleaving. ✔ 1573 days left. One at a time. Written by my own daily machine, checked by me. · Day 027 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |