torobi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +71 -0
  3. data/Cargo.lock +539 -0
  4. data/Cargo.toml +6 -0
  5. data/LICENSE +21 -0
  6. data/README.md +259 -0
  7. data/config/ops.yml +230 -0
  8. data/docs/plan.md +3982 -0
  9. data/docs/vendoring.md +656 -0
  10. data/engine/Cargo.toml +35 -0
  11. data/engine/build.rs +253 -0
  12. data/engine/src/checkpoint.rs +513 -0
  13. data/engine/src/executor.rs +257 -0
  14. data/engine/src/export.rs +431 -0
  15. data/engine/src/fixtures.rs +518 -0
  16. data/engine/src/graph.rs +115 -0
  17. data/engine/src/init.rs +65 -0
  18. data/engine/src/interp.rs +985 -0
  19. data/engine/src/lib.rs +62 -0
  20. data/engine/src/main.rs +97 -0
  21. data/engine/src/memory.rs +109 -0
  22. data/engine/src/mlxc/array.rs +454 -0
  23. data/engine/src/mlxc/error.rs +205 -0
  24. data/engine/src/mlxc/fast.rs +46 -0
  25. data/engine/src/mlxc/handle.rs +155 -0
  26. data/engine/src/mlxc/io.rs +268 -0
  27. data/engine/src/mlxc/memory.rs +56 -0
  28. data/engine/src/mlxc/metal.rs +24 -0
  29. data/engine/src/mlxc/mod.rs +55 -0
  30. data/engine/src/mlxc/nn.rs +38 -0
  31. data/engine/src/mlxc/ops.rs +477 -0
  32. data/engine/src/mlxc/quantized.rs +405 -0
  33. data/engine/src/mlxc/random.rs +161 -0
  34. data/engine/src/mlxc/transforms.rs +439 -0
  35. data/engine/src/op.rs +745 -0
  36. data/engine/src/optimizer.rs +650 -0
  37. data/engine/src/plan.rs +1638 -0
  38. data/engine/src/runtime.rs +377 -0
  39. data/engine/src/session.rs +1523 -0
  40. data/engine/src/state.rs +1007 -0
  41. data/engine/src/tensor.rs +331 -0
  42. data/ext/torobi/Cargo.toml +21 -0
  43. data/ext/torobi/extconf.rb +42 -0
  44. data/ext/torobi/src/gvl.rs +182 -0
  45. data/ext/torobi/src/lib.rs +1037 -0
  46. data/lib/torobi/adapter_file.rb +184 -0
  47. data/lib/torobi/batch.rb +55 -0
  48. data/lib/torobi/checkpoint.rb +60 -0
  49. data/lib/torobi/dsl/builder.rb +414 -0
  50. data/lib/torobi/dsl/handle.rb +156 -0
  51. data/lib/torobi/dsl/layers.rb +82 -0
  52. data/lib/torobi/dsl.rb +35 -0
  53. data/lib/torobi/errors.rb +88 -0
  54. data/lib/torobi/export.rb +534 -0
  55. data/lib/torobi/freeze.rb +24 -0
  56. data/lib/torobi/freshness.rb +57 -0
  57. data/lib/torobi/grad_cache.rb +143 -0
  58. data/lib/torobi/graph_config.rb +301 -0
  59. data/lib/torobi/hooks.rb +439 -0
  60. data/lib/torobi/ir/dimensions.rb +26 -0
  61. data/lib/torobi/ir/dtype.rb +28 -0
  62. data/lib/torobi/ir/graph/check.rb +116 -0
  63. data/lib/torobi/ir/graph.rb +52 -0
  64. data/lib/torobi/ir/input_spec.rb +39 -0
  65. data/lib/torobi/ir/json.rb +45 -0
  66. data/lib/torobi/ir/node_spec.rb +52 -0
  67. data/lib/torobi/ir/parameter_spec.rb +67 -0
  68. data/lib/torobi/ir/ref.rb +52 -0
  69. data/lib/torobi/ir/source.rb +65 -0
  70. data/lib/torobi/ir.rb +23 -0
  71. data/lib/torobi/journal.rb +310 -0
  72. data/lib/torobi/lora.rb +190 -0
  73. data/lib/torobi/memory.rb +50 -0
  74. data/lib/torobi/metallib.rb +50 -0
  75. data/lib/torobi/mlx_prebuilt.json +24 -0
  76. data/lib/torobi/mlx_prebuilt.rb +378 -0
  77. data/lib/torobi/models/build.rb +37 -0
  78. data/lib/torobi/models/description.rb +59 -0
  79. data/lib/torobi/models/gemma3.rb +273 -0
  80. data/lib/torobi/models/llama.rb +381 -0
  81. data/lib/torobi/models/modern_bert.rb +513 -0
  82. data/lib/torobi/models/padding.rb +27 -0
  83. data/lib/torobi/models/windows.rb +53 -0
  84. data/lib/torobi/ops.rb +81 -0
  85. data/lib/torobi/preflight.rb +136 -0
  86. data/lib/torobi/provenance.rb +75 -0
  87. data/lib/torobi/quantization.rb +151 -0
  88. data/lib/torobi/replay.rb +229 -0
  89. data/lib/torobi/runner.rb +419 -0
  90. data/lib/torobi/session.rb +855 -0
  91. data/lib/torobi/shape.rb +438 -0
  92. data/lib/torobi/tensor_data.rb +178 -0
  93. data/lib/torobi/version.rb +5 -0
  94. data/lib/torobi/weights.rb +108 -0
  95. data/lib/torobi.rb +67 -0
  96. data/licenses/MLX.txt +21 -0
  97. data/licenses/README.md +16 -0
  98. data/licenses/gguflib.txt +21 -0
  99. data/licenses/mlx-c.txt +21 -0
  100. data/licenses/mlx-rs.txt +27 -0
  101. metadata +229 -0
@@ -0,0 +1,438 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Shape and dtype inference, one rule per manifest entry. Rules work on
5
+ # shapes whose nil dimensions are symbolic: nil unifies with anything,
6
+ # concrete dimensions must match exactly. Everything raises ConfigError
7
+ # naming the node and op, so a shape mistake is reported at build time.
8
+ #
9
+ # One emission is one `Shape::Inference`: what it reads, and where to
10
+ # say a refusal happened. The rules are its methods, so each reads
11
+ # those rather than being handed them. What is left here at the top is
12
+ # dimension arithmetic the DSL also asks for, which needs no emission.
13
+ module Shape
14
+ # The rules `Inference` implements, which must be exactly the set
15
+ # `config/ops.yml` names. Declared rather than left implicit in the
16
+ # methods, so the two can be compared instead of remembered.
17
+ RULES = %i[
18
+ parameter same_as_input broadcast transpose reshape slice reduce
19
+ matmul take sdpa cross_entropy cast quantized_matmul
20
+ ].freeze
21
+
22
+ # The quantizations MLX has kernels for (docs/qlora.md section 3.3).
23
+ # Checked where a graph is written, so a width no group divides is
24
+ # refused with the linear's name rather than by a kernel.
25
+ GROUP_SIZES = [32, 64, 128].freeze
26
+ BITS = [2, 3, 4, 5, 6, 8].freeze
27
+ QUANTIZATION_MODES = %w[affine].freeze
28
+
29
+ # [shape, dtype] for one emission.
30
+ def self.infer(rule, inputs:, params:, attrs:, where:)
31
+ Inference.new(inputs:, params:, attrs:, where:).call(rule)
32
+ end
33
+
34
+ # `dim` divided into `count` equal parts, as the length of each: what
35
+ # splitting a value or its width into heads asks. Refused, in the DSL's
36
+ # own words, when `count` is not a positive count, when `dim` is
37
+ # symbolic, or when it does not divide.
38
+ def self.divide!(dim, count, into:, where:)
39
+ given = count
40
+ count = Integer(count, exception: false)
41
+ raise ConfigError, "#{where}: #{given.inspect} #{into} is not a count" unless count&.positive?
42
+ raise ConfigError, "#{where}: the dimension being divided must be concrete" if dim.nil?
43
+ unless (dim % count).zero?
44
+ raise ConfigError,
45
+ "#{where}: #{dim} does not divide into #{count} #{into}"
46
+ end
47
+
48
+ dim / count
49
+ end
50
+
51
+ # `axis` counted from the front, however it was written.
52
+ def self.axis!(axis, rank, where:)
53
+ normalized = axis.negative? ? axis + rank : axis
54
+ unless (0...rank).cover?(normalized)
55
+ raise ConfigError, "#{where}: axis #{axis} is out of range for rank #{rank}"
56
+ end
57
+
58
+ normalized
59
+ end
60
+
61
+ # One emission's shape and dtype: the handles it reads, the parameters
62
+ # it uses, its attributes, and `where` for what it says on refusing.
63
+ class Inference
64
+ def initialize(inputs:, params:, attrs:, where:)
65
+ @inputs = inputs
66
+ @params = params
67
+ @attrs = attrs
68
+ @where = where
69
+ end
70
+
71
+ # [shape, dtype] by `rule`, one of RULES.
72
+ def call(rule)
73
+ unless RULES.include?(rule)
74
+ raise ConfigError, "#{@where}: no shape rule #{rule.inspect} (ops.yml and Shape disagree)"
75
+ end
76
+
77
+ send(rule)
78
+ end
79
+
80
+ private
81
+
82
+ # Where this emission is, for what a refusal says.
83
+ attr_reader :where
84
+
85
+ # The input most rules are about.
86
+ def first = @inputs.first
87
+
88
+ def unify_dim(a, b, axis:, where: @where)
89
+ return b if a.nil?
90
+ return a if b.nil? || a == b
91
+
92
+ raise ConfigError, "#{where}: dimension #{axis} mismatch (#{a} vs #{b})"
93
+ end
94
+
95
+ def unify(a, b, where: @where)
96
+ unless a.size == b.size
97
+ raise ConfigError, "#{where}: rank mismatch (#{a.inspect} vs #{b.inspect})"
98
+ end
99
+
100
+ a.zip(b).each_with_index.map { |(x, y), i| unify_dim(x, y, where:, axis: i) }
101
+ end
102
+
103
+ def same_dtype(inputs = @inputs)
104
+ dtypes = inputs.map(&:dtype).uniq
105
+ return dtypes.first if dtypes.size == 1
106
+
107
+ raise ConfigError, "#{@where}: mixed dtypes #{dtypes.join(", ")}"
108
+ end
109
+
110
+ def axis!(axis, rank) = Shape.axis!(axis, rank, where: @where)
111
+
112
+ # --- rules ---
113
+
114
+ def parameter = [@params.fetch(0).shape, @params.fetch(0).dtype]
115
+
116
+ # Never to u32: that is a packed weight, not a number anything
117
+ # could be converted into (`IR::Dtype::CASTABLE`).
118
+ def cast
119
+ dtype = @attrs.fetch("dtype").to_sym
120
+ unless IR::Dtype::CASTABLE.include?(dtype)
121
+ raise ConfigError,
122
+ "#{where}: cannot cast to #{dtype.inspect}; a value is one of " \
123
+ "#{IR::Dtype::CASTABLE.join(", ")}, and u32 is only the packed form of a " \
124
+ "quantized weight"
125
+ end
126
+
127
+ [first.shape, dtype]
128
+ end
129
+
130
+ # `x @ dequantize(weight)ᵀ`, with the weight packed:
131
+ #
132
+ # x: [..., d_in], weight: u32 [d_out, d_in × bits / 32],
133
+ # scales, biases: x.dtype [d_out, d_in / group_size] -> [..., d_out]
134
+ #
135
+ # The three arrays carry no record of how they were made, so the
136
+ # attributes say, and the shapes have to agree with them: a packed
137
+ # width that does not unpack to `d_in`, or a group count that does
138
+ # not divide it, is a weight quantized some other way.
139
+ def quantized_matmul
140
+ x, weight, scales, biases = @inputs
141
+ group_size = @attrs.fetch("group_size")
142
+ bits = @attrs.fetch("bits")
143
+ mode = @attrs.fetch("mode")
144
+ unless GROUP_SIZES.include?(group_size)
145
+ raise ConfigError,
146
+ "#{where}: group_size must be one of #{GROUP_SIZES.join(", ")}, got #{group_size}"
147
+ end
148
+ unless BITS.include?(bits)
149
+ raise ConfigError,
150
+ "#{where}: bits must be one of #{BITS.join(", ")}, got #{bits}"
151
+ end
152
+ unless QUANTIZATION_MODES.include?(mode)
153
+ raise ConfigError,
154
+ "#{where}: quantization mode must be #{QUANTIZATION_MODES.join(", ")}, " \
155
+ "got #{mode.inspect}"
156
+ end
157
+ unless weight.dtype == :u32
158
+ raise ConfigError, "#{where}: a quantized weight is packed u32, got #{weight.dtype}"
159
+ end
160
+ if x.shape.empty? || x.shape.last.nil?
161
+ raise ConfigError, "#{where}: x needs a concrete last dimension, got #{x.shape.inspect}"
162
+ end
163
+ unless weight.shape.size == 2 && scales.shape.size == 2
164
+ raise ConfigError,
165
+ "#{where}: a quantized weight and its scales are matrices, got " \
166
+ "#{weight.shape.inspect} and #{scales.shape.inspect}"
167
+ end
168
+
169
+ d_in = x.shape.last
170
+ d_out, packed = weight.shape
171
+ unless (d_in % group_size).zero?
172
+ raise ConfigError,
173
+ "#{where}: d_in #{d_in} is not a multiple of group_size #{group_size}; " \
174
+ "the sizes that divide it are #{GROUP_SIZES.select do |g|
175
+ (d_in % g).zero?
176
+ end.inspect}"
177
+ end
178
+ unless packed * 32 == d_in * bits
179
+ raise ConfigError,
180
+ "#{where}: a packed weight for d_in #{d_in} at #{bits} bits is " \
181
+ "[#{d_out}, #{d_in * bits / 32}], got #{weight.shape.inspect}"
182
+ end
183
+ groups = [d_out, d_in / group_size]
184
+ unless scales.shape == groups
185
+ raise ConfigError,
186
+ "#{where}: scales must be #{groups.inspect}, got #{scales.shape.inspect}"
187
+ end
188
+ if biases && biases.shape != groups
189
+ raise ConfigError,
190
+ "#{where}: biases must be #{groups.inspect}, got #{biases.shape.inspect}"
191
+ end
192
+
193
+ dtype = same_dtype([x, scales, biases].compact)
194
+ [x.shape[0...-1] + [d_out], dtype]
195
+ end
196
+
197
+ def same_as_input
198
+ [first.shape, same_dtype]
199
+ end
200
+
201
+ # One dimension may be -1 and takes whatever is left over, and any
202
+ # number of leading 0s keep the dimensions the input already has.
203
+ #
204
+ # A symbolic dimension can only go into one of those two: nothing
205
+ # else can stand for "however many rows this batch has". A -1 takes
206
+ # one of them, which is enough while the batch is the only thing that
207
+ # varies. A 0 is for when it is not: splitting the last dimension
208
+ # into heads under a batch *and* a sequence that are both unknown
209
+ # needs two dimensions carried through untouched, and "keep what is
210
+ # there" is the only way to say that (docs/plan.md 15.63).
211
+ def reshape
212
+ from = first.shape
213
+ target = @attrs.fetch("shape")
214
+ if target.any? { |d| !d.is_a?(Integer) || d < -1 }
215
+ raise ConfigError,
216
+ "#{where}: a shape is positive integers, at most one -1, and leading 0s " \
217
+ "for the dimensions kept as they are, got #{target.inspect}"
218
+ end
219
+
220
+ keep = target.take_while(&:zero?).size
221
+ if target.drop(keep).include?(0)
222
+ raise ConfigError,
223
+ "#{where}: a 0 keeps the dimension the input has there, so only the " \
224
+ "leading ones can be kept (got #{target.inspect})"
225
+ end
226
+ if keep > from.size
227
+ raise ConfigError,
228
+ "#{where}: #{target.inspect} keeps #{keep} dimensions and " \
229
+ "#{from.inspect} has #{from.size}"
230
+ end
231
+
232
+ shape, dtype = rest_of_reshape(from.drop(keep), target.drop(keep), kept: keep)
233
+ [from.take(keep) + shape, dtype]
234
+ end
235
+
236
+ # What is left of a reshape once the kept dimensions are set aside:
237
+ # no 0s, so this is the whole of the old rule. The concrete part has
238
+ # to be preserved exactly, which is a check worth having rather than
239
+ # a formality.
240
+ def rest_of_reshape(from, target, kept: 0)
241
+ after = kept.zero? ? "" : " (past the #{kept} it keeps)"
242
+ inferred = target.count(-1)
243
+ if inferred > 1
244
+ raise ConfigError, "#{where}: only one dimension may be -1, got #{target.inspect}"
245
+ end
246
+
247
+ known = target.reject { |d| d == -1 }.reduce(1, :*)
248
+ if from.include?(nil)
249
+ unless inferred == 1
250
+ raise ConfigError,
251
+ "#{where}: #{from.inspect}#{after} has a symbolic dimension, so the " \
252
+ "target must name a -1 or a 0 for it to go into (got #{target.inspect})"
253
+ end
254
+ concrete = from.compact.reduce(1, :*)
255
+ unless concrete == known
256
+ raise ConfigError,
257
+ "#{where}: #{from.inspect}#{after} holds #{concrete} per symbolic step " \
258
+ "and #{target.inspect} wants #{known}"
259
+ end
260
+ return [target.map { |d| d == -1 ? nil : d }, first.dtype]
261
+ end
262
+
263
+ total = from.reduce(1, :*)
264
+ if inferred.zero?
265
+ unless total == known
266
+ raise ConfigError, "#{where}: #{from.inspect}#{after} holds #{total}, " \
267
+ "#{target.inspect} wants #{known}"
268
+ end
269
+ return [target, first.dtype]
270
+ end
271
+ unless known.positive? && (total % known).zero?
272
+ raise ConfigError, "#{where}: #{from.inspect}#{after} holds #{total}, which does " \
273
+ "not divide into #{target.inspect}"
274
+ end
275
+ [target.map { |d| d == -1 ? total / known : d }, first.dtype]
276
+ end
277
+
278
+ def broadcast
279
+ a, b = @inputs
280
+ [broadcast_shapes(a.shape, b.shape), same_dtype]
281
+ end
282
+
283
+ # NumPy-style broadcasting, right-aligned: 1 stretches, nil is symbolic
284
+ # and assumed to match, anything else must be equal.
285
+ def broadcast_shapes(a, b)
286
+ rank = [a.size, b.size].max
287
+ pad_a = ([1] * (rank - a.size)) + a
288
+ pad_b = ([1] * (rank - b.size)) + b
289
+ pad_a.zip(pad_b).each_with_index.map do |(x, y), i|
290
+ next y if x == 1
291
+ next x if y == 1
292
+
293
+ unify_dim(x, y, axis: i - rank)
294
+ end
295
+ end
296
+
297
+ def transpose
298
+ shape = first.shape
299
+ axes = @attrs.fetch("axes")
300
+ unless axes.sort == (0...shape.size).to_a
301
+ raise ConfigError,
302
+ "#{where}: axes #{axes.inspect} is not a permutation of 0...#{shape.size}"
303
+ end
304
+ [axes.map { |i| shape[i] }, first.dtype]
305
+ end
306
+
307
+ def slice
308
+ shape = first.shape.dup
309
+ axis = axis!(@attrs.fetch("axis"), shape.size)
310
+ start = @attrs.fetch("start")
311
+ length = @attrs.fetch("length")
312
+ dim = shape[axis]
313
+ unless length.positive? && start >= 0
314
+ raise ConfigError,
315
+ "#{where}: slice #{start}...#{start + length} is not a positive range"
316
+ end
317
+ # A concrete dimension bounds the range and is checked here. A
318
+ # symbolic one has no length to check against, and the engine checks
319
+ # it when the batch arrives; what a symbolic axis cannot change is
320
+ # the length the slice produces. This is what lets a classifier pool
321
+ # the first token of a sequence whose length the batch decides
322
+ # (`classifier(seq: nil)`).
323
+ if dim && start + length > dim
324
+ raise ConfigError,
325
+ "#{where}: slice #{start}...#{start + length} is out of 0...#{dim} on axis #{axis}"
326
+ end
327
+ shape[axis] = length
328
+ [shape, first.dtype]
329
+ end
330
+
331
+ def reduce
332
+ shape = first.shape
333
+ keepdims = @attrs.fetch("keepdims")
334
+ axes = @attrs.fetch("axes")&.map { |a| axis!(a, shape.size) } || (0...shape.size).to_a
335
+ if axes.uniq.size != axes.size
336
+ raise ConfigError, "#{where}: duplicate reduction axes #{@attrs["axes"].inspect}"
337
+ end
338
+
339
+ # flat_map rather than filter_map: a dimension that is kept can
340
+ # itself be nil (the batch is symbolic), and dropping those was how
341
+ # a reduction over [nil, seq, hidden] came back as [hidden].
342
+ out = shape.each_with_index.flat_map do |dim, i|
343
+ next [dim] unless axes.include?(i)
344
+
345
+ keepdims ? [1] : []
346
+ end
347
+ [out, first.dtype]
348
+ end
349
+
350
+ def matmul
351
+ a, b = @inputs.map(&:shape)
352
+ if a.size < 2 || b.size < 2
353
+ raise ConfigError, "#{where}: matmul needs rank >= 2 (#{a.inspect} @ #{b.inspect})"
354
+ end
355
+
356
+ unify_dim(a[-1], b[-2], axis: -1)
357
+ batch =
358
+ if b.size == 2
359
+ a[0...-2]
360
+ else
361
+ unify(a[0...-2], b[0...-2], where: "#{where} (batch dims)")
362
+ end
363
+ [batch + [a[-2], b[-1]], same_dtype]
364
+ end
365
+
366
+ def take
367
+ table, indices = @inputs
368
+ unless indices.dtype == :i32
369
+ raise ConfigError, "#{where}: take indices must be i32, got #{indices.dtype}"
370
+ end
371
+ if table.shape.size < 2
372
+ raise ConfigError, "#{where}: take table needs rank >= 2, got #{table.shape.inspect}"
373
+ end
374
+
375
+ [indices.shape + table.shape[1..], table.dtype]
376
+ end
377
+
378
+ # Attention over [batch, heads, positions, head_dim].
379
+ #
380
+ # The head counts need not agree. Grouped-query attention gives
381
+ # several query heads one key head, and the backend takes k and v
382
+ # untiled, so what is required of them is that they divide rather than
383
+ # match. Everything else does have to: one batch, keys and values in
384
+ # step with each other, and a query as wide as a key.
385
+ def sdpa
386
+ given = @inputs.first(3).map(&:shape)
387
+ rank = given.first.size
388
+ unless [3, 4].include?(rank) && given.all? { |shape| shape.size == rank }
389
+ raise ConfigError,
390
+ "#{where}: attention takes [batch, heads, positions, head_dim], or " \
391
+ "the same without the heads; q is #{given[0].inspect}, k is " \
392
+ "#{given[1].inspect}, v is #{given[2].inspect}"
393
+ end
394
+
395
+ # One head, written without saying so, is still one head.
396
+ q, k, v = given.map { |shape| rank == 3 ? [shape[0], 1, shape[1], shape[2]] : shape }
397
+ batch = unify_dim(q[0], unify_dim(k[0], v[0], axis: 0), axis: 0)
398
+ unify_dim(k[1], v[1], where: "#{where} (k vs v heads)", axis: 1)
399
+ unify_dim(k[2], v[2], where: "#{where} (k vs v positions)", axis: 2)
400
+ unify_dim(q[3], k[3], where: "#{where} (q vs k head_dim)", axis: 3)
401
+ grouped!(q[1], k[1])
402
+ out = rank == 3 ? [batch, q[2], v[3]] : [batch, q[1], q[2], v[3]]
403
+ [out, same_dtype(@inputs.first(3))]
404
+ end
405
+
406
+ # Each key head serves the same number of query heads, so the one
407
+ # count divides the other. Unknown either way is left alone, as
408
+ # everywhere else a dimension is symbolic.
409
+ def grouped!(heads, kv_heads)
410
+ return if heads.nil? || kv_heads.nil?
411
+ return if kv_heads.positive? && (heads % kv_heads).zero?
412
+
413
+ raise ConfigError,
414
+ "#{where}: #{heads} query heads do not divide into #{kv_heads} key heads"
415
+ end
416
+
417
+ # Logits and the class each position wants, to the loss at each
418
+ # position: [..., classes] and [...] to [...].
419
+ #
420
+ # The class axis is the last one and disappears; what is left is the
421
+ # positions, which is what the two sides have to agree about.
422
+ def cross_entropy
423
+ logits, targets = @inputs
424
+ unless targets.dtype == :i32
425
+ raise ConfigError,
426
+ "#{where}: targets are class indices, so i32, got #{targets.dtype}"
427
+ end
428
+ if logits.shape.size < 2
429
+ raise ConfigError,
430
+ "#{where}: logits need a class axis after the positions, " \
431
+ "got #{logits.shape.inspect}"
432
+ end
433
+
434
+ [unify(logits.shape[0..-2], targets.shape), logits.dtype]
435
+ end
436
+ end
437
+ end
438
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Host-side data: bytes, a shape and a dtype. What crosses the boundary.
5
+ #
6
+ # It holds no operations, and that is deliberate (the same rule burn-rb's
7
+ # TensorData follows). Reshaping, concatenating and slicing happen on the
8
+ # device, where the graph says them; here there is only the value.
9
+ #
10
+ # Its reason for existing is the cost of *building* one. A batch used to
11
+ # be written as a flat Ruby Array of Floats and packed on the way in,
12
+ # which is fine for a spike and ruinous for a mask: an attention mask at
13
+ # sequence 512 and batch 32 is 16.8 million Floats, built to be thrown
14
+ # away a moment later. Most large tensors are not arbitrary numbers, they
15
+ # are runs of the same one, and `runs` writes those without an Array at
16
+ # all.
17
+ #
18
+ # Reading is the other direction and stays as it was: what comes back out
19
+ # is numbers, because numbers are what a caller wants to look at.
20
+ class TensorData
21
+ # dtype => [pack directive, bytes per value].
22
+ FORMATS = { f32: ["f", 4], i32: ["l<", 4] }.freeze
23
+
24
+ attr_reader :dtype, :shape, :bytes
25
+
26
+ # Already-packed bytes, native-endian. The form the boundary carries,
27
+ # so this is the constructor the others end at. `where` names the
28
+ # tensor in a refusal, when the caller knows it by a name.
29
+ def initialize(shape, bytes, dtype: :f32, where: nil)
30
+ TensorData.format(dtype)
31
+ @dtype = dtype.to_sym
32
+ @shape = shape.map { Integer(_1) }.freeze
33
+ @bytes = bytes.b.freeze
34
+ expected = size * value_size
35
+ unless @bytes.bytesize == expected
36
+ raise ArgumentError,
37
+ "#{"#{where}: " if where}#{@shape.inspect} of #{@dtype} wants #{expected} " \
38
+ "bytes, got #{@bytes.bytesize}"
39
+ end
40
+ freeze
41
+ end
42
+
43
+ class << self
44
+ # The [pack directive, bytes per value] a dtype crosses as, or an
45
+ # ArgumentError naming the ones that can.
46
+ def format(dtype)
47
+ FORMATS.fetch(dtype.to_sym) do
48
+ raise ArgumentError,
49
+ "dtype #{dtype.inspect} does not cross the boundary (#{FORMATS.keys.join(", ")})"
50
+ end
51
+ end
52
+
53
+ # Whatever a caller wrote a tensor as: a TensorData, or the
54
+ # {shape:, data:, dtype:} Hash whose data is a flat Array of numbers
55
+ # or an already-packed String. `where` names it in a refusal.
56
+ def from(value, where: "a tensor")
57
+ return value if value.is_a?(TensorData)
58
+
59
+ unless value.is_a?(Hash)
60
+ raise ArgumentError, "#{where} is a #{value.class}; a tensor is a TensorData " \
61
+ "or {shape:, data:, dtype:}"
62
+ end
63
+ field = ->(key) { value.fetch(key) { value.fetch(key.to_s) } }
64
+ dtype = value[:dtype] || value["dtype"] || :f32
65
+ unless FORMATS.key?(dtype.to_sym)
66
+ raise ArgumentError, "#{where}: dtype #{dtype.inspect} does not cross the boundary " \
67
+ "(#{FORMATS.keys.join(", ")})"
68
+ end
69
+ data = field.call(:data)
70
+ shape = field.call(:shape)
71
+ bytes = data.is_a?(String) ? data : data.pack("#{format(dtype).first}*")
72
+ new(shape, bytes, dtype:, where:)
73
+ end
74
+
75
+ # What the engine answers with: the dtype and shape readable, the
76
+ # payload packed.
77
+ def from_native(dtype, shape, bytes) = new(shape, bytes, dtype: dtype.to_sym)
78
+
79
+ # From a flat Array of numbers. The plain way, and the expensive one:
80
+ # every element exists in Ruby before any of it is packed.
81
+ def from_a(shape, data, dtype: :f32)
82
+ directive, = format(dtype)
83
+ new(shape, data.pack("#{directive}*"), dtype:)
84
+ end
85
+
86
+ # From a nested Array, taking the shape from the nesting.
87
+ #
88
+ # TensorData.nested([[1.0, 2.0], [3.0, 4.0]]) # shape [2, 2]
89
+ def nested(array, dtype: :f32)
90
+ shape = []
91
+ node = array
92
+ while node.is_a?(Array)
93
+ shape << node.size
94
+ node = node.first
95
+ end
96
+ from_a(shape, array.flatten, dtype:)
97
+ end
98
+
99
+ # One value, everywhere. No Array is built.
100
+ def filled(shape, value, dtype: :f32)
101
+ count = shape.inject(1, :*)
102
+ new(shape, one(value, dtype) * count, dtype:)
103
+ end
104
+
105
+ # Runs of equal values, in order, covering the whole tensor.
106
+ #
107
+ # What a mask is: a row of a padding mask is "this many open, then
108
+ # this many shut", and a sliding window row is three runs. Written as
109
+ # String multiplication, so a 512x512 window costs three string
110
+ # operations per row instead of 262,144 Floats.
111
+ #
112
+ # TensorData.runs([2, 3], [[3, 0.0], [3, -1e9]])
113
+ def runs(shape, runs, dtype: :f32)
114
+ count = shape.inject(1, :*)
115
+ given = runs.sum { |n, _| n }
116
+ unless given == count
117
+ raise ArgumentError, "#{shape.inspect} holds #{count} values, the runs give #{given}"
118
+ end
119
+
120
+ packed = +""
121
+ runs.each { |n, value| packed << (one(value, dtype) * n) if n.positive? }
122
+ new(shape, packed, dtype:)
123
+ end
124
+
125
+ private
126
+
127
+ # One value as its bytes.
128
+ def one(value, dtype)
129
+ directive, = format(dtype)
130
+ [value].pack(directive)
131
+ end
132
+ end
133
+
134
+ # The {shape:, data:} pair the JSON paths speak (inline weights, and
135
+ # `put` before it packs). Spells every number out, so it is a request,
136
+ # not something the boundary does on its own.
137
+ def to_h = { shape:, data: to_a }
138
+
139
+ def rank = shape.size
140
+
141
+ # How many values, not how many bytes.
142
+ def size = shape.inject(1, :*)
143
+
144
+ def bytesize = bytes.bytesize
145
+
146
+ # How many bytes one value takes.
147
+ def value_size = FORMATS.fetch(dtype).last
148
+
149
+ # What the engine is handed: the dtype and shape readable, the payload
150
+ # packed.
151
+ def to_native = [dtype.to_s, shape, bytes]
152
+
153
+ # The numbers, when a caller wants to look at them. Builds the Array
154
+ # this class exists to avoid, so it is a question rather than a habit.
155
+ def to_a
156
+ directive, = FORMATS.fetch(dtype)
157
+ bytes.unpack("#{directive}*")
158
+ end
159
+
160
+ # As a value: same shape, same dtype, same bytes.
161
+ #
162
+ # Ruby's == answers false for what it cannot compare rather than
163
+ # raising, so `[t].include?(3)` and `t == nil` behave.
164
+ def ==(other)
165
+ other.is_a?(TensorData) && other.dtype == dtype &&
166
+ other.shape == shape && other.bytes == bytes
167
+ end
168
+ alias eql? ==
169
+
170
+ # Equal values must hash equally, and unequal ones may. Shape and dtype
171
+ # sort them well enough; reading the whole buffer to key a Hash would
172
+ # be paying for what eql? settles.
173
+ def hash = [self.class, shape, dtype].hash
174
+
175
+ def inspect = "#<Torobi::TensorData #{dtype}#{shape.inspect} #{bytesize} bytes>"
176
+ alias to_s inspect
177
+ end
178
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ VERSION = "0.1.0"
5
+ end