brotensor/
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
22 / 24
91.7%
Branches:
-
-%
Functions:
17 / 18
94.4%

src/jit/trace_dag.h
Line Branch Exec Source
1 #pragma once
2
3 #include <brotensor/tensor.h>
4 #include <cstdint>
5 #include <cstddef>
6 #include <vector>
7 #include <unordered_map>
8 #include <string>
9
10 namespace brotensor::jit {
11
12 enum class TraceOpKind : uint8_t {
13 Input = 0,
14 Add,
15 Sub,
16 Mul,
17 Div,
18 AddScalar,
19 SubScalar,
20 MulScalar,
21 DivScalar,
22 ScalarSub,
23 ScalarDiv,
24 FMA,
25 SiLU,
26 GELU,
27 ReLU,
28 RMSNorm,
29 LayerNorm,
30 Modulate,
31 Tanh,
32 Sigmoid,
33 Copy,
34 Where,
35 Clamp,
36 Cast,
37 Const,
38 Neg,
39 Exp,
40 Log,
41 Sqrt,
42 Rsqrt,
43 Abs
44 };
45
46 const char* op_kind_name(TraceOpKind op);
47
48 // How a node's buffer maps onto the trace's dominant (rows, cols) shape.
49 //
50 // Row, Col and Scalar are the broadcast forms: a (1, D) row, a (R, 1) column,
51 // or a (1, 1) scalar combined against an (R, D) activation. The emitters turn
52 // these into a different address computation for that operand, not into a
53 // materialised expansion — a broadcast operand contributes D, R, or 1 elements
54 // of traffic, not R*D.
55 enum class BroadcastKind : uint8_t { Full = 0, Row = 1, Scalar = 2, Col = 3 };
56
57 BroadcastKind broadcast_of(int node_rows, int node_cols, int rows, int cols);
58
59 9058 struct TraceNode {
60 3992 int id = -1;
61 3992 TraceOpKind op = TraceOpKind::Input;
62 std::vector<int> inputs;
63 std::vector<int> outputs; // consumer node indices
64 3992 float scalar = 0.0f;
65 3992 float scalar2 = 0.0f;
66 // Destination or input data pointer — and null for every node the fused
67 // kernel evaluates in registers and never spills.
68 //
69 // A buffer is present on exactly three kinds of node: an Input and an
70 // in-place target, whose storage the caller owns and whose address is
71 // therefore stable for the whole trace; a store() destination, likewise
72 // caller-owned; and a live-at-end intermediate, which end_trace()
73 // allocates and installs into the Tensor the caller is still holding.
74 // Every other node — every dead intermediate — carries a null buffer and
75 // is addressed by `id` alone, which is the reason the tracer no longer
76 // allocates a full-size tensor per traced op. Nothing hashes the buffer,
77 // so a null one cannot collide two different traces.
78 3992 void* buffer = nullptr;
79 3992 Device device = Device::CPU;
80 3992 Dtype dtype = Dtype::FP32;
81 3992 int rows = 0;
82 3992 int cols = 0;
83 3992 bool is_inplace = false;
84 3992 int inplace_target_slot = -1;
85 3992 bool is_live_at_end = false;
86 };
87
88 43 class TraceDAG {
89 public:
90 406 TraceDAG() = default;
91
92 int register_input(const Tensor& t);
93 int add_node(TraceOpKind op, const std::vector<int>& inputs, float scalar = 0.0f,
94 void* buffer = nullptr, const Device& dev = Device::CPU,
95 Dtype dt = Dtype::FP32, int rows = 0, int cols = 0,
96 float scalar2 = 0.0f);
97 int add_inplace_node(TraceOpKind op, int target_slot, int arg_slot,
98 void* buffer, float scalar = 0.0f, float scalar2 = 0.0f);
99
100 void analyze_liveness();
101 // A 64-bit digest for the in-process TraceCache (compute_hash) — and, for
102 // a key that must never be a wrong hit (the on-disk kernel cache), every
103 // field a compiler reads from the DAG, in full (key_material: one fixed-
104 // width little-endian record per node; never a buffer address).
105 uint64_t compute_hash() const;
106 std::string key_material() const;
107
108 // The trace's dominant shape: the largest (rows * cols) any node carries.
109 // Every non-broadcast node must match it; (1, cols), (rows, 1), and (1, 1)
110 // nodes are broadcast operands.
111 void dominant_shape(int& rows, int& cols) const;
112
113 854 const std::vector<TraceNode>& nodes() const noexcept { return nodes_; }
114 6763 std::vector<TraceNode>& nodes() noexcept { return nodes_; }
115 142505 const TraceNode& node(int id) const { return nodes_.at(id); }
116 102 size_t node_count() const noexcept { return nodes_.size(); }
117
118 // True when `slot` still describes `t` (same buffer, shape, dtype, device).
119 bool slot_matches(int slot, const Tensor& t) const;
120 void reset();
121
122 // Builds the reverse-mode automatic differentiation (VJP) TraceDAG for this
123 // forward TraceDAG.
124 // - If `target_input_idx >= 0`, returns a single-output backward TraceDAG
125 // computing d(loss)/d(input[target_input_idx]).
126 // - If `target_input_idx < 0`, returns a fused multi-output backward TraceDAG
127 // computing d(loss)/d(input[i]) for every primal Input node in order.
128 // The returned backward TraceDAG has the same primal Input nodes in slots
129 // [0..num_inputs-1], followed by an Input node for `grad_output` (`dL/dy`).
130 TraceDAG backward(int target_input_idx = -1) const;
131
132 private:
133 std::vector<TraceNode> nodes_;
134 std::unordered_map<const void*, int> input_ptr_to_slot_;
135 };
136
137 // ─── TraceContext ───────────────────────────────────────────────────────────
138 //
139 // The thread's trace in progress, and the symbolic tensors it has handed out.
140 //
141 // A traced op does not produce a tensor; it produces a *name* for a node of
142 // the DAG. record_op() returns that name as a Tensor with a null `data`, a
143 // real shape/dtype/device and `jit_slot` set — so the expression the caller
144 // wrote goes on type-checking and composing exactly as before while allocating
145 // nothing. Node identity follows suit: a symbolic operand is identified by its
146 // slot, and only a caller-owned buffer (an input, an in-place target, a store()
147 // destination) is still identified by its pointer, which is safe precisely
148 // because the caller owns it and it cannot be recycled mid-trace.
149 //
150 // The catch a tracked-pointer table solves: a value the caller still holds
151 // when the trace closes has to end up owning a real buffer it can read from.
152 // Every symbolic Tensor handed out is recorded here as slot -> Tensor*, and
153 // Tensor's move ctor / move assignment / destructor keep that table pointing
154 // at wherever the caller moved the value (see detail::jit_slot_retarget in
155 // tensor.h). end() then allocates for exactly those slots.
156 class TraceContext {
157 public:
158 static TraceContext& current();
159
160 void begin();
161 // Runs liveness, gives every still-held live-at-end intermediate a real
162 // buffer, and returns the DAG. Any symbolic Tensor the caller still holds
163 // whose value the fused kernel only consumes internally is neutralised to
164 // an empty tensor — its contents were never computed to memory.
165 TraceDAG end();
166 // Throws away a trace in progress and neutralises every symbolic Tensor
167 // the caller still holds to an empty tensor. Leaves the context idle.
168 void discard();
169 207 bool is_active() const noexcept { return active_; }
170
171 int get_or_register_slot(const Tensor& t);
172
173 // Records `op` and returns the symbolic Tensor standing for its result.
174 Tensor record_op(TraceOpKind op, const std::vector<int>& in_slots, float scalar,
175 const Device& dev, Dtype dt, int rows, int cols,
176 float scalar2 = 0.0f);
177
178 // Records a Copy into `dst`, a buffer the caller already owns.
179 void record_store(int src_slot, const Tensor& dst);
180
181 // Records a 3-arg cast(src, dst, out_dtype) into `dst`.
182 void record_cast_out(int src_slot, const Tensor& src, Tensor& dst, Dtype out_dtype);
183
184 int record_inplace_op(TraceOpKind op, int target_slot, int arg_slot, float scalar,
185 Tensor& target_tensor, float scalar2 = 0.0f);
186
187 // Tensor lifetime callback: the symbolic Tensor for `slot` moved from
188 // `from` to `to`, or was destroyed (`to` == nullptr). Never throws and
189 // never allocates — Tensor's move and destructor are noexcept.
190 void retarget(int slot, const Tensor* from, Tensor* to) noexcept;
191
192 private:
193 21 TraceContext() = default;
194
195 // Allocates and installs the buffers for live-at-end nodes that do not
196 // already have one; demotes a live-at-end node nobody can observe.
197 void materialize_();
198 // Turns every still-tracked symbolic Tensor into an ordinary empty one.
199 void release_tracked_() noexcept;
200
201 7 bool active_ = false;
202 TraceDAG dag_;
203 std::unordered_map<const void*, int> active_ptr_to_slot_;
204 std::unordered_map<int, Tensor*> slot_to_tensor_;
205 };
206
207 } // namespace brotensor::jit
208