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,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # One graph input: a name, where its data comes from ([`Source`]), a
6
+ # shape whose nil dimensions are symbolic (batch, sequence), and a dtype.
7
+ class InputSpec < Data.define(:id, :name, :source, :shape, :dtype)
8
+ def initialize(id:, name:, shape:, dtype:, source: nil)
9
+ name = name.to_s
10
+ raise ConfigError, "input #{id}: name must not be empty" if name.empty?
11
+
12
+ where = "input #{name.inspect}"
13
+ shape = Dimensions.check!(shape, where:, symbolic: true)
14
+ Dtype.check!(dtype, where:)
15
+ source ||= Source.batch(name)
16
+ unless source.is_a?(Source::Batch) || source.is_a?(Source::ModelOutput)
17
+ raise ConfigError, "#{where}: source is a #{source.class}, expected an IR::Source"
18
+ end
19
+
20
+ super(id: Integer(id), name: -name, source:, shape:, dtype:)
21
+ end
22
+
23
+ def from_batch? = source.is_a?(Source::Batch)
24
+ def from_model? = source.is_a?(Source::ModelOutput)
25
+
26
+ def to_h
27
+ { "id" => id, "name" => name, "source" => source.to_h, "shape" => shape,
28
+ "dtype" => dtype.to_s }
29
+ end
30
+
31
+ def self.from_h(h)
32
+ where = "input #{h["name"].inspect}"
33
+ new(id: h.fetch("id"), name: h.fetch("name"),
34
+ source: h["source"]&.then { |s| Source.from_h(s, where:) },
35
+ shape: h.fetch("shape"), dtype: h.fetch("dtype").to_sym)
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # What may appear inside attributes, initializers and metadata: JSON
6
+ # primitives only, so the canonical serialization is total and the
7
+ # digest never depends on Ruby object identity.
8
+ module Json
9
+ module_function
10
+
11
+ def primitive!(value, where:)
12
+ case value
13
+ when nil, true, false, Integer, Float, String
14
+ value
15
+ when Array
16
+ value.each { |v| primitive!(v, where:) }
17
+ value
18
+ when Hash
19
+ value.each do |k, v|
20
+ unless k.is_a?(String)
21
+ raise ConfigError, "#{where}: hash keys must be strings, got #{k.inspect}"
22
+ end
23
+
24
+ primitive!(v, where:)
25
+ end
26
+ value
27
+ else
28
+ raise ConfigError,
29
+ "#{where}: #{value.inspect} is not JSON-serializable data " \
30
+ "(allowed: nil, booleans, numbers, strings, arrays, hashes)"
31
+ end
32
+ end
33
+
34
+ # The order-normalized form the canonical JSON is built from: hash keys
35
+ # sorted at every depth, so insertion order never reaches the digest.
36
+ def canonical(value)
37
+ case value
38
+ when Hash then value.sort.to_h { |k, v| [k, canonical(v)] }
39
+ when Array then value.map { |v| canonical(v) }
40
+ else value
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # One operation: which op, what it reads (references to inputs and
6
+ # earlier nodes), which parameters it uses, its attributes, and the
7
+ # shape and dtype shape inference gave it. A node is only ever made
8
+ # after its shape is known, so neither is optional.
9
+ #
10
+ # `name` is a stable path under the scopes the node was built in
11
+ # ("layers.3.attn.sdpa"), which is how a tap asks for it (docs/plan.md
12
+ # section 6.4). Names are unique within a graph, and nil for nodes the
13
+ # DSL did not name.
14
+ class NodeSpec < Data.define(:id, :op, :name, :inputs, :parameters, :attributes,
15
+ :shape, :dtype)
16
+ def initialize(id:, op:, inputs:, shape:, dtype:, name: nil, parameters: [],
17
+ attributes: {})
18
+ op = op.to_s
19
+ raise ConfigError, "node #{id}: op must not be empty" if op.empty?
20
+
21
+ name = name&.to_s
22
+ raise ConfigError, "node #{id}: name must not be empty" if name && name.empty?
23
+
24
+ where = "node #{id} (#{op})"
25
+ # Read here so a malformed reference is refused by the node that
26
+ # holds it; whether it points anywhere is the graph's to say.
27
+ inputs = inputs.map { |ref| Ref.parse(ref) }.freeze
28
+ parameters = Freeze.deep(parameters.map { |pid| Integer(pid) })
29
+ attributes = Freeze.deep(Json.primitive!(attributes.transform_keys(&:to_s),
30
+ where: "#{where} attributes"))
31
+ shape = Dimensions.check!(shape, where:, symbolic: true)
32
+ Dtype.check!(dtype, where:)
33
+ super(id: Integer(id), op: -op, name: name && -name, inputs:, parameters:,
34
+ attributes:, shape:, dtype:)
35
+ end
36
+
37
+ def to_h
38
+ {
39
+ "id" => id, "op" => op, "name" => name, "inputs" => inputs.map(&:to_s),
40
+ "parameters" => parameters, "attributes" => Json.canonical(attributes),
41
+ "shape" => shape, "dtype" => dtype.to_s
42
+ }
43
+ end
44
+
45
+ def self.from_h(h)
46
+ new(id: h.fetch("id"), op: h.fetch("op"), name: h["name"], inputs: h.fetch("inputs"),
47
+ parameters: h.fetch("parameters"), attributes: h.fetch("attributes"),
48
+ shape: h.fetch("shape"), dtype: h.fetch("dtype").to_sym)
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # One learnable (or frozen) tensor: a stable path such as
6
+ # "layers.3.attn.wqkv.weight", a concrete shape, and an initializer
7
+ # declaration. The initializer is data, not code: either a random
8
+ # scheme, or {"type" => "pretrained", ...} naming a tensor in a
9
+ # checkpoint. Parameter order and paths are what checkpoints are
10
+ # validated against, so both must be stable.
11
+ class ParameterSpec < Data.define(:id, :path, :shape, :dtype, :initializer, :trainable)
12
+ def initialize(id:, path:, shape:, dtype:, initializer:, trainable: true)
13
+ path = path.to_s
14
+ raise ConfigError, "parameter #{id}: path must not be empty" if path.empty?
15
+
16
+ where = "parameter #{path.inspect}"
17
+ shape = check_shape(shape, where:)
18
+ Dtype.check!(dtype, where:)
19
+ initializer = check_initializer(initializer, where:)
20
+ unless [true, false].include?(trainable)
21
+ raise ConfigError, "#{where}: trainable must be true or false"
22
+ end
23
+
24
+ super(id: Integer(id), path: -path, shape:, dtype:, initializer:, trainable:)
25
+ end
26
+
27
+ def to_h
28
+ {
29
+ "id" => id, "path" => path, "shape" => shape, "dtype" => dtype.to_s,
30
+ "initializer" => Json.canonical(initializer), "trainable" => trainable
31
+ }
32
+ end
33
+
34
+ def self.from_h(h)
35
+ new(id: h.fetch("id"), path: h.fetch("path"), shape: h.fetch("shape"),
36
+ dtype: h.fetch("dtype").to_sym, initializer: h.fetch("initializer"),
37
+ trainable: h.fetch("trainable"))
38
+ end
39
+
40
+ private
41
+
42
+ # Parameters are storage: every dimension must be concrete, and there
43
+ # is at least one.
44
+ def check_shape(shape, where:)
45
+ raise ConfigError, "#{where}: shape must not be empty (a scalar)" if shape == []
46
+
47
+ Dimensions.check!(shape, where:, symbolic: false)
48
+ end
49
+
50
+ # The top level is keyed like keyword arguments, so `{type: "zeros"}`
51
+ # reads as `{"type" => "zeros"}`; below it an initializer is JSON
52
+ # data like any other, and a symbol key there is refused.
53
+ def check_initializer(initializer, where:)
54
+ unless initializer.is_a?(Hash)
55
+ raise ConfigError, "#{where}: initializer must be a Hash, got #{initializer.inspect}"
56
+ end
57
+
58
+ initializer = initializer.transform_keys(&:to_s)
59
+ unless initializer["type"]
60
+ raise ConfigError,
61
+ "#{where}: initializer must have a \"type\" key, got #{initializer.inspect}"
62
+ end
63
+ Freeze.deep(Json.primitive!(initializer, where: "#{where} initializer"))
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # A reference from one IR value to another: the `id`th input, or the
6
+ # `id`th node. Written as a short string so the JSON stays readable
7
+ # ("input:0", "node:3"), and read back from it once, where it enters,
8
+ # so everything past that asks the value rather than the text.
9
+ #
10
+ # Parameters are referenced by their bare id in NodeSpec, not through
11
+ # Ref, since they live in a namespace of their own.
12
+ class Ref < Data.define(:kind, :id)
13
+ KINDS = %i[input node].freeze
14
+ PATTERN = /\A(input|node):(0|[1-9][0-9]*)\z/
15
+
16
+ def self.input(id) = new(kind: :input, id:)
17
+ def self.node(id) = new(kind: :node, id:)
18
+
19
+ # The reference `ref` is, or is written as. A Ref passes through.
20
+ def self.parse(ref)
21
+ return ref if ref.is_a?(Ref)
22
+
23
+ m = PATTERN.match(ref.to_s) or
24
+ raise ConfigError, "#{ref.inspect} is not a reference; expected \"input:N\" or \"node:N\""
25
+ new(kind: m[1].to_sym, id: Integer(m[2]))
26
+ end
27
+
28
+ def initialize(kind:, id:)
29
+ raise ConfigError, "a reference is to an input or a node, not #{kind.inspect}" unless
30
+ KINDS.include?(kind)
31
+
32
+ super(kind:, id: Integer(id))
33
+ end
34
+
35
+ def input? = kind == :input
36
+ def node? = kind == :node
37
+
38
+ # The spec this points at, among `inputs` and `nodes`, or a
39
+ # ConfigError saying `where` asked for something that is not there.
40
+ def resolve(inputs:, nodes:, where:)
41
+ specs = input? ? inputs : nodes
42
+ return specs[id] if id < specs.size
43
+
44
+ raise ConfigError, "#{where} references unknown #{self}"
45
+ end
46
+
47
+ def to_s = "#{kind}:#{id}"
48
+
49
+ def inspect = to_s
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # Where an input's data comes from. Every input says so, uniformly, as
6
+ # one of two kinds:
7
+ #
8
+ # Batch.new(field: "x") {"batch" => "x"}
9
+ # ModelOutput.new(model: "student", {"model" => "student",
10
+ # output: "logits") "output" => "logits"}
11
+ #
12
+ # A model graph reads only from the batch. An objective graph reads from
13
+ # both, and that is how the two halves of a GraphConfig are wired
14
+ # (docs/plan.md section 5A.3); GraphConfig holds both to it.
15
+ module Source
16
+ # A field of the batch the run is fed.
17
+ Batch = Data.define(:field) do
18
+ def initialize(field:)
19
+ super(field: Source.name!(field, "batch field"))
20
+ end
21
+
22
+ def to_h = { "batch" => field }
23
+ end
24
+
25
+ # A named output of another model in the same config.
26
+ ModelOutput = Data.define(:model, :output) do
27
+ def initialize(model:, output:)
28
+ super(model: Source.name!(model, "model name"),
29
+ output: Source.name!(output, "output name"))
30
+ end
31
+
32
+ def to_h = { "model" => model, "output" => output }
33
+ end
34
+
35
+ module_function
36
+
37
+ # What the DSL calls, with the symbols it is written in.
38
+ def batch(field) = Batch.new(field: field.to_s)
39
+ def model_output(model, output) = ModelOutput.new(model: model.to_s, output: output.to_s)
40
+
41
+ # The source a serialized input names.
42
+ def from_h(h, where:)
43
+ raise ConfigError, "#{where}: source must be a Hash, got #{h.inspect}" unless h.is_a?(Hash)
44
+
45
+ case h.keys.sort
46
+ when ["batch"] then Batch.new(field: h["batch"])
47
+ when %w[model output] then ModelOutput.new(model: h["model"], output: h["output"])
48
+ else
49
+ raise ConfigError,
50
+ "#{where}: a source is {\"batch\" => field} or " \
51
+ "{\"model\" => name, \"output\" => name}, got #{h.inspect}"
52
+ end
53
+ end
54
+
55
+ # The one check both kinds make of what they name. An empty or
56
+ # missing name is refused as the value is made, so no input can hold
57
+ # one, whichever way it arrived.
58
+ def name!(value, what)
59
+ return -value if value.is_a?(String) && !value.empty?
60
+
61
+ raise ConfigError, "#{what} must be a non-empty String, got #{value.inspect}"
62
+ end
63
+ end
64
+ end
65
+ end
data/lib/torobi/ir.rb ADDED
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ir/ref"
4
+ require_relative "ir/dtype"
5
+ require_relative "ir/dimensions"
6
+ require_relative "ir/json"
7
+ require_relative "ir/source"
8
+ require_relative "ir/input_spec"
9
+ require_relative "ir/parameter_spec"
10
+ require_relative "ir/node_spec"
11
+ require_relative "ir/graph"
12
+ require_relative "ir/graph/check"
13
+
14
+ module Torobi
15
+ # The intermediate representation behind the Graph DSL.
16
+ #
17
+ # A graph is data: inputs, parameters, nodes and outputs, each a frozen
18
+ # value object with a stable serialization. The DSL produces these; the
19
+ # engine (and the Python oracle runner) consume them. Nothing in here
20
+ # computes anything.
21
+ module IR
22
+ end
23
+ end
@@ -0,0 +1,310 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ # For Time#iso8601, which is not on Time until somebody asks: a run
5
+ # started by `Torobi::Runner` is a process where nothing else has.
6
+ require "time"
7
+
8
+ module Torobi
9
+ # What a run recorded, so that it can be replayed.
10
+ #
11
+ # A journal is JSONL: one header, then one entry per thing that happened.
12
+ # It is written as it goes, so an interrupted run leaves a readable file.
13
+ #
14
+ # The schema is the one docs/plan.md section 8.5 lists, and it exists for
15
+ # the two modes of section 8.6:
16
+ #
17
+ # action replay applies the recorded operations without running
18
+ # the policy that produced them
19
+ # deterministic rerun runs the policy again and holds it to the
20
+ # observations recorded here
21
+ #
22
+ # The second is why observations are recorded at all. v3.1 said reading
23
+ # needed no record; that was wrong, because a policy that reads and then
24
+ # decides has the reading as its input.
25
+ #
26
+ # Every entry is a value of its own kind (`Journal::Span`, `Adjust`, ...),
27
+ # so what a kind holds is written once, here, and the session that writes
28
+ # one and the replay that reads it back agree by construction rather than
29
+ # by string keys.
30
+ class Journal
31
+ # 3: `batches_digest` names the data a batch held rather than only its
32
+ # field names, and an accumulation carries one too, so a replay can
33
+ # tell whether the batches it is handed are the ones that ran.
34
+ SCHEMA_VERSION = 3
35
+
36
+ def self.now = Time.now.utc.iso8601
37
+
38
+ # What every entry has: its kind, the step it happened at, and when.
39
+ # The rest is the kind's own, and is written beside those three.
40
+ module Entry
41
+ def self.included(kind)
42
+ kind.extend(ClassMethods)
43
+ end
44
+
45
+ module ClassMethods
46
+ # The name the kind is written under.
47
+ attr_accessor :kind
48
+ end
49
+
50
+ # The entry a serialized line holds.
51
+ def self.from_h(h)
52
+ kind = KINDS.fetch(h.fetch("kind")) do
53
+ raise ArgumentError, "#{h["kind"].inspect} is not a journal entry kind " \
54
+ "(#{KINDS.keys.join(", ")})"
55
+ end
56
+ kind.read(h.except("kind", "step", "at"), step: h["step"], at: h["at"])
57
+ end
58
+
59
+ def initialize(at: nil, **fields)
60
+ super(at: at || Journal.now, **fields)
61
+ end
62
+
63
+ def kind = self.class.kind
64
+
65
+ def to_h
66
+ { "kind" => kind, "step" => step, "at" => at }.compact.merge(payload)
67
+ end
68
+
69
+ def to_json(*) = JSON.generate(to_h)
70
+ end
71
+
72
+ # A step was taken: on one batch, or on the `parts` accumulated before
73
+ # it. `batches_digest` (`Batch#digest`) is nil when it took the parts,
74
+ # which have their own `Accumulate` entries.
75
+ Span = Data.define(:step, :at, :steps, :loss, :parts, :batches_digest) do
76
+ include Entry
77
+
78
+ def self.read(h, step:, at:)
79
+ new(step:, at:, steps: h["steps"], loss: h["loss"], parts: h["parts"],
80
+ batches_digest: h["batches_digest"])
81
+ end
82
+
83
+ def initialize(step:, steps: 1, loss: nil, parts: nil, batches_digest: nil, at: nil)
84
+ super
85
+ end
86
+
87
+ def accumulated? = !parts.nil?
88
+
89
+ def payload
90
+ { "steps" => steps, "loss" => loss, "parts" => parts,
91
+ "batches_digest" => batches_digest }.compact
92
+ end
93
+ end
94
+
95
+ # One batch's gradients were added to what is waiting. `batches_digest`
96
+ # names that part's data, so a replay can check the parts it is handed.
97
+ Accumulate = Data.define(:step, :at, :parts, :loss, :batches_digest) do
98
+ include Entry
99
+
100
+ def self.read(h, step:, at:)
101
+ new(step:, at:, parts: h.fetch("parts"), loss: h["loss"],
102
+ batches_digest: h["batches_digest"])
103
+ end
104
+
105
+ def initialize(step:, parts:, loss: nil, batches_digest: nil, at: nil)
106
+ super
107
+ end
108
+
109
+ def payload = { "parts" => parts, "loss" => loss, "batches_digest" => batches_digest }.compact
110
+ end
111
+
112
+ # Knobs turned, by name, to the value the window set. A knob set to nil
113
+ # (`clip: nil`, no cap) is held as nil rather than dropped, because
114
+ # "lifted" and "not touched" are different decisions.
115
+ Adjust = Data.define(:step, :at, :knobs) do
116
+ include Entry
117
+
118
+ def self.read(h, step:, at:) = new(step:, at:, knobs: h)
119
+
120
+ def initialize(step:, knobs:, at: nil)
121
+ super(step:, at:, knobs: Freeze.deep(knobs.transform_keys(&:to_s)))
122
+ end
123
+
124
+ def payload = knobs
125
+ end
126
+
127
+ # What `pattern` matched was frozen (or thawed), and which paths moved.
128
+ Freezing = Data.define(:step, :at, :pattern, :frozen, :moved) do
129
+ include Entry
130
+
131
+ def self.read(h, step:, at:)
132
+ new(step:, at:, pattern: h.fetch("pattern"), frozen: h.fetch("frozen"),
133
+ moved: h.fetch("moved"))
134
+ end
135
+
136
+ def payload = { "pattern" => pattern, "frozen" => frozen, "moved" => moved }
137
+ end
138
+
139
+ # What the window read, and therefore what a policy could have decided
140
+ # on. Recorded so a rerun can be held to it.
141
+ Observe = Data.define(:step, :at, :values) do
142
+ include Entry
143
+
144
+ def self.read(h, step:, at:) = new(step:, at:, values: h)
145
+
146
+ def initialize(step:, values:, at: nil)
147
+ super(step:, at:, values: Freeze.deep(values.transform_keys(&:to_s)))
148
+ end
149
+
150
+ def payload = values
151
+ end
152
+
153
+ # A parameter written from the window, named by digest.
154
+ Put = Data.define(:step, :at, :path, :digest) do
155
+ include Entry
156
+
157
+ def self.read(h, step:, at:)
158
+ new(step:, at:, path: h.fetch("path"), digest: h.fetch("digest"))
159
+ end
160
+
161
+ def payload = { "path" => path, "digest" => digest }
162
+ end
163
+
164
+ # A checkpoint was written.
165
+ Checkpoint = Data.define(:step, :at, :path) do
166
+ include Entry
167
+
168
+ def self.read(h, step:, at:) = new(step:, at:, path: h.fetch("path"))
169
+
170
+ def payload = { "path" => path }
171
+ end
172
+
173
+ # Something happened that a replay does not apply: the run opened,
174
+ # finished a span, exported, restored, closed, ended. `event` says
175
+ # which; the rest is what the one who noted it wanted kept.
176
+ Note = Data.define(:step, :at, :event, :details) do
177
+ include Entry
178
+
179
+ def self.read(h, step:, at:)
180
+ new(step:, at:, event: h.fetch("event"), details: h.except("event"))
181
+ end
182
+
183
+ def initialize(event:, step: nil, details: {}, at: nil)
184
+ details = details.transform_keys(&:to_s).transform_values do |v|
185
+ v.is_a?(Symbol) ? v.to_s : v
186
+ end
187
+ super(step:, at:, event: event.to_s, details: Freeze.deep(details))
188
+ end
189
+
190
+ def [](key) = details[key.to_s]
191
+
192
+ def payload = { "event" => event }.merge(details)
193
+ end
194
+
195
+ KINDS = {
196
+ "span" => Span, "accumulate" => Accumulate, "adjust" => Adjust, "freeze" => Freezing,
197
+ "observe" => Observe, "put" => Put, "checkpoint" => Checkpoint, "note" => Note
198
+ }.each { |name, kind| kind.kind = name }.freeze
199
+
200
+ # The first line: which schema, when, and what the run was.
201
+ Header = Data.define(:schema_version, :started_at, :provenance) do
202
+ def self.from_h(h)
203
+ new(schema_version: h.fetch("schema_version"), started_at: h["started_at"],
204
+ provenance: Provenance.from_h(h.fetch("provenance")))
205
+ end
206
+
207
+ def to_h
208
+ { "schema_version" => schema_version, "started_at" => started_at,
209
+ "provenance" => provenance.to_h }
210
+ end
211
+
212
+ def to_json(*) = JSON.generate(to_h)
213
+ end
214
+
215
+ # A journal as it was read back: its header and its entries.
216
+ Record = Data.define(:header, :entries) do
217
+ # The entries of one kind, in order.
218
+ def of(kind) = entries.grep(kind)
219
+ end
220
+
221
+ attr_reader :header, :entries
222
+
223
+ # `provenance` is everything about the run that is not an event
224
+ # (`Torobi::Provenance`).
225
+ def initialize(provenance, io: nil)
226
+ @header = Header.new(schema_version: SCHEMA_VERSION, started_at: Journal.now, provenance:)
227
+ @entries = []
228
+ @io = io
229
+ write(@header)
230
+ end
231
+
232
+ def span(step:, loss:, parts: nil, batches_digest: nil)
233
+ add(Span.new(step:, loss:, parts:, batches_digest:))
234
+ end
235
+
236
+ def accumulate(step:, parts:, loss:, batches_digest: nil)
237
+ add(Accumulate.new(step:, parts:, loss:, batches_digest:))
238
+ end
239
+
240
+ # The value is what the window set, not what it was.
241
+ def adjust(step:, **knobs) = add(Adjust.new(step:, knobs:))
242
+
243
+ def freezing(step:, pattern:, frozen:, moved:)
244
+ add(Freezing.new(step:, pattern:, frozen:, moved:))
245
+ end
246
+
247
+ def observe(step:, **values) = add(Observe.new(step:, values:))
248
+
249
+ def put(step:, path:, digest:) = add(Put.new(step:, path:, digest:))
250
+
251
+ def checkpoint(step:, path:) = add(Checkpoint.new(step:, path:))
252
+
253
+ # Anything a caller wants in the record; not interpreted.
254
+ def note(event:, step: nil, **details) = add(Note.new(event:, step:, details:))
255
+
256
+ def close
257
+ @io&.flush
258
+ self
259
+ end
260
+
261
+ # The journal as it would be re-read.
262
+ def to_record = Record.new(header: @header, entries: @entries.dup.freeze)
263
+
264
+ def to_jsonl = [@header, *@entries].map(&:to_json).join("\n") << "\n"
265
+
266
+ # Parses a journal back.
267
+ #
268
+ # A run that was killed leaves whole lines and, possibly, a last one
269
+ # that never finished: entries are flushed one at a time, but a write
270
+ # is not atomic. So an unterminated final line is dropped, and only
271
+ # that one. A broken line anywhere else means the file is damaged
272
+ # rather than truncated, and saying so is better than reading past it.
273
+ def self.read(text)
274
+ lines = text.lines
275
+ lines.pop if lines.last && !lines.last.end_with?("\n")
276
+ header, *entries = lines.reject { |line| line.strip.empty? }.map { |line| JSON.parse(line) }
277
+ header = Header.from_h(header)
278
+ # Refused rather than read: an entry does not mean the same thing
279
+ # across a schema change (before 3, `batches_digest` named a batch's
280
+ # field names rather than its data), and a replay of one under the
281
+ # other's meaning would report the data as changed when it had not.
282
+ unless header.schema_version == SCHEMA_VERSION
283
+ raise ArgumentError,
284
+ "this journal is schema #{header.schema_version}, and this version reads " \
285
+ "schema #{SCHEMA_VERSION}; what its entries mean is not the same across a " \
286
+ "schema change, so it is refused rather than read"
287
+ end
288
+
289
+ Record.new(header:, entries: entries.map { |h| Entry.from_h(h) })
290
+ end
291
+
292
+ private
293
+
294
+ def add(entry)
295
+ @entries << entry
296
+ write(entry)
297
+ entry
298
+ end
299
+
300
+ # Flushed per entry, because the promise is that an interrupted run
301
+ # leaves a readable file, and a buffer that never reached the disk is
302
+ # not one.
303
+ def write(line)
304
+ return unless @io
305
+
306
+ @io.puts(line.to_json)
307
+ @io.flush
308
+ end
309
+ end
310
+ end