Skip to content

Commit 034028c

Browse files
committed
Sparsity
1 parent 0c3c8e4 commit 034028c

1 file changed

Lines changed: 17 additions & 2 deletions

File tree

benchmarks/nn.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@
3333
N_TRAIN, N_TEST = 500, 200
3434
LR, STEPS, CHUNK = 0.5, 60, 250
3535

36+
# Drop zero-valued pixels from the (dominant) layer-0 contraction. A background
37+
# pixel contributes 0 * weight = 0, so skipping those rows shrinks the join
38+
# *exactly* — the result is identical, and the speedup scales with the fraction
39+
# of zeros (a dark background). On dense inputs it is a no-op. Toggle to compare.
40+
SKIP_ZERO_PIXELS = True
41+
3642

3743
def fashion_mnist():
3844
try:
@@ -154,6 +160,12 @@ def init_weight(inp: int, out: int):
154160
)
155161
ctx.register_table("weight", ctx.sql(seed).cache())
156162

163+
# The zero-pixel skip. fwd0 has no WHERE (it forwards all samples), so it
164+
# needs a fresh `WHERE`; g0 already filters to the train split, so it
165+
# appends an `AND`. Empty strings when the flag is off.
166+
zero_where = "WHERE images <> 0" if SKIP_ZERO_PIXELS else ""
167+
zero_and = "AND images <> 0" if SKIP_ZERO_PIXELS else ""
168+
157169
for step in range(STEPS):
158170
#
159171
# --- forward pass -----------------------------------------------------
@@ -172,6 +184,7 @@ def init_weight(inp: int, out: int):
172184
WITH a AS (
173185
SELECT sample, height * {SIDE} + width AS inp, images AS val
174186
FROM mnist.pixels
187+
{zero_where}
175188
UNION ALL
176189
-- the constant-1 bias unit
177190
SELECT sample,
@@ -309,6 +322,7 @@ def init_weight(inp: int, out: int):
309322
SELECT sample, height * {SIDE} + width AS inp, images AS val
310323
FROM mnist.pixels
311324
WHERE sample IN (SELECT sample FROM data WHERE split = 'train')
325+
{zero_and}
312326
UNION ALL
313327
SELECT sample,
314328
(SELECT DISTINCT width FROM weight WHERE layer = 0) AS inp,
@@ -334,8 +348,9 @@ def init_weight(inp: int, out: int):
334348
UNION ALL SELECT 1 AS layer, inp, out, val FROM g1
335349
UNION ALL SELECT 2 AS layer, inp, out, val FROM g2
336350
)
337-
SELECT w.layer, w.inp, w.out, w.val - {LR} * g.val AS val, w.width
338-
FROM weight w JOIN grad g
351+
SELECT w.layer, w.inp, w.out,
352+
w.val - {LR} * COALESCE(g.val, 0) AS val, w.width
353+
FROM weight w LEFT JOIN grad g
339354
ON w.layer = g.layer AND w.inp = g.inp AND w.out = g.out
340355
""").cache()
341356
ctx.deregister_table("weight")

0 commit comments

Comments
 (0)