-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssa.scm
More file actions
1751 lines (1579 loc) · 83.4 KB
/
Copy pathssa.scm
File metadata and controls
1751 lines (1579 loc) · 83.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; array-morphisms-ssa.scm
;;;
;;; SSA IR for fused forward+backward computation.
;;;
;;; Compiles a morph-variable loss node into a flat SSA program once,
;;; then replays the joint forward+backward computation every training step.
;;; Eliminates the lazy/eager boundary, fresh-copy overhead, and missed
;;; fusion opportunities that arise when forward and backward pass each
;;; build separate lazy trees.
;;;
;;; Phases:
;;; 1. morphism-to-ssa -- DFS over morphism-expr tree -> SSA program
;;; 2. ssa-vjp -- symbolic VJP over SSA bindings -> extended program
;;; 3. ssa-realize -- sequential executor (no context pooling)
;;; 4. ssa-realize/ctx -- context-pooled executor
;;;
;;; Key invariants:
;;; - Constants (concrete-array leaves) are stored in a hash-table keyed by
;;; gensym cid-symbols. Parameters are concrete-arrays whose underlying
;;; SRFI-4 vectors are updated in-place by the optimizer; the SSA constants
;;; table sees the updated values automatically each step.
;;; - Binding IDs are gensym symbols (bid-NNN for forward, adj-NNN for
;;; backward adjoints) serving as hash-table keys in the value table.
;;; - Reduction ops use (list 'reduce rop) as their op field to distinguish
;;; them from plain element-wise ops.
(module array-morphisms-ssa
(;; Data-type predicates/accessors
ssa-value?
ssa-binding-ref? ssa-const-ref?
ssa-value-id
;; SSA records
ssa-binding?
ssa-binding-name ssa-binding-op ssa-binding-inputs
ssa-binding-shape ssa-binding-dtype ssa-binding-meta
ssa-program?
ssa-program-constants ssa-program-morph-to-val
ssa-program-bindings ssa-program-outputs ssa-program-n-params
ssa-program-replay-plan
;; Compilation
morphism-to-ssa
ssa-constant-id
ssa-loss-binding-val
;; VJP
ssa-vjp
;; Execution
ssa-realize
ssa-realize/ctx
;; Replay plan ADTs
replay-ref?
rr-val rr-const
replay-instruction replay-instruction?
ri-gemm ri-gemm-strided ri-index ri-reduce ri-view
ri-flat-unary ri-flat-binary ri-flat-bias-broadcast
ri-gemm-epilogue ri-alias
;; Fusion pass
ssa-compute-use-counts
ssa-fusion-eligible?
ssa-element-wise-fusion-pass
;; Replay plan compilation and execution
compile-replay-plan
execute-replay-plan)
(import scheme (chicken base))
(import (only srfi-1 iota fold filter map for-each append-map filter-map every))
(import (only srfi-4
f64vector f64vector-set! f64vector-length
f32vector f32vector-set! f32vector-length))
(import (only srfi-69
make-hash-table
hash-table-ref
hash-table-ref/default
hash-table-set!
hash-table-walk
eq?-hash))
(import datatype matchable)
(import array-morphisms-core)
(import array-morphisms-index-fn)
(import array-morphisms-basic-ops)
(import array-morphisms-structural-ops)
(import array-morphisms-blas-exec)
(import array-morphisms-blas-compat)
(import array-morphisms-realization)
(import array-morphisms-context)
(import array-morphisms-morph-env)
(import (prefix array-morphisms-grad am:))
;;; ============================================================
;;; SSA Value ADT
;;;
;;; An ssa-value identifies either a binding result (binding-ref) or
;;; a constant array (const-ref). IDs are gensym symbols.
;;; ============================================================
(define-datatype ssa-value ssa-value?
(binding-ref (id symbol?))
(const-ref (cid symbol?)))
(define (ssa-binding-ref? v)
(cases ssa-value v (binding-ref (_) #t) (else #f)))
(define (ssa-const-ref? v)
(cases ssa-value v (const-ref (_) #t) (else #f)))
(define (ssa-value-id v)
"Return the gensym symbol identifying this ssa-value."
(cases ssa-value v
(binding-ref (id) id)
(const-ref (cid) cid)))
;;; ============================================================
;;; SSA Records
;;; ============================================================
;; One binding in the SSA program.
;; name : gensym symbol (bid-NNN or adj-NNN); key in value table
;; op : symbol (e.g. 'add) or list (e.g. '(reduce mean))
;; inputs : list of ssa-value
;; shape : vector (result shape)
;; dtype : symbol
;; meta : alist of extra info (index-fn, axes, perm, fn, ...)
(define-record ssa-binding name op inputs shape dtype meta)
;; The compiled SSA program.
;; constants : hash-table cid-symbol -> concrete-array
;; morph-to-val: morph-env stable-id (symbol) -> ssa-value (for ssa-constant-id)
;; bindings : list of ssa-binding in topological order
;; outputs : list of ssa-value (loss first, then param grads)
;; n-params : count of trainable parameter constants
;; replay-plan : #f until compiled; vector of replay-instruction (one per binding)
;; trace-info : #f until trace; morph-env bid-sym -> (concrete-array . is-pool?)
;; output-specs : #f until compiled; list of (integer | concrete-array) per output
;; integer = index into vals vector; concrete-array = const-ref value
(define-record ssa-program constants morph-to-val bindings outputs n-params
replay-plan trace-info output-specs)
;;; ============================================================
;;; Replay Plan ADTs
;;;
;;; Pre-compiled dispatch structures produced by compile-replay-plan.
;;; Used by execute-replay-plan to avoid per-step morphism rebuilding,
;;; BLAS eligibility re-evaluation, and context-vector allocation.
;;; ============================================================
;; Input reference: previous binding result (by 0-based position in vals vector)
;; or a constant (by cid-symbol from constants hash-table).
(define-datatype replay-ref replay-ref?
(rr-val (val-idx integer?))
(rr-const (cid symbol?)))
;; One pre-compiled instruction per SSA binding.
(define-datatype replay-instruction replay-instruction?
;; Row-major matmul: strides pre-computed at compile time.
(ri-gemm
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(in-A replay-ref?)
(in-B replay-ref?))
;; Strided matmul (at least one input is a transposed zero-copy view).
(ri-gemm-strided
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(in-A replay-ref?)
(in-B replay-ref?))
;; Element-wise / general index-fn op: strides pre-computed at compile time.
(ri-index
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(index-fn index-fn?)
(in-refs list?))
;; Reduction (sum, mean, max, ...): strides pre-computed at compile time.
(ri-reduce
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(src-dtype symbol?)
(rop symbol?)
(reduce-axes list?)
(reducer procedure?)
(keepdims? boolean?)
(in-ref replay-ref?))
;; Zero-copy view (transpose, reshape, slice): shares pool buffer with source.
(ri-view
(view-fn procedure?)
(in-ref replay-ref?))
;; Element-wise unary: output[i] = combiner(A[i])
;; Emitted when: 1 operand, operand and output both row-major with same shape.
(ri-flat-unary
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(combiner procedure?)
(in-A replay-ref?))
;; Element-wise binary same-shape: output[i] = combiner(A[i], B[i])
;; Emitted when: 2 operands, all row-major with identical shape.
(ri-flat-binary
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(combiner procedure?)
(in-A replay-ref?)
(in-B replay-ref?))
;; Bias broadcast: output[i] = combiner(A[i], B[i mod N])
;; Emitted when: A row-major = output shape; B row-major shape [N] = last dim of output.
;; N baked in at compile time.
(ri-flat-bias-broadcast
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(combiner procedure?)
(bias-N integer?)
(in-A replay-ref?)
(in-B replay-ref?))
;; GEMM with in-place element-wise epilogue: one buffer, one combined kernel.
;; BLAS GEMM writes out-pool-idx buffer C[M,N] = A[M,K]*B[K,N],
;; then epilogue applied in-place to C.
;; epilogue-kind: 'unary | 'bias-broadcast
;; epilogue-N: bias length for 'bias-broadcast; 0 for 'unary
;; bias-ref: unused sentinel for 'unary; bias replay-ref for 'bias-broadcast
(ri-gemm-epilogue
(out-pool-idx integer?)
(out-shape vector?)
(out-strides vector?)
(out-dtype symbol?)
(in-A replay-ref?)
(in-B replay-ref?)
(epilogue-kind symbol?)
(epilogue-comb procedure?)
(epilogue-N integer?)
(bias-ref replay-ref?))
;; Alias for the epilogue binding position after ri-gemm-epilogue.
;; Advances alloc-ctr to stay in sync with trace-time pool allocation.
;; Returns the already-computed epilogue result from in-ref (the GEMM step).
(ri-alias
(pool-idx integer?)
(shape vector?)
(strides vector?)
(dtype symbol?)
(in-ref replay-ref?)))
;;; ============================================================
;;; SSA Fusion Helpers (element-wise fusion pass)
;;;
;;; Implements MoA's psi-composition theorem at the SSA IR level:
;;; Psi(f, Psi(g, A)) = Psi(f o g, A)
;;; Two adjacent element-wise bindings with use-count=1 are collapsed
;;; into a single binding whose combiner is the composition of theirs.
;;; ============================================================
(define (ssa-binding-combiner b)
"Extract element-wise combiner from an SSA binding's meta.
Forward bindings carry (index-fn . compute-index-fn); backward bindings
carry explicit (combiner . proc) embedded during ssa-vjp."
(let* ((meta (ssa-binding-meta b))
(cp (assq 'combiner meta)))
(if cp
(cdr cp)
(let ((ip (assq 'index-fn meta)))
(if (and ip (compute-index-fn? (cdr ip)))
(compute-index-fn-combiner (cdr ip))
(error "ssa-binding-combiner: no combiner in meta"
(ssa-binding-name b) (ssa-binding-op b)))))))
(define (ssa-binding-elementwise? b)
"True when b is an element-wise compute op (not matmul, reduce, or structural)."
(let ((op (ssa-binding-op b)))
(and (not (eq? op 'matmul))
(not (and (pair? op) (eq? (car op) 'reduce)))
(not (memq op '(reshape transpose broadcast-expand slice))))))
(define (ssa-compute-use-counts bindings)
"Return hash-table: binding-name-sym -> integer (number of consuming bindings)."
(let ((counts (make-hash-table)))
(for-each (lambda (b)
(hash-table-set! counts (ssa-binding-name b) 0))
bindings)
(for-each
(lambda (b)
(for-each
(lambda (v)
(cases ssa-value v
(binding-ref (bid)
(when (hash-table-ref/default counts bid #f)
(hash-table-set! counts bid
(+ 1 (hash-table-ref counts bid)))))
(const-ref (_) #f)))
(ssa-binding-inputs b)))
bindings)
counts))
(define (ssa-binding-has-combiner? b)
"True when b carries an extractable element-wise combiner in meta."
(let ((meta (ssa-binding-meta b)))
(or (and (assq 'combiner meta) #t)
(let ((ip (assq 'index-fn meta)))
(and ip (compute-index-fn? (cdr ip)))))))
(define (ssa-fusion-eligible? producer consumer use-counts)
"True when producer and consumer can be fused by MoA psi-composition.
Requires: use-count(producer)=1, consumer's first input is producer's output,
same shape, both element-wise, both have extractable combiners."
(let* ((p-name (ssa-binding-name producer))
(p-count (hash-table-ref/default use-counts p-name 0))
(c-in0 (and (pair? (ssa-binding-inputs consumer))
(car (ssa-binding-inputs consumer)))))
(and (= p-count 1)
(cases ssa-value c-in0
(binding-ref (bid) (eq? bid p-name))
(else #f))
(equal? (ssa-binding-shape producer) (ssa-binding-shape consumer))
(ssa-binding-elementwise? producer)
(ssa-binding-elementwise? consumer)
(ssa-binding-has-combiner? producer)
(ssa-binding-has-combiner? consumer))))
(define (fuse-two-ssa-bindings producer consumer)
"Fuse producer into consumer via combiner composition.
The fused binding inherits consumer's name (preserving downstream refs).
Producer's intermediate buffer is eliminated."
(let* ((p-inputs (ssa-binding-inputs producer))
(c-inputs (ssa-binding-inputs consumer))
(c-other (cdr c-inputs))
(fused-inputs (append p-inputs c-other))
(p-comb (ssa-binding-combiner producer))
(c-comb (ssa-binding-combiner consumer))
(p-nargs (length p-inputs))
(fused-comb (compose-flat-combiners p-comb p-nargs c-comb (length c-other)))
(base-meta (filter (lambda (kv)
(not (memq (car kv) '(combiner index-fn fused?))))
(ssa-binding-meta consumer)))
(fused-meta (cons `(combiner . ,fused-comb)
(cons `(fused? . #t) base-meta))))
(make-ssa-binding (ssa-binding-name consumer)
(ssa-binding-op consumer)
fused-inputs
(ssa-binding-shape consumer)
(ssa-binding-dtype consumer)
fused-meta)))
(define (ssa-element-wise-fusion-pass prog)
"Apply MoA psi-composition to eligible adjacent binding pairs.
Greedy left-to-right scan: whenever a producer P has use-count=1 and
its only consumer C immediately follows, fuse them into one binding F.
Chains of length > 2 are handled by re-presenting F as the new producer.
Safety constraint: fusion is only applied when ALL of producer's inputs
have the same shape as the producer's output (flat/non-broadcasting ops),
ensuring identity index functions are valid in the fused binding."
(let* ((bindings (ssa-program-bindings prog))
(use-counts (ssa-compute-use-counts bindings))
;; Shape lookup: id-sym -> shape vector (bindings + constants)
(shape-of-eb (make-env-builder))
;; Eliminated-binding membership set: id-sym -> #t
(elim-eb (make-env-builder)))
(for-each (lambda (b)
(env-builder-extend! shape-of-eb
(ssa-binding-name b) (ssa-binding-shape b)))
bindings)
(hash-table-walk (ssa-program-constants prog)
(lambda (k v) (env-builder-extend! shape-of-eb k (morph-shape v))))
;; True when all inputs of b have the same shape as b's output.
(define (flat-producer? b)
(let ((b-shape (ssa-binding-shape b)))
(every (lambda (inp)
(let ((id (cases ssa-value inp
(binding-ref (bid) bid)
(const-ref (cid) cid))))
(equal? (env-builder-lookup shape-of-eb id) b-shape)))
(ssa-binding-inputs b))))
(let loop ((bs bindings) (result '()))
(cond
((null? bs)
(make-ssa-program
(ssa-program-constants prog)
(ssa-program-morph-to-val prog)
(reverse result)
(ssa-program-outputs prog)
(ssa-program-n-params prog)
#f #f #f))
((env-builder-lookup elim-eb (ssa-binding-name (car bs)))
(loop (cdr bs) result))
((and (pair? (cdr bs))
(not (env-builder-lookup elim-eb (ssa-binding-name (cadr bs))))
(ssa-fusion-eligible? (car bs) (cadr bs) use-counts)
(flat-producer? (car bs)))
(let ((fused (fuse-two-ssa-bindings (car bs) (cadr bs))))
(env-builder-extend! elim-eb (ssa-binding-name (car bs)) #t)
;; Update shape-of for the fused binding (inherits consumer's name+shape)
(env-builder-extend! shape-of-eb
(ssa-binding-name fused) (ssa-binding-shape fused))
(loop (cons fused (cddr bs)) result)))
(else
(loop (cdr bs) (cons (car bs) result)))))))
;;; ============================================================
;;; Phase 1: morphism-to-ssa
;;;
;;; Post-order DFS over the morphism-expr tree rooted at loss-mv.
;;; concrete-array leaves become constants; morphism-expr / reduction-morphism
;;; nodes become SSA bindings.
;;; ============================================================
(define (morphism-to-ssa loss-mv)
"Compile the morph-variable graph rooted at loss-mv into an SSA program.
Returns an ssa-program with outputs = (list loss-binding-val) and n-params = 0."
(let* ((constants (make-hash-table)) ; cid-symbol -> concrete-array
(visited-eb (make-env-builder)) ; stable-id (symbol) -> ssa-value
(bindings '())) ; accumulated in reverse topo order
(define (emit-binding! op inputs shape dtype meta)
(let* ((bid (gensym 'bid-))
(b (make-ssa-binding bid op inputs shape dtype meta)))
(set! bindings (cons b bindings)) ; O(1); reversed at end
(binding-ref bid)))
(define (visit m)
(or (env-builder-lookup visited-eb (morph-stable-id m))
(cases array-morphism m
(concrete-array (data shape strides offset dtype alloc-id batch-axis)
(let* ((cid (gensym 'cid-))
(v (const-ref cid)))
(hash-table-set! constants cid m)
(env-builder-extend! visited-eb (morph-stable-id m) v)
v))
(morphism-expr (morph-id op operands index-fn shape dtype metadata batch-axis)
(let* ((input-vals (map visit operands))
;; Normalize: morph-transpose stores key 'permutation; we use 'perm
(norm-meta (if (eq? op 'transpose)
(let ((pe (assq 'permutation metadata)))
(if pe
(cons (cons 'perm (cdr pe))
(filter (lambda (x)
(not (eq? (car x) 'permutation)))
metadata))
metadata))
metadata))
(meta (cons (cons 'index-fn index-fn) norm-meta))
(v (emit-binding! op input-vals shape dtype meta)))
(env-builder-extend! visited-eb (morph-stable-id m) v)
v))
(reduction-morphism (morph-id rop operand reduce-axes index-fn shape dtype batch-axis)
(let* ((src-val (visit operand))
(meta (list (cons 'axes reduce-axes)
(cons 'index-fn index-fn)
(cons 'src-shape (morph-shape operand))
(cons 'keepdims? (reduction-index-fn-keepdims? index-fn))))
(v (emit-binding! (list 'reduce rop) (list src-val) shape dtype meta)))
(env-builder-extend! visited-eb (morph-stable-id m) v)
v)))))
(let* ((loss-m (am:var-value loss-mv))
(loss-val (visit loss-m)))
(make-ssa-program constants (env-builder-env visited-eb)
(reverse bindings) (list loss-val) 0 #f #f #f))))
;;; ============================================================
;;; Accessors into a compiled program
;;; ============================================================
(define (ssa-constant-id prog m)
"Return (const-ref cid) for morphism m if it is a constant in prog, else #f."
(let ((v (morph-env-lookup (ssa-program-morph-to-val prog) (morph-stable-id m))))
(and v (ssa-const-ref? v) v)))
(define (ssa-loss-binding-val prog)
"Return the ssa-value for the loss node (first output)."
(car (ssa-program-outputs prog)))
;;; ============================================================
;;; Phase 2: ssa-vjp
;;;
;;; Symbolic reverse-mode AD over SSA bindings.
;;; Appends backward bindings to fwd-prog's bindings and returns an
;;; extended ssa-program whose outputs are:
;;; (loss-binding-val . param-grad-binding-vals)
;;; ============================================================
(define (ssa-vjp fwd-prog param-const-vals loss-binding-val)
"Compute symbolic VJP of fwd-prog with respect to params.
param-const-vals: list of (const-ref cid) ssa-values for trainable params.
loss-binding-val: (binding-ref bid) ssa-value for the loss node.
Returns extended ssa-program."
(let* (;; Build shape/dtype lookup from forward bindings (single env-builder)
(fwd-bindings (ssa-program-bindings fwd-prog))
(binding-sd-eb (make-env-builder)) ; sym -> (shape . dtype)
;; Accumulate backward bindings in reverse order; reverse at end
(bwd-bindings '())
;; Adjoint table: bid-symbol -> ssa-value (the accumulated dL/d(bid))
(adjoint-eb (make-env-builder))
;; Param gradient table: cid-symbol -> ssa-value
(param-grad-eb (make-env-builder))
;; Set of trainable param cid-symbols for fast membership test
(param-cid-eb (make-env-builder))
;; Loss shape/dtype
(loss-bid-sym (ssa-value-id loss-binding-val)))
;; Index forward binding shapes and dtypes
(for-each (lambda (b)
(env-builder-extend! binding-sd-eb
(ssa-binding-name b)
(cons (ssa-binding-shape b) (ssa-binding-dtype b))))
fwd-bindings)
;; Also index constant shapes/dtypes
(hash-table-walk (ssa-program-constants fwd-prog)
(lambda (cid m)
(env-builder-extend! binding-sd-eb cid (cons (morph-shape m) (morph-dtype m)))))
;; Register trainable param cid-symbols
(for-each (lambda (v)
(env-builder-extend! param-cid-eb (ssa-value-id v) #t))
param-const-vals)
;; Lookup helpers
(define (val-shape v)
(let ((sd (env-builder-lookup binding-sd-eb (ssa-value-id v))))
(and sd (car sd))))
(define (val-dtype v)
(let ((sd (env-builder-lookup binding-sd-eb (ssa-value-id v))))
(and sd (cdr sd))))
;; emit! -- create a new backward SSA binding (O(1) cons; reversed at end)
(define (emit! op inputs shape dtype meta)
(let* ((adj-id (gensym 'adj-))
(b (make-ssa-binding adj-id op inputs shape dtype meta)))
(set! bwd-bindings (cons b bwd-bindings))
(env-builder-extend! binding-sd-eb adj-id (cons shape dtype))
(binding-ref adj-id)))
;; Accumulate adjoint for a binding-ref input
(define (accumulate-adjoint! bid-sym new-val shape dtype)
(let ((existing (env-builder-lookup adjoint-eb bid-sym)))
(if existing
(let ((sum (emit! 'add (list existing new-val) shape dtype '())))
(env-builder-extend! adjoint-eb bid-sym sum))
(env-builder-extend! adjoint-eb bid-sym new-val))))
;; Accumulate gradient for a const-ref param input
(define (accumulate-param-grad! cid-sym new-val shape dtype)
(let ((existing (env-builder-lookup param-grad-eb cid-sym)))
(if existing
(let ((sum (emit! 'add (list existing new-val) shape dtype '())))
(env-builder-extend! param-grad-eb cid-sym sum))
(env-builder-extend! param-grad-eb cid-sym new-val))))
;; Dispatch adjoint accumulation based on ssa-value type
(define (accumulate-input-adjoint! input-val new-val)
(let ((shape (val-shape input-val))
(dtype (val-dtype input-val)))
(cases ssa-value input-val
(binding-ref (bid)
(accumulate-adjoint! bid new-val shape dtype))
(const-ref (cid)
(when (env-builder-lookup param-cid-eb cid)
(accumulate-param-grad! cid new-val shape dtype))))))
;; emit-reduce-sum-to! -- reduce g-val to target-shape
(define (emit-reduce-sum-to! g-val g-shape target-shape dtype)
(let* ((g-rank (vector-length g-shape))
(t-vec (if (vector? target-shape)
target-shape
(list->vector target-shape)))
(t-rank (vector-length t-vec)))
;; Step 1: sum leading extra dims
(let* ((extra (- g-rank t-rank))
(cur (if (> extra 0)
(emit! (list 'reduce 'sum) (list g-val)
(vector-drop-left g-shape extra)
dtype
(list (cons 'axes (iota extra))
(cons 'keepdims? #f)
(cons 'src-shape g-shape)))
g-val))
(cur-shape (val-shape cur)))
;; Step 2: sum broadcast (size-1) dims
(let loop ((k 0) (cur cur) (cur-shape cur-shape))
(if (>= k t-rank)
cur
(let ((t-dim (vector-ref t-vec k))
(g-dim (vector-ref cur-shape k)))
(if (and (= t-dim 1) (> g-dim 1))
(let* ((new-shape (let* ((len (vector-length cur-shape))
(nv (make-vector len)))
(do ((i 0 (+ i 1))) ((= i len) nv)
(vector-set! nv i (vector-ref cur-shape i)))))
(_ (vector-set! new-shape k 1))
(r (emit! (list 'reduce 'sum) (list cur)
new-shape dtype
(list (cons 'axes (list k))
(cons 'keepdims? #t)
(cons 'src-shape cur-shape)))))
(loop (+ k 1) r new-shape))
(loop (+ k 1) cur cur-shape))))))))
;; vector-drop-left -- remove first n elements of a vector
(define (vector-drop-left v n)
(let* ((len (vector-length v))
(new-len (- len n))
(result (make-vector new-len)))
(do ((i 0 (+ i 1)))
((= i new-len) result)
(vector-set! result i (vector-ref v (+ i n))))))
;; emit-broadcast-grad! -- broadcast reduced gradient back to src-shape
;; src-shape: original input shape; reduced-axes: axes that were reduced
;; keepdims?: whether the reduction kept dimensions
(define (emit-broadcast-grad! g-val g-shape src-shape reduced-axes keepdims? dtype)
(let* ((in-rank (vector-length src-shape))
;; Compute keepdims shape (insert 1s at reduced positions)
(kd-shape (list->vector
(map (lambda (i)
(if (member i reduced-axes) 1
(vector-ref src-shape i)))
(iota in-rank))))
;; Reshape g to keepdims shape if needed
(g-kd (if keepdims?
g-val
(emit! 'reshape (list g-val) kd-shape dtype '())))
;; Emit ones-like constant for src-shape
(ones-data (allocate-typed-vector dtype (shape-size src-shape)))
(_ (let loop ((i 0) (n (shape-size src-shape)))
(when (< i n)
(typed-vector-set! ones-data dtype i 1.0)
(loop (+ i 1) n))))
(ones-const (make-morphism ones-data (vector->list src-shape) dtype))
(ones-cid (gensym 'cid-))
(_ (hash-table-set! (ssa-program-constants fwd-prog) ones-cid ones-const))
(_ (env-builder-extend! binding-sd-eb ones-cid (cons src-shape dtype)))
(ones-val (const-ref ones-cid)))
;; morph* broadcasts: g-kd * ones -> src-shape
(emit! 'mul (list g-kd ones-val) src-shape dtype `((combiner . ,*)))))
;; emit-scalar-const! -- emit a scalar constant of given value
(define (emit-scalar-const! value dtype)
(let* ((data (allocate-typed-vector dtype 1))
(_ (typed-vector-set! data dtype 0 value))
(m (make-morphism data '(1) dtype))
(cid (gensym 'cid-)))
(hash-table-set! (ssa-program-constants fwd-prog) cid m)
(env-builder-extend! binding-sd-eb cid (cons (vector 1) dtype))
(const-ref cid)))
;; Seed: dL/dL = ones-like(loss) stored as a constant
(let* ((loss-bid (find-fwd-binding fwd-bindings loss-bid-sym))
(loss-shape (ssa-binding-shape loss-bid))
(loss-dtype (ssa-binding-dtype loss-bid))
(seed-data (allocate-typed-vector loss-dtype (shape-size loss-shape)))
(_ (let loop ((i 0) (n (shape-size loss-shape)))
(when (< i n)
(typed-vector-set! seed-data loss-dtype i 1.0)
(loop (+ i 1) n))))
(seed-const (make-morphism seed-data (vector->list loss-shape) loss-dtype))
(seed-cid (gensym 'cid-))
(_ (hash-table-set! (ssa-program-constants fwd-prog) seed-cid seed-const))
(_ (env-builder-extend! binding-sd-eb seed-cid (cons loss-shape loss-dtype)))
(seed-val (const-ref seed-cid)))
(env-builder-extend! adjoint-eb loss-bid-sym seed-val))
;; Backward sweep: iterate bindings in reverse order
(for-each
(lambda (b)
(let* ((bid-sym (ssa-binding-name b))
(g-val (env-builder-lookup adjoint-eb bid-sym)))
(when g-val
(let* ((op (ssa-binding-op b))
(inputs (ssa-binding-inputs b))
(shape (ssa-binding-shape b))
(dtype (ssa-binding-dtype b))
(meta (ssa-binding-meta b))
(g-shape (val-shape g-val)))
(cond
;; add(x, y) -- dx = reduce-sum-to(g, shape-x); dy = reduce-sum-to(g, shape-y)
((eq? op 'add)
(let* ((x-val (list-ref inputs 0))
(y-val (list-ref inputs 1))
(x-shape (val-shape x-val))
(y-shape (val-shape y-val)))
(let ((dx (emit-reduce-sum-to! g-val g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx))
(let ((dy (emit-reduce-sum-to! g-val g-shape y-shape dtype)))
(accumulate-input-adjoint! y-val dy))))
;; sub(x, y) -- dx = reduce-sum-to(g, shape-x); dy = reduce-sum-to(-g, shape-y)
((eq? op 'sub)
(let* ((x-val (list-ref inputs 0))
(y-val (list-ref inputs 1))
(x-shape (val-shape x-val))
(y-shape (val-shape y-val)))
(let ((dx (emit-reduce-sum-to! g-val g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx))
(let* ((neg-g (emit! 'negate (list g-val) g-shape dtype
`((combiner . ,(lambda (x) (- x))))))
(dy (emit-reduce-sum-to! neg-g g-shape y-shape dtype)))
(accumulate-input-adjoint! y-val dy))))
;; mul(x, y) -- dx = reduce-sum-to(g*y, shape-x); dy = reduce-sum-to(g*x, shape-y)
((eq? op 'mul)
(let* ((x-val (list-ref inputs 0))
(y-val (list-ref inputs 1))
(x-shape (val-shape x-val))
(y-shape (val-shape y-val)))
(let* ((gy (emit! 'mul (list g-val y-val) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! gy g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx))
(let* ((gx (emit! 'mul (list g-val x-val) g-shape dtype
`((combiner . ,*))))
(dy (emit-reduce-sum-to! gx g-shape y-shape dtype)))
(accumulate-input-adjoint! y-val dy))))
;; div(x, y) -- dx = g/y; dy = -g*x/y^2
((eq? op 'div)
(let* ((x-val (list-ref inputs 0))
(y-val (list-ref inputs 1))
(x-shape (val-shape x-val))
(y-shape (val-shape y-val)))
(let* ((g-over-y (emit! 'div (list g-val y-val) g-shape dtype
`((combiner . ,/))))
(dx (emit-reduce-sum-to! g-over-y g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx))
(let* ((y2 (emit! 'mul (list y-val y-val) y-shape dtype
`((combiner . ,*))))
(x-over-y2 (emit! 'div (list x-val y2) g-shape dtype
`((combiner . ,/))))
(neg-dy (emit! 'mul (list g-val x-over-y2) g-shape dtype
`((combiner . ,*))))
(neg-dy2 (emit! 'negate (list neg-dy) g-shape dtype
`((combiner . ,(lambda (x) (- x))))))
(dy (emit-reduce-sum-to! neg-dy2 g-shape y-shape dtype)))
(accumulate-input-adjoint! y-val dy))))
;; pow(x, n) -- dx = g * n * x^(n-1); dn skipped (n usually not a param)
((eq? op 'pow)
(let* ((x-val (list-ref inputs 0))
(n-val (list-ref inputs 1))
(x-shape (val-shape x-val)))
;; n_minus_1 = n - 1 (using scalar 1 constant)
(let* ((one-val (emit-scalar-const! 1.0 dtype))
(nm1 (emit! 'sub (list n-val one-val)
(val-shape n-val) dtype
`((combiner . ,(lambda (a b) (- a b))))))
(xpow (emit! 'pow (list x-val nm1) g-shape dtype
`((combiner . ,expt))))
(n-xpow (emit! 'mul (list n-val xpow) g-shape dtype
`((combiner . ,*))))
(dx-raw (emit! 'mul (list g-val n-xpow) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx))))
;; negate(x) -- dx = -g
((eq? op 'negate)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(neg-g (emit! 'negate (list g-val) g-shape dtype
`((combiner . ,(lambda (x) (- x))))))
(dx (emit-reduce-sum-to! neg-g g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; abs(x) -- dx = g * sign(x)
((eq? op 'abs)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(sign-fn (lambda (xv)
(cond ((> xv 0.0) 1.0)
((< xv 0.0) -1.0)
(else 0.0))))
(sign-x (emit! 'map (list x-val) x-shape dtype
(list (cons 'fn sign-fn))))
(dx-raw (emit! 'mul (list g-val sign-x) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; sqrt(x) -- dx = g / (2 * sqrt(x)) i.e. g / (2 * fwd-output)
;; fwd-output is (binding-ref bid-sym) at this point in execution
((eq? op 'sqrt)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(two-val (emit-scalar-const! 2.0 dtype))
;; fwd output = this binding
(fwd-out (binding-ref bid-sym))
(two-out (emit! 'mul (list two-val fwd-out) g-shape dtype
`((combiner . ,*))))
(dx-raw (emit! 'div (list g-val two-out) g-shape dtype
`((combiner . ,/))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; exp(x) -- dx = g * exp(x) = g * fwd-output
((eq? op 'exp)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(fwd-out (binding-ref bid-sym))
(dx-raw (emit! 'mul (list g-val fwd-out) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; log(x) -- dx = g / x
((eq? op 'log)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(dx-raw (emit! 'div (list g-val x-val) g-shape dtype
`((combiner . ,/))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; sin(x) -- dx = g * cos(x)
((eq? op 'sin)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(cos-x (emit! 'cos (list x-val) x-shape dtype
`((combiner . ,cos))))
(dx-raw (emit! 'mul (list g-val cos-x) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; cos(x) -- dx = -g * sin(x)
((eq? op 'cos)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(sin-x (emit! 'sin (list x-val) x-shape dtype
`((combiner . ,sin))))
(neg-sin (emit! 'negate (list sin-x) x-shape dtype
`((combiner . ,(lambda (x) (- x))))))
(dx-raw (emit! 'mul (list g-val neg-sin) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; relu(x) -- dx = g * heaviside(x)
;; Decomposed as: hx = map(heaviside, x); dx = mul(g, hx)
;; (abs-style decomposition keeps rebuild-morphism simple)
((eq? op 'relu)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(hx (emit! 'map (list x-val) x-shape dtype
`((fn . ,(lambda (xv) (if (> xv 0.0) 1.0 0.0)))
(combiner . ,(lambda (xv) (if (> xv 0.0) 1.0 0.0))))))
(dx-raw (emit! 'mul (list g-val hx) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; sigmoid(x) -- dx = g * deriv where deriv = s*(1-s), s = forward output
((eq? op 'sigmoid)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(fwd-out (binding-ref bid-sym))
(deriv (emit! 'map (list fwd-out) g-shape dtype
`((fn . ,(lambda (sv) (* sv (- 1.0 sv))))
(combiner . ,(lambda (sv) (* sv (- 1.0 sv)))))))
(dx-raw (emit! 'mul (list g-val deriv) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; tanh(x) -- dx = g * (1-t^2) where t = tanh(x) = forward output
((eq? op 'tanh)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(fwd-out (binding-ref bid-sym))
(deriv (emit! 'map (list fwd-out) g-shape dtype
`((fn . ,(lambda (tv) (- 1.0 (* tv tv))))
(combiner . ,(lambda (tv) (- 1.0 (* tv tv)))))))
(dx-raw (emit! 'mul (list g-val deriv) g-shape dtype
`((combiner . ,*))))
(dx (emit-reduce-sum-to! dx-raw g-shape x-shape dtype)))
(accumulate-input-adjoint! x-val dx)))
;; matmul(A, B) -- dA = g @ B^T; dB = A^T @ g
((eq? op 'matmul)
(let* ((a-val (list-ref inputs 0))
(b-val (list-ref inputs 1))
(a-shape (val-shape a-val))
(b-shape (val-shape b-val))
;; Determine 2D shapes; shape = [M K] [K N] -> [M N]
(rank (vector-length a-shape))
(perm-t (transpose-perm rank))
(b-t-shape (permute-shape b-shape perm-t))
(a-t-shape (permute-shape a-shape perm-t))
(bt-val (emit! 'transpose (list b-val) b-t-shape dtype
(list (cons 'perm perm-t))))
(at-val (emit! 'transpose (list a-val) a-t-shape dtype
(list (cons 'perm perm-t))))
(da-val (emit! 'matmul (list g-val bt-val) a-shape dtype '()))
(db-val (emit! 'matmul (list at-val g-val) b-shape dtype '())))
(accumulate-input-adjoint! a-val da-val)
(accumulate-input-adjoint! b-val db-val)))
;; transpose(x, perm) -- dx = transpose(g, inv-perm)
((eq? op 'transpose)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(perm (cdr (assq 'perm meta)))
(inv-perm (invert-permutation perm))
(dx (emit! 'transpose (list g-val) x-shape dtype
(list (cons 'perm inv-perm)))))
(accumulate-input-adjoint! x-val dx)))
;; reshape(x) -- dx = reshape(g, original-shape)
((eq? op 'reshape)
(let* ((x-val (list-ref inputs 0))
(x-shape (val-shape x-val))
(dx (emit! 'reshape (list g-val) x-shape dtype '())))
(accumulate-input-adjoint! x-val dx)))
;; (reduce mean) -- dx = broadcast(g / n, src-shape)
((equal? op '(reduce mean))
(let* ((src-val (list-ref inputs 0))
(src-shape (cdr (assq 'src-shape meta)))
(axes (cdr (assq 'axes meta)))
(keepdims? (cdr (assq 'keepdims? meta)))
(n (apply * (map (lambda (a) (vector-ref src-shape a)) axes)))
(n-val (emit-scalar-const! (exact->inexact n) dtype))
(g-over-n (emit! 'div (list g-val n-val) g-shape dtype '()))
(dx (emit-broadcast-grad! g-over-n g-shape src-shape
axes keepdims? dtype)))
(accumulate-input-adjoint! src-val dx)))
;; (reduce sum) -- dx = broadcast(g, src-shape)
((equal? op '(reduce sum))
(let* ((src-val (list-ref inputs 0))
(src-shape (cdr (assq 'src-shape meta)))
(axes (cdr (assq 'axes meta)))
(keepdims? (cdr (assq 'keepdims? meta)))
(dx (emit-broadcast-grad! g-val g-shape src-shape
axes keepdims? dtype)))
(accumulate-input-adjoint! src-val dx)))
;; (reduce max) -- not needed for standard MLP; skip
((equal? op '(reduce max))
(void))
;; map(x, fn) -- no grad (non-differentiable; sign fn used in abs backward)
((eq? op 'map)
(void))
(else
(void)))))))
(reverse fwd-bindings))
;; Emit add(loss, zero-const) as the final backward binding.
;;
;; The context's compute-last-uses! extends a buffer's lifetime only when
;; it appears as an INPUT to a later allocation-rec. The loss forward binding
;; has no backward binding that references it directly (the seed is stored as
;; a pre-computed constant), so loss.alloc-id's last-use stays at its birth
;; step and backward bindings can reuse its buffer slot in replay mode.
;;
;; add(loss, zero) is a two-operand op -- can-zero-copy? returns #f so a real
;; allocation is recorded. input-ids includes loss.alloc-id, which forces
;; compute-last-uses! to extend loss's lifetime to this final step, preventing
;; any backward binding from aliasing its buffer.
(let* ((loss-bid-b (find-fwd-binding fwd-bindings loss-bid-sym))
(loss-shape (ssa-binding-shape loss-bid-b))