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,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # What must hold before the engine is asked to do anything.
5
+ #
6
+ # Not defensive programming for its own sake: some MLX failures do not
7
+ # come back as errors. A machine with no working Metal device raises a
8
+ # C++ exception during device initialization, which Rust cannot catch;
9
+ # the process exits with nothing for Ruby to rescue.
10
+ #
11
+ # This file holds the checks only Ruby can make. The missing-metallib
12
+ # refusal moved into the engine's runtime, where it also covers callers
13
+ # that never pass through here (`Torobi::Native` used directly, the
14
+ # engine's own CLI and tests). What stays is the probe: an external
15
+ # review reached a machine where the metallib was present and
16
+ # initialization still aborted, and the only honest way to ask "will the
17
+ # device start" is in a subprocess, where an abort is an exit status
18
+ # rather than the end of this process (docs/plan.md section 4.1).
19
+ module Preflight
20
+ # Where MLX will look for its Metal kernels: beside the library holding
21
+ # the MLX symbols, found through dladdr. The engine refuses when the
22
+ # file is not there; this constant remains for the tests that hide it.
23
+ METALLIB = File.expand_path("mlx.metallib", __dir__)
24
+
25
+ # The Linux counterpart: the NVIDIA headers MLX's CUDA backend compiles
26
+ # its kernels against at run time, one directory above the extension
27
+ # (its parent's `include/`). Same purpose as METALLIB, and the same
28
+ # reason for a constant - the tests that hide it.
29
+ JIT_HEADERS = File.expand_path("../include/cccl", __dir__)
30
+
31
+ # The process that loaded the extension. A Metal device and its command
32
+ # queues do not survive fork, so a child that inherited them cannot use
33
+ # them, and finding out at the GPU is finding out by aborting.
34
+ ORIGIN_PID = Process.pid
35
+
36
+ # Refuses, before MLX is touched, what would otherwise fail at the GPU
37
+ # or end the process: a forked child, and a device that cannot start.
38
+ def self.check!
39
+ unless Process.pid == ORIGIN_PID
40
+ raise Torobi::EngineUnavailable,
41
+ "this process (#{Process.pid}) inherited Torobi from a fork of " \
42
+ "#{ORIGIN_PID}. A Metal device does not survive fork, so a session " \
43
+ "here would fail at the GPU rather than here. Run training in a " \
44
+ "process started with Process.spawn or exec, not in a prefork " \
45
+ "worker (Puma clustered, Sidekiq, Spring)."
46
+ end
47
+
48
+ # The kernels a platform gem did not ship, fetched and named before
49
+ # the probe below: without them MLX ends the process rather than
50
+ # raising, so this has to happen where the answer is still ours to
51
+ # give. Touches no device, so it is after the pid check, not before
52
+ # it.
53
+ Metallib.ensure! if MlxPrebuilt.metal?
54
+
55
+ probe = Probe.current
56
+ return if probe.ok?
57
+
58
+ raise Torobi::EngineUnavailable, "MLX cannot start on this machine: #{probe.reason}"
59
+ end
60
+
61
+ # Whether MLX could initialize, as one process found out: its pid, and
62
+ # nil or the reason it could not.
63
+ #
64
+ # Asked in a subprocess, because the failure it looks for is an abort:
65
+ # asking in this process is the thing we are trying to avoid. The answer
66
+ # is kept against the pid that learned it (`current`), so a forked
67
+ # child does not inherit its parent's answer: it would be answering
68
+ # about the parent's device, not its own.
69
+ class Probe < Data.define(:pid, :reason)
70
+ # Enough to make MLX build a device and run a kernel.
71
+ SCRIPT = <<~RUBY.freeze
72
+ $LOAD_PATH.unshift(#{File.expand_path("..", __dir__).inspect})
73
+ require "torobi"
74
+ # The parent named the kernels; this process has not. Without it
75
+ # the probe would look beside its own bundle and, on a platform gem,
76
+ # find nothing.
77
+ Torobi::Metallib.ensure! if MlxPrebuilt.metal?
78
+ model = Torobi.graph do |g|
79
+ x = g.input :x, [nil, 1]
80
+ g.output :loss, g.mean(g.linear(x, 1, name: "probe"))
81
+ end
82
+ config = Torobi::GraphConfig.new(models: { "m" => model })
83
+ weights = { params: { "m.probe.weight" => { shape: [1, 1], data: [0.0] },
84
+ "m.probe.bias" => { shape: [1], data: [0.0] } } }
85
+ # The engine directly, and nothing of the session around it: what
86
+ # this asks is whether the device starts, and a failure anywhere
87
+ # else would be reported as that.
88
+ native = Torobi::Native::Session.open(
89
+ config.canonical_json, JSON.generate(weights),
90
+ JSON.generate(Torobi::Session::DEFAULT_OPTIMIZER),
91
+ Torobi::Session::DEFAULT_SEED
92
+ )
93
+ native.run_step({ "x" => ["f32", [1, 1], [1.0].pack("f*")] })
94
+ print "ok"
95
+ RUBY
96
+
97
+ # This process's answer, asked for the first time if it has not been.
98
+ def self.current
99
+ @current = run unless @current&.pid == Process.pid
100
+ @current
101
+ end
102
+
103
+ # Forgets the answer, for tests that need the probe run again.
104
+ def self.forget! = @current = nil
105
+
106
+ # Asks, in a subprocess, now.
107
+ def self.run
108
+ require "open3"
109
+ output, status = Open3.capture2e(RbConfig.ruby, "-e", SCRIPT)
110
+ ok = status.success? && output.end_with?("ok")
111
+ new(pid: Process.pid, reason: ok ? nil : reason_from(output))
112
+ rescue StandardError => e
113
+ new(pid: Process.pid, reason: e.message)
114
+ end
115
+
116
+ # The child's own words, when it had any. An engine refusal arrives as
117
+ # an exception message; an abort leaves whatever MLX printed on the way
118
+ # down; a silent death leaves nothing, and then the generic truth is
119
+ # all there is to say.
120
+ def self.reason_from(output)
121
+ line = output.lines.map(&:strip).reject(&:empty?).first
122
+ unless line
123
+ return "initializing its device ended a probe process rather than raising. " \
124
+ "Torobi needs a working GPU for the backend it was built against: " \
125
+ "Metal on Apple silicon, or an NVIDIA card and its driver " \
126
+ "elsewhere; see docs/vendoring.md."
127
+ end
128
+
129
+ # An unrescued Ruby exception prints as "-e:12:in '<main>': message".
130
+ line.sub(/\A.*?:\d+:in '.*?': /, "")
131
+ end
132
+
133
+ def ok? = reason.nil?
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "digest"
5
+
6
+ module Torobi
7
+ # Everything about a run that is not an event: what was trained, with
8
+ # what, on what, and by which build. Gathered once, at the top of a
9
+ # journal and in every checkpoint (docs/plan.md sections 8.5 and 11.2).
10
+ #
11
+ # config what the GraphConfig was: its digest, versions, models,
12
+ # what is trained, and every parameter by qualified path
13
+ # dataset whatever the caller said about the data, verbatim
14
+ # runtime the build: torobi, Ruby, the platform, and the engine's
15
+ # own report when the extension is there
16
+ # optimizer the update rule the run was opened with
17
+ # seed where its randomness starts
18
+ Provenance = Data.define(:config, :dataset, :runtime, :optimizer, :seed) do
19
+ def self.of(config, dataset: nil, optimizer: nil, seed: nil)
20
+ new(config: {
21
+ "digest" => config.digest,
22
+ "schema_version" => config.schema_version,
23
+ "semantics_version" => config.semantics_version,
24
+ "models" => config.models.keys,
25
+ "train" => config.train,
26
+ "parameters" => config.parameters.map(&:qualified_path)
27
+ },
28
+ dataset:, runtime: runtime, optimizer:, seed:)
29
+ end
30
+
31
+ # The build this ran on. The engine's half is asked for only when the
32
+ # extension is there, so a pure-Ruby run still has a provenance.
33
+ def self.runtime
34
+ info = { "torobi" => Torobi::VERSION, "ruby" => RUBY_VERSION, "platform" => RUBY_PLATFORM }
35
+ if Torobi.const_defined?(:Native) && Torobi::Native.respond_to?(:build_info)
36
+ info["engine"] = Torobi::Native.build_info
37
+ end
38
+ info
39
+ end
40
+
41
+ # A digest of data, so that a record names what it was fed without
42
+ # holding it.
43
+ #
44
+ # Framed: each part contributes its length before its bytes, so that
45
+ # ("ab", "c") and ("a", "bc") do not agree, which plain concatenation
46
+ # let them do. Hashes are serialized with their keys sorted, so a
47
+ # digest depends on the data and not on the order it was written in.
48
+ def self.digest_of(*parts)
49
+ digest = Digest::SHA256.new
50
+ digest << "torobi/1\n"
51
+ parts.each do |part|
52
+ bytes = part.is_a?(String) ? part : JSON.generate(IR::Json.canonical(part))
53
+ digest << "#{bytes.bytesize}:"
54
+ digest << bytes
55
+ end
56
+ digest.hexdigest
57
+ end
58
+
59
+ def self.from_h(h)
60
+ new(config: h.fetch("config"), dataset: h["dataset"], runtime: h.fetch("runtime"),
61
+ optimizer: h["optimizer"], seed: h["seed"])
62
+ end
63
+
64
+ def initialize(config:, runtime:, dataset: nil, optimizer: nil, seed: nil)
65
+ optimizer = optimizer&.to_h { |k, v| [k.to_s, v.is_a?(Symbol) ? v.to_s : v] }
66
+ super(config: Freeze.deep(config), dataset: Freeze.deep(dataset),
67
+ runtime: Freeze.deep(runtime), optimizer: Freeze.deep(optimizer), seed:)
68
+ end
69
+
70
+ def to_h
71
+ { "config" => config, "dataset" => dataset, "runtime" => runtime,
72
+ "optimizer" => optimizer, "seed" => seed }.compact
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Torobi
6
+ # A base model held in a few bits per weight, as something a graph is
7
+ # built with (docs/qlora.md).
8
+ #
9
+ # `Torobi::LoRA` leaves the base where it is and trains a pair of small
10
+ # matrices beside each linear. The base still has to be in memory, and
11
+ # in bf16 a 32B model is 61 GiB, which is on no machine this is for.
12
+ # QLoRA (Dettmers et al., 2023) holds the base quantized instead: each
13
+ # weight becomes a 4-bit integer, and every group of 64 of them shares
14
+ # one scale and one bias, which is 4.5 bits a weight. The forward reads
15
+ # it packed (`quantized_matmul`); the backward reaches the adapter and
16
+ # the activations, never the base, so the base is frozen by nature
17
+ # rather than by choice.
18
+ #
19
+ # What this holds is the decision, not the arithmetic:
20
+ #
21
+ # quant = Torobi::Quantization.new(bits: 4, group_size: 64)
22
+ # adapter = Torobi::LoRA.new(rank: 8, alpha: 16, on: %w[q_proj v_proj])
23
+ # model = Torobi::Models::Llama.causal_lm(config, seq: 512, adapter:, quantization: quant)
24
+ #
25
+ # A quantized linear is **three parameters**, named as mlx-lm's
26
+ # checkpoints name them (`{name}.weight` packed u32, `{name}.scales`,
27
+ # `{name}.biases`), so a published `*-4bit` file imports with no
28
+ # renaming and a checkpoint of a quantized run is an ordinary
29
+ # checkpoint. A bf16 checkpoint opens as the same model: a weight the
30
+ # file holds as numbers is quantized as it is read, to what the graph
31
+ # declares. Only linears are quantized here. An embedding is a `take`
32
+ # rather than a matmul, and a quantized one is a different operation;
33
+ # a file that holds one quantized is dequantized when it is read.
34
+ Quantization = Data.define(:bits, :group_size, :mode, :on) do
35
+ # `on:` names the linears to quantize by their last segment, as a
36
+ # `LoRA`'s `on:` does, or `:linears` for all of them, which is what a
37
+ # published 4-bit checkpoint holds and the default.
38
+ def initialize(bits: 4, group_size: 64, mode: "affine", on: :linears)
39
+ bits = Integer(bits)
40
+ group_size = Integer(group_size)
41
+ mode = mode.to_s
42
+ unless Shape::BITS.include?(bits)
43
+ raise ConfigError, "bits must be one of #{Shape::BITS.join(", ")}, got #{bits}"
44
+ end
45
+ unless Shape::GROUP_SIZES.include?(group_size)
46
+ raise ConfigError,
47
+ "group_size must be one of #{Shape::GROUP_SIZES.join(", ")}, got #{group_size}"
48
+ end
49
+ unless Shape::QUANTIZATION_MODES.include?(mode)
50
+ raise ConfigError,
51
+ "quantization mode must be #{Shape::QUANTIZATION_MODES.join(", ")}, " \
52
+ "got #{mode.inspect}"
53
+ end
54
+
55
+ on = on == :linears ? :linears : Array(on).map(&:to_s).freeze
56
+ raise ConfigError, "a quantization quantizes something: on: names which linears" if on == []
57
+
58
+ super
59
+ end
60
+
61
+ # What a checkpoint's `config.json` says, as mlx-lm writes it:
62
+ #
63
+ # "quantization": {"group_size": 64, "bits": 4}
64
+ #
65
+ # `nil` when the config says nothing, which is a bf16 checkpoint.
66
+ # `on:` is left at every linear; `from_header` reads which ones the
67
+ # file actually holds quantized.
68
+ def self.from_config(raw, on: :linears)
69
+ given = raw["quantization"] || raw["quantization_config"]
70
+ return nil unless given
71
+
72
+ new(bits: given.fetch("bits"), group_size: given.fetch("group_size"),
73
+ mode: given.fetch("mode", "affine"), on:)
74
+ end
75
+
76
+ # The same, with `on:` read from a safetensors header: the modules
77
+ # that hold a `.scales` are the ones that are quantized. A published
78
+ # file may leave some linears out, and the file is the only thing
79
+ # that says which.
80
+ def self.from_header(raw, header)
81
+ quantized = header.keys.filter_map do |name|
82
+ name.delete_suffix(".scales") if name.end_with?(".scales")
83
+ end
84
+ from_config(raw, on: quantized.map { |path| path.split(".").last }.uniq.sort)
85
+ end
86
+
87
+ # Both of the above from a checkpoint directory: its `config.json`
88
+ # and the header at the front of its `model.safetensors`.
89
+ def self.from_directory(dir)
90
+ raw = JSON.parse(File.read(File.join(dir, "config.json")))
91
+ header = File.open(File.join(dir, "model.safetensors"), "rb") do |f|
92
+ JSON.parse(f.read(f.read(8).unpack1("Q<")))
93
+ end
94
+ from_header(raw, header)
95
+ end
96
+
97
+ # Whether the linear at `path` is held quantized. Matched on the last
98
+ # segment, as a `LoRA` matches.
99
+ def wraps?(path)
100
+ return true if on == :linears
101
+
102
+ path = path.to_s
103
+ on.any? { |target| path == target || path.end_with?(".#{target}") }
104
+ end
105
+
106
+ # How many values one u32 of the packed weight holds.
107
+ def values_per_word = 32 / bits
108
+
109
+ # The shapes a `[d_out, d_in]` weight becomes.
110
+ def packed_shape(d_out, d_in) = [d_out, d_in * bits / 32]
111
+ def group_shape(d_out, d_in) = [d_out, d_in / group_size]
112
+
113
+ # What a quantized linear adds to the graph, in place of its weight:
114
+ # the three parameters, frozen, and the matmul that reads them
115
+ # packed. Built through the graph's public vocabulary, with the names
116
+ # a checkpoint uses.
117
+ #
118
+ # Frozen by declaration (`trainable: false`), which no adapter can
119
+ # undo: a packed weight has no gradient, and the scales and biases
120
+ # are the base model's, not something a fine-tune moves.
121
+ def apply(g, x, d_in:, d_out:, name:)
122
+ where = "linear #{name.inspect}"
123
+ unless (d_in % group_size).zero?
124
+ fits = Shape::GROUP_SIZES.select { |size| (d_in % size).zero? }
125
+ raise ConfigError,
126
+ "#{where}: d_in #{d_in} is not a multiple of group_size #{group_size}" \
127
+ "#{fits.empty? ? ", and no group size divides it" : "; #{fits.join(" or ")} would"}"
128
+ end
129
+ unless ((d_in * bits) % 32).zero?
130
+ raise ConfigError, "#{where}: d_in #{d_in} at #{bits} bits does not pack into whole words"
131
+ end
132
+
133
+ frozen = { "type" => "zeros" }
134
+ weight = g.param("#{name}.weight", packed_shape(d_out, d_in), dtype: :u32,
135
+ init: frozen, trainable: false)
136
+ scales = g.param("#{name}.scales", group_shape(d_out, d_in), dtype: x.dtype,
137
+ init: frozen, trainable: false)
138
+ biases = g.param("#{name}.biases", group_shape(d_out, d_in), dtype: x.dtype,
139
+ init: frozen, trainable: false)
140
+ g.emit("quantized_matmul", inputs: [x, weight, scales, biases],
141
+ attrs: { group_size:, bits:, mode: })
142
+ end
143
+
144
+ # Whether a parameter path is one of a quantized weight's own: the
145
+ # packed weight cannot be told from a plain one by its name, so this
146
+ # names the two that only a quantized linear has.
147
+ def self.quantized?(path)
148
+ %w[scales biases].any? { |suffix| path.to_s.end_with?(".#{suffix}") }
149
+ end
150
+ end
151
+ end
@@ -0,0 +1,229 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Running a journal again.
5
+ #
6
+ # "Replay" was one word for two things (docs/plan.md section 8.6), and
7
+ # they answer different questions:
8
+ #
9
+ # action replay applies what was recorded, without the policy
10
+ # that decided it. Asks: does this training
11
+ # reproduce? Used for CI and for making a run
12
+ # again from its record.
13
+ #
14
+ # deterministic rerun runs the policy again, against the same data,
15
+ # and holds it to what it observed the first
16
+ # time. Asks: does this policy still decide what
17
+ # it decided? Used to catch a regression in the
18
+ # Ruby that drove the run.
19
+ #
20
+ # Neither replays the data: a journal names batches by digest rather
21
+ # than holding them, so the caller supplies them. Action replay holds
22
+ # each one to the digest that was recorded (`Batch#digest`); a rerun
23
+ # holds the run to the observations instead, and the losses those
24
+ # observations came from move if the data did. Both open the session
25
+ # the way the run was opened, with the optimizer and seed its
26
+ # provenance recorded.
27
+ module Replay
28
+ # One place the replay and the record disagree.
29
+ Divergence = Data.define(:step, :expected, :actual, :why)
30
+
31
+ # What a replay found. `agrees?` answers the question the mode asked.
32
+ Result = Data.define(:mode, :steps, :final_loss, :divergences) do
33
+ def agrees? = divergences.empty?
34
+
35
+ def to_s
36
+ return "#{mode}: agrees after #{steps} steps" if agrees?
37
+
38
+ "#{mode}: #{divergences.size} divergence(s), first at step #{divergences.first.step}"
39
+ end
40
+ end
41
+
42
+ # `Replay::Action.new(...).call(batches)`, said shorter.
43
+ def self.action(journal, config:, weights:, batches:, tolerance: :bitwise)
44
+ Action.new(journal, config:, weights:, tolerance:).call(batches)
45
+ end
46
+
47
+ # `Replay::Rerun.new(...).call(batches, &program)`, said shorter.
48
+ def self.rerun(journal, config:, weights:, batches:, tolerance: 1e-6, &program)
49
+ Rerun.new(journal, config:, weights:, tolerance:).call(batches, &program)
50
+ end
51
+
52
+ # What both modes share: the record, how to open a session the way the
53
+ # run was opened, and what counts as agreeing.
54
+ class Mode
55
+ # `journal` is a Journal, its JSONL, or what `Journal.read` returned.
56
+ #
57
+ # `tolerance` is the agreement asked for: nil for none (only the
58
+ # operations are replayed), a number for the dtype-scale agreement of
59
+ # docs/plan.md section 8.6, and :bitwise for exact equality, which the
60
+ # same machine and build should give.
61
+ def initialize(journal, config:, weights:, tolerance:)
62
+ @record = record_of(journal)
63
+ @config = config
64
+ @weights = weights
65
+ @tolerance = tolerance
66
+ @divergences = []
67
+ end
68
+
69
+ private
70
+
71
+ def open_session(observer: nil, &)
72
+ provenance = @record.header.provenance
73
+ optimizer = provenance.optimizer&.transform_keys(&:to_sym) || Session::DEFAULT_OPTIMIZER
74
+ Session.open(@config, weights: @weights, optimizer:,
75
+ seed: provenance.seed || Session::DEFAULT_SEED, observer:, &)
76
+ end
77
+
78
+ def agrees?(a, b)
79
+ return true if @tolerance.nil?
80
+ return a == b unless a.is_a?(Numeric) && b.is_a?(Numeric)
81
+ return a == b if @tolerance == :bitwise
82
+
83
+ (a - b).abs <= @tolerance
84
+ end
85
+
86
+ def diverged(step:, expected:, actual:, why:)
87
+ @divergences << Divergence.new(step:, expected:, actual:, why:)
88
+ end
89
+
90
+ def record_of(journal)
91
+ case journal
92
+ when Journal then journal.to_record
93
+ when String then Journal.read(journal)
94
+ when Journal::Record then journal
95
+ else
96
+ raise ArgumentError, "a journal is a Journal, its JSONL, or what Journal.read returned"
97
+ end
98
+ end
99
+ end
100
+
101
+ # Applies a journal's operations to a fresh session, in order, without
102
+ # running any policy. `batches` supplies the data the journal names,
103
+ # one per step taken or part accumulated.
104
+ class Action < Mode
105
+ def call(batches)
106
+ @data = batches.to_a
107
+ @fed = 0
108
+ steps = @record.of(Journal::Span).size
109
+ final = open_session do |session|
110
+ @record.entries.each { |entry| apply(session, entry) }
111
+ session.loss
112
+ end
113
+ Result.new(mode: :action, steps:, final_loss: final, divergences: @divergences.dup)
114
+ end
115
+
116
+ private
117
+
118
+ def apply(session, entry)
119
+ case entry
120
+ when Journal::Adjust
121
+ session.adjust(**entry.knobs.transform_keys(&:to_sym))
122
+ when Journal::Freezing
123
+ entry.frozen ? session.freeze!(entry.pattern) : session.unfreeze!(entry.pattern)
124
+ when Journal::Accumulate
125
+ session.accumulate(checked(entry, next_batch))
126
+ when Journal::Span
127
+ if entry.accumulated?
128
+ compare(entry, session.apply!)
129
+ else
130
+ compare(entry, session.step!(checked(entry, next_batch)))
131
+ end
132
+ end
133
+ # A put's value is not in the journal, only its digest; observations
134
+ # and notes change nothing.
135
+ end
136
+
137
+ # The batch to feed, after holding it to the digest the journal
138
+ # recorded. It is fed either way: a mismatch is reported and the
139
+ # replay goes on, so the losses can be compared too.
140
+ def checked(entry, batch)
141
+ batch = Batch.of(batch)
142
+ recorded = entry.batches_digest
143
+ return batch if recorded.nil?
144
+
145
+ actual = batch.digest
146
+ return batch if actual == recorded
147
+
148
+ diverged(step: entry.step, expected: recorded, actual:,
149
+ why: "the batch differs from the one that was recorded")
150
+ batch
151
+ end
152
+
153
+ def compare(entry, loss)
154
+ return if agrees?(entry.loss, loss)
155
+
156
+ diverged(step: entry.step, expected: entry.loss, actual: loss,
157
+ why: "the loss differs by #{(entry.loss - loss).abs}")
158
+ end
159
+
160
+ # The batch the next step or part was fed.
161
+ def next_batch
162
+ batch = @data.fetch(@fed) do
163
+ raise ArgumentError,
164
+ "the journal was fed #{fed_in_all} batches and only #{@data.size} " \
165
+ "batches were given"
166
+ end
167
+ @fed += 1
168
+ batch
169
+ end
170
+
171
+ # One per step taken on a batch, and one per part accumulated.
172
+ def fed_in_all
173
+ @record.of(Journal::Span).count { |span| !span.accumulated? } +
174
+ @record.of(Journal::Accumulate).size
175
+ end
176
+ end
177
+
178
+ # Runs `program` again over the same data and holds it to what the
179
+ # journal observed: every `observe` the first run recorded must be
180
+ # observed again, with the same values.
181
+ #
182
+ # This is the mode for a policy: the program is the Ruby that drove the
183
+ # run, and what is compared is its inputs and its decisions, not only
184
+ # where the training ended up. It collects observations through the
185
+ # session's observer, so a `Torobi::Policies` object firing in the
186
+ # window is held to what it decided just as the driving program is
187
+ # (`Session.open`).
188
+ class Rerun < Mode
189
+ def call(batches, &program)
190
+ raise ArgumentError, "rerun needs the program that drove the run" unless program
191
+
192
+ seen = []
193
+ collect = ->(step:, values:) { seen << Journal::Observe.new(step:, values:) }
194
+ final = open_session(observer: collect) do |session|
195
+ program.call(session, batches)
196
+ session.loss
197
+ end
198
+ expected = @record.of(Journal::Observe)
199
+ expected.zip(seen).each_with_index { |(want, got), i| compare(want, got, i) }
200
+ if seen.size > expected.size
201
+ extra = seen[expected.size]
202
+ diverged(step: extra.step, expected: nil, actual: extra.values,
203
+ why: "the rerun observed more than the journal did")
204
+ end
205
+ Result.new(mode: :rerun, steps: seen.size, final_loss: final, divergences: @divergences.dup)
206
+ end
207
+
208
+ private
209
+
210
+ def compare(want, got, index)
211
+ if got.nil?
212
+ diverged(step: want.step, expected: want.values, actual: nil,
213
+ why: "the rerun observed nothing here")
214
+ elsif want.values.keys.sort != got.values.keys.sort
215
+ diverged(step: want.step, expected: want.values, actual: got.values,
216
+ why: "the rerun observed different things")
217
+ else
218
+ want.values.each_pair do |key, value|
219
+ other = got.values.fetch(key)
220
+ next if agrees?(value, other)
221
+
222
+ diverged(step: want.step, expected: { key => value }, actual: { key => other },
223
+ why: "observation #{index} differs on #{key}")
224
+ end
225
+ end
226
+ end
227
+ end
228
+ end
229
+ end