torobi 0.1.0-arm64-darwin
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +71 -0
- data/LICENSE +21 -0
- data/README.md +259 -0
- data/config/ops.yml +230 -0
- data/docs/plan.md +3982 -0
- data/docs/vendoring.md +656 -0
- data/lib/torobi/3.3/torobi.bundle +0 -0
- data/lib/torobi/3.4/torobi.bundle +0 -0
- data/lib/torobi/4.0/torobi.bundle +0 -0
- data/lib/torobi/adapter_file.rb +184 -0
- data/lib/torobi/batch.rb +55 -0
- data/lib/torobi/checkpoint.rb +60 -0
- data/lib/torobi/dsl/builder.rb +414 -0
- data/lib/torobi/dsl/handle.rb +156 -0
- data/lib/torobi/dsl/layers.rb +82 -0
- data/lib/torobi/dsl.rb +35 -0
- data/lib/torobi/errors.rb +88 -0
- data/lib/torobi/export.rb +534 -0
- data/lib/torobi/freeze.rb +24 -0
- data/lib/torobi/freshness.rb +57 -0
- data/lib/torobi/grad_cache.rb +143 -0
- data/lib/torobi/graph_config.rb +301 -0
- data/lib/torobi/hooks.rb +439 -0
- data/lib/torobi/ir/dimensions.rb +26 -0
- data/lib/torobi/ir/dtype.rb +28 -0
- data/lib/torobi/ir/graph/check.rb +116 -0
- data/lib/torobi/ir/graph.rb +52 -0
- data/lib/torobi/ir/input_spec.rb +39 -0
- data/lib/torobi/ir/json.rb +45 -0
- data/lib/torobi/ir/node_spec.rb +52 -0
- data/lib/torobi/ir/parameter_spec.rb +67 -0
- data/lib/torobi/ir/ref.rb +52 -0
- data/lib/torobi/ir/source.rb +65 -0
- data/lib/torobi/ir.rb +23 -0
- data/lib/torobi/journal.rb +310 -0
- data/lib/torobi/lora.rb +190 -0
- data/lib/torobi/memory.rb +50 -0
- data/lib/torobi/metallib.rb +50 -0
- data/lib/torobi/mlx_prebuilt.json +24 -0
- data/lib/torobi/mlx_prebuilt.rb +378 -0
- data/lib/torobi/models/build.rb +37 -0
- data/lib/torobi/models/description.rb +59 -0
- data/lib/torobi/models/gemma3.rb +273 -0
- data/lib/torobi/models/llama.rb +381 -0
- data/lib/torobi/models/modern_bert.rb +513 -0
- data/lib/torobi/models/padding.rb +27 -0
- data/lib/torobi/models/windows.rb +53 -0
- data/lib/torobi/ops.rb +81 -0
- data/lib/torobi/preflight.rb +136 -0
- data/lib/torobi/provenance.rb +75 -0
- data/lib/torobi/quantization.rb +151 -0
- data/lib/torobi/replay.rb +229 -0
- data/lib/torobi/runner.rb +419 -0
- data/lib/torobi/session.rb +855 -0
- data/lib/torobi/shape.rb +438 -0
- data/lib/torobi/tensor_data.rb +178 -0
- data/lib/torobi/version.rb +5 -0
- data/lib/torobi/weights.rb +108 -0
- data/lib/torobi.rb +67 -0
- data/licenses/MLX.txt +21 -0
- data/licenses/README.md +16 -0
- data/licenses/gguflib.txt +21 -0
- data/licenses/mlx-c.txt +21 -0
- data/licenses/mlx-rs.txt +27 -0
- metadata +196 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
# Whether the compiled extension is older than the engine it was built
|
|
5
|
+
# from.
|
|
6
|
+
#
|
|
7
|
+
# Torobi is one description held in two halves: the Ruby that builds a
|
|
8
|
+
# graph and the Rust that runs it. They are compiled at different
|
|
9
|
+
# times, and when the Rust half is behind, what it looks like is the
|
|
10
|
+
# engine refusing a graph Ruby built happily. An op it does not know, a
|
|
11
|
+
# shape it will not take: all of them true, none of them the reason.
|
|
12
|
+
#
|
|
13
|
+
# m: node 11 (reshape): a shape is positive integers and at most
|
|
14
|
+
# one -1, got [0, 0, 8, 64]
|
|
15
|
+
#
|
|
16
|
+
# That is a confusing way to be told to run `rake compile`, so this
|
|
17
|
+
# says it plainly instead, once, when the sources are there to compare
|
|
18
|
+
# against. An installed gem carries no `engine/src` and this does
|
|
19
|
+
# nothing at all.
|
|
20
|
+
module Freshness
|
|
21
|
+
module_function
|
|
22
|
+
|
|
23
|
+
# The extension this process actually loaded, whatever it is called
|
|
24
|
+
# on this platform, or nil if none was.
|
|
25
|
+
def extension
|
|
26
|
+
$LOADED_FEATURES.grep(%r{/torobi\.(bundle|so|dylib)\z}).first
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# The newest thing the engine is built from, or nil where there is
|
|
30
|
+
# nothing to compare against. `Cargo.toml` counts: a dependency
|
|
31
|
+
# changing is a rebuild too.
|
|
32
|
+
def engine(root)
|
|
33
|
+
Dir[File.join(root, "engine", "src", "**", "*.rs"),
|
|
34
|
+
File.join(root, "engine", "Cargo.toml")]
|
|
35
|
+
.filter_map { |path| File.mtime(path) }.max
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def stale?(built = extension, root: File.expand_path("../..", __dir__))
|
|
39
|
+
return false unless built && File.exist?(built)
|
|
40
|
+
|
|
41
|
+
newest = engine(root)
|
|
42
|
+
!newest.nil? && newest > File.mtime(built)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Said on stderr rather than raised. What is loaded may still be
|
|
46
|
+
# perfectly able to run what this process asks of it, and a warning
|
|
47
|
+
# that turns out to be unnecessary is cheaper than a refusal that
|
|
48
|
+
# turns out to be wrong.
|
|
49
|
+
def warn!(built = extension, root: File.expand_path("../..", __dir__), io: $stderr)
|
|
50
|
+
return unless stale?(built, root:)
|
|
51
|
+
|
|
52
|
+
io.puts "torobi: engine/src is newer than the extension that is loaded " \
|
|
53
|
+
"(#{built}). Run `rake compile`; until then the engine may refuse " \
|
|
54
|
+
"graphs this Ruby builds, and say something else."
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
# A contrastive batch larger than the machine can hold.
|
|
5
|
+
#
|
|
6
|
+
# A loss whose negatives are the other rows wants the largest batch it
|
|
7
|
+
# can get, and the memory a batch needs is set by the activations kept
|
|
8
|
+
# for the backward pass. The gradient cache (Gao et al., 2021) separates
|
|
9
|
+
# the two: encode the parts one at a time **without** keeping activations,
|
|
10
|
+
# work out the loss over all of the representations at once, then encode
|
|
11
|
+
# each part again and back-propagate it with the loss's gradient by its
|
|
12
|
+
# representations as the seed. Memory is then set by one part, and the
|
|
13
|
+
# contrastive signal by the whole.
|
|
14
|
+
#
|
|
15
|
+
# Nothing here is new machinery. It is four things Torobi already has,
|
|
16
|
+
# in the order the algorithm puts them:
|
|
17
|
+
#
|
|
18
|
+
# 1. `evaluate` with a tap, which is a forward that keeps nothing
|
|
19
|
+
# 2. `field_gradients`, which is dL/d(representations)
|
|
20
|
+
# 3. an objective of `sum(representations * seed)`, whose gradient by
|
|
21
|
+
# the parameters is exactly the product of the seed with the
|
|
22
|
+
# Jacobian, which is what back-propagating a seed means
|
|
23
|
+
# 4. `accumulate` / `apply!`, which sums the parts and steps once
|
|
24
|
+
#
|
|
25
|
+
# What it asks of the graphs:
|
|
26
|
+
#
|
|
27
|
+
# encoder a named node holding the representations (`tap:`), and a
|
|
28
|
+
# batch field for the seed (`seed:`) whose objective is
|
|
29
|
+
# `sum(node * seed)`. Declare the seed with a symbolic
|
|
30
|
+
# shape (`[nil, nil]`): on the pass that only wants the tap
|
|
31
|
+
# a single zero stands in for it and broadcasts, so this
|
|
32
|
+
# needs to know neither how wide a representation is nor how
|
|
33
|
+
# many rows a part holds.
|
|
34
|
+
# loss a batch field for the representations (`into:`), and the
|
|
35
|
+
# real loss as its objective. It is opened once and never
|
|
36
|
+
# steps; nothing in it moves.
|
|
37
|
+
#
|
|
38
|
+
# **The graph must draw no randomness.** Each part is encoded twice and
|
|
39
|
+
# the two must agree; dropout would make them different passes, and the
|
|
40
|
+
# seed from the first would be the wrong answer for the second. ModernBERT
|
|
41
|
+
# as `Torobi::Models` builds it has no random ops.
|
|
42
|
+
#
|
|
43
|
+
# cache = Torobi::GradCache.new(encoder, loss: scores,
|
|
44
|
+
# tap: "m.embeddings", into: :vectors,
|
|
45
|
+
# seed: :cotangent)
|
|
46
|
+
# cache.step(parts) # => the loss over the whole batch
|
|
47
|
+
#
|
|
48
|
+
# `parts` is an Enumerable of batches. Their rows keep their order: the
|
|
49
|
+
# representations are stacked in the order the parts arrive, and the
|
|
50
|
+
# loss graph sees them that way.
|
|
51
|
+
class GradCache
|
|
52
|
+
# The seed for a pass that is not using it. One zero, which broadcasts
|
|
53
|
+
# over whatever the representations turn out to be, so the first pass
|
|
54
|
+
# needs no notion of their shape.
|
|
55
|
+
NOTHING = TensorData.filled([1, 1], 0.0)
|
|
56
|
+
|
|
57
|
+
# How many parts the last step was made of, and how many rows they
|
|
58
|
+
# held. For a caller watching what its splitting actually does.
|
|
59
|
+
attr_reader :parts, :rows
|
|
60
|
+
|
|
61
|
+
def initialize(session, loss:, tap:, into:, seed:)
|
|
62
|
+
if session.random?
|
|
63
|
+
raise ConfigError,
|
|
64
|
+
"a gradient cache encodes each part twice and the two must agree, and a graph with " \
|
|
65
|
+
"a dropout (a LoRA with dropout:, say) draws a different mask each time"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
@session = session
|
|
69
|
+
@loss = loss
|
|
70
|
+
@tap = tap.to_s
|
|
71
|
+
@into = into
|
|
72
|
+
@seed = seed
|
|
73
|
+
@parts = 0
|
|
74
|
+
@rows = 0
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# One optimizer step over every part, and the loss it was taken on.
|
|
78
|
+
#
|
|
79
|
+
# The parts are walked three times: once to encode them, once for the
|
|
80
|
+
# loss and its gradient, once to back-propagate. They are therefore
|
|
81
|
+
# kept, so an Enumerable that can only be read once is read into an
|
|
82
|
+
# Array here rather than surprising the caller half way through.
|
|
83
|
+
def step(parts)
|
|
84
|
+
parts = parts.to_a
|
|
85
|
+
raise ArgumentError, "a step needs at least one part" if parts.empty?
|
|
86
|
+
|
|
87
|
+
cached = parts.map { |part| encode(part) }
|
|
88
|
+
@parts = parts.size
|
|
89
|
+
@rows = cached.sum { |data| data.shape.first }
|
|
90
|
+
|
|
91
|
+
whole = stack(cached)
|
|
92
|
+
loss = @loss.evaluate(@into => whole)
|
|
93
|
+
seeds = @loss.field_gradients({ @into => whole }, of: [@into]).fetch(@into.to_s)
|
|
94
|
+
|
|
95
|
+
at = 0
|
|
96
|
+
parts.zip(cached) do |part, data|
|
|
97
|
+
height = data.shape.first
|
|
98
|
+
@session.accumulate(part.merge(@seed => slice(seeds, at, height)))
|
|
99
|
+
at += height
|
|
100
|
+
end
|
|
101
|
+
@session.apply!
|
|
102
|
+
loss
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
private
|
|
106
|
+
|
|
107
|
+
# One part's representations, from a forward that keeps nothing.
|
|
108
|
+
#
|
|
109
|
+
# The seed is zeros here: the objective is a product with it, so the
|
|
110
|
+
# loss is zero and nothing is being asked of it. What is wanted is the
|
|
111
|
+
# tap, and a tap reports whatever pass it watches.
|
|
112
|
+
def encode(part)
|
|
113
|
+
@session.tap(@tap, stat: :full)
|
|
114
|
+
@session.evaluate(part.merge(@seed => NOTHING))
|
|
115
|
+
@session.tapped.fetch(@tap)
|
|
116
|
+
ensure
|
|
117
|
+
@session.untap(@tap)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# The parts' representations as one, in the order they arrived.
|
|
121
|
+
#
|
|
122
|
+
# Bytes, so this is a concatenation rather than a conversion: rows are
|
|
123
|
+
# contiguous and equal width, which makes stacking them along the first
|
|
124
|
+
# axis the same as joining what they are written as.
|
|
125
|
+
def stack(parts)
|
|
126
|
+
width = parts.first.shape.last
|
|
127
|
+
unless parts.all? { |p| p.shape.last == width }
|
|
128
|
+
raise Error, "the parts hold representations of different widths"
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
TensorData.new([parts.sum { |p| p.shape.first }, width],
|
|
132
|
+
parts.map(&:bytes).join, dtype: parts.first.dtype)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# `height` rows of `data`, starting at `at`. The same fact the other
|
|
136
|
+
# way round.
|
|
137
|
+
def slice(data, at, height)
|
|
138
|
+
stride = data.shape.last * data.value_size
|
|
139
|
+
TensorData.new([height, data.shape.last],
|
|
140
|
+
data.bytes.byteslice(at * stride, height * stride), dtype: data.dtype)
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
end
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "digest"
|
|
5
|
+
|
|
6
|
+
module Torobi
|
|
7
|
+
# The serializable artifact the Graph DSL produces and everything else
|
|
8
|
+
# consumes: named model graphs, an optional objective graph wiring them
|
|
9
|
+
# into a loss, which of them are trained, and metadata.
|
|
10
|
+
#
|
|
11
|
+
# Immutable; its canonical JSON is deterministic (fixed key order, models
|
|
12
|
+
# sorted by name), so the same definition always yields the same digest.
|
|
13
|
+
class GraphConfig < Data.define(:schema_version, :semantics_version, :models,
|
|
14
|
+
:objective, :train, :metadata)
|
|
15
|
+
SCHEMA_VERSION = 1
|
|
16
|
+
SEMANTICS_VERSION = 1
|
|
17
|
+
|
|
18
|
+
# The one output an objective declares. The engine differentiates it,
|
|
19
|
+
# so there is no room for a second, and no room for a guess.
|
|
20
|
+
LOSS = "loss"
|
|
21
|
+
|
|
22
|
+
# A parameter as the engine sees it: namespaced by its model, and
|
|
23
|
+
# carrying whether gradients are wanted for it.
|
|
24
|
+
Parameter = Data.define(:model, :path, :spec, :trained) do
|
|
25
|
+
# "student.layers.0.wqkv.weight"
|
|
26
|
+
def qualified_path = "#{model}.#{path}"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def initialize(models:, objective: nil, train: nil, metadata: {},
|
|
30
|
+
schema_version: SCHEMA_VERSION, semantics_version: SEMANTICS_VERSION)
|
|
31
|
+
unless models.is_a?(Hash) && !models.empty?
|
|
32
|
+
raise ConfigError, "models must be a non-empty Hash of name => Graph"
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
models = models.to_h do |name, graph|
|
|
36
|
+
name = name.to_s
|
|
37
|
+
raise ConfigError, "model name must not be empty" if name.empty?
|
|
38
|
+
# A model name qualifies what the model declares ("m.embedding",
|
|
39
|
+
# "m.layers.0.attn.Wqkv.weight"), and the dot is what joins them.
|
|
40
|
+
# An output's own name may hold one (`towers` declares
|
|
41
|
+
# "queries.embedding"), so a name with a dot on both sides has two
|
|
42
|
+
# readings: model "a" with output "b.c", or model "a.b" with
|
|
43
|
+
# output "c". Refused here, where the ambiguity is created.
|
|
44
|
+
if name.include?(".")
|
|
45
|
+
raise ConfigError,
|
|
46
|
+
"model name #{name.inspect} holds a dot, and a dot is what joins a " \
|
|
47
|
+
"model to what it declares; #{name}.x could then be two things"
|
|
48
|
+
end
|
|
49
|
+
unless graph.is_a?(IR::Graph)
|
|
50
|
+
raise ConfigError, "model #{name.inspect} is a #{graph.class}, expected Torobi::IR::Graph"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
[-name, graph]
|
|
54
|
+
end
|
|
55
|
+
if objective && !objective.is_a?(IR::Graph)
|
|
56
|
+
raise ConfigError, "objective is a #{objective.class}, expected Torobi::IR::Graph"
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
models.each do |name, graph|
|
|
60
|
+
check_reads_batch(name, graph)
|
|
61
|
+
check_packed_are_frozen(name, graph)
|
|
62
|
+
end
|
|
63
|
+
train = check_train(train, models)
|
|
64
|
+
if objective
|
|
65
|
+
check_objective(objective)
|
|
66
|
+
check_wiring(objective, models)
|
|
67
|
+
elsif !train.empty?
|
|
68
|
+
check_single_loss(models)
|
|
69
|
+
end
|
|
70
|
+
metadata = IR::Json.primitive!(metadata.transform_keys(&:to_s), where: "metadata")
|
|
71
|
+
|
|
72
|
+
super(schema_version: Integer(schema_version),
|
|
73
|
+
semantics_version: Integer(semantics_version),
|
|
74
|
+
models: Freeze.deep(models.sort.to_h), objective:,
|
|
75
|
+
train: Freeze.deep(train), metadata: Freeze.deep(metadata))
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Every parameter, model by model in name order, each namespaced and
|
|
79
|
+
# marked with whether it is differentiated. This order is the contract:
|
|
80
|
+
# checkpoints and the engine's argnums both follow it.
|
|
81
|
+
def parameters
|
|
82
|
+
models.flat_map do |name, graph|
|
|
83
|
+
trained = train.include?(name)
|
|
84
|
+
graph.parameters.map do |spec|
|
|
85
|
+
Parameter.new(model: name, path: spec.path, spec:,
|
|
86
|
+
trained: trained && spec.trainable)
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# The positions in `parameters` that autodiff differentiates: trainable
|
|
92
|
+
# parameters of trained models, and nothing else (docs/plan.md 5A.3).
|
|
93
|
+
def argnums
|
|
94
|
+
params = parameters
|
|
95
|
+
params.each_index.select { |i| params[i].trained }
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def to_h
|
|
99
|
+
{
|
|
100
|
+
"schema_version" => schema_version,
|
|
101
|
+
"semantics_version" => semantics_version,
|
|
102
|
+
"models" => models.to_h { |name, graph| [name, graph.to_h] },
|
|
103
|
+
"objective" => objective&.to_h,
|
|
104
|
+
"train" => train,
|
|
105
|
+
"metadata" => IR::Json.canonical(metadata)
|
|
106
|
+
}
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# The one serialization the digest is defined over. Key order is fixed by
|
|
110
|
+
# construction (ordered hashes; models, train and metadata sorted).
|
|
111
|
+
def canonical_json
|
|
112
|
+
JSON.generate(to_h)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def digest
|
|
116
|
+
Digest::SHA256.hexdigest(canonical_json)
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# Whether any graph of it draws randomness (a `dropout`). Two passes over
|
|
120
|
+
# the same batch then differ, which a gradient cache cannot have
|
|
121
|
+
# (`Torobi::GradCache`).
|
|
122
|
+
def random?
|
|
123
|
+
graphs = [*models.values, objective].compact
|
|
124
|
+
graphs.any? { |graph| graph.nodes.any? { |node| node.op.to_s == "dropout" } }
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Whether this config has a loss: something to train on, to evaluate,
|
|
128
|
+
# or to differentiate.
|
|
129
|
+
#
|
|
130
|
+
# An objective's is the one it declares. Without an objective it is the
|
|
131
|
+
# single model's single scalar output, which is the shorthand a spike
|
|
132
|
+
# is written in. A config that trains nothing and declares neither has
|
|
133
|
+
# no loss at all, and is one opened to look at what a model produces
|
|
134
|
+
# (`Session#forward`) rather than to move it.
|
|
135
|
+
def loss?
|
|
136
|
+
return true if objective
|
|
137
|
+
return false unless models.size == 1
|
|
138
|
+
|
|
139
|
+
graph = models.values.first
|
|
140
|
+
return false unless graph.outputs.size == 1
|
|
141
|
+
|
|
142
|
+
shape, dtype = graph.output_signature(graph.outputs.keys.first)
|
|
143
|
+
shape.empty? && dtype == :f32
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def self.from_h(h)
|
|
147
|
+
new(schema_version: h.fetch("schema_version"),
|
|
148
|
+
semantics_version: h.fetch("semantics_version"),
|
|
149
|
+
models: h.fetch("models").transform_values { |g| IR::Graph.from_h(g) },
|
|
150
|
+
objective: h["objective"]&.then { |g| IR::Graph.from_h(g) },
|
|
151
|
+
train: h["train"],
|
|
152
|
+
metadata: h.fetch("metadata"))
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
private
|
|
156
|
+
|
|
157
|
+
# Which models a run differentiates. Omitted means all of them, which
|
|
158
|
+
# is what training is; `train: []` means none, which is a graph opened
|
|
159
|
+
# to be read rather than trained (a loss over representations computed
|
|
160
|
+
# elsewhere, say). Saying it is what separates that from the mistake
|
|
161
|
+
# of declaring nothing trainable by accident, which is still refused.
|
|
162
|
+
def check_train(train, models)
|
|
163
|
+
return models.keys.sort if train.nil?
|
|
164
|
+
|
|
165
|
+
unless train.is_a?(Array)
|
|
166
|
+
raise ConfigError, "train must be an Array of model names, got #{train.inspect}"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
train.map do |name|
|
|
170
|
+
name = name.to_s
|
|
171
|
+
unless models.key?(name)
|
|
172
|
+
raise ConfigError,
|
|
173
|
+
"train names #{name.inspect}, which is not a model here " \
|
|
174
|
+
"(#{models.keys.map(&:inspect).join(", ")})"
|
|
175
|
+
end
|
|
176
|
+
-name
|
|
177
|
+
end.sort.uniq
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# What an objective must be, because the engine has no way to guess
|
|
181
|
+
# otherwise: exactly one output, named "loss", a scalar, and no
|
|
182
|
+
# parameters of its own. Every one of these was representable before,
|
|
183
|
+
# and each ended in the engine picking something arbitrary or indexing
|
|
184
|
+
# past the end of an empty slice.
|
|
185
|
+
def check_objective(objective)
|
|
186
|
+
unless objective.parameters.empty?
|
|
187
|
+
raise ConfigError,
|
|
188
|
+
"an objective has no parameters of its own; move " \
|
|
189
|
+
"#{objective.parameters.map(&:path).map(&:inspect).join(", ")} into a model"
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
names = objective.outputs.keys
|
|
193
|
+
unless names == [LOSS]
|
|
194
|
+
raise ConfigError,
|
|
195
|
+
"an objective declares exactly one output, named #{LOSS.inspect}; " \
|
|
196
|
+
"this one declares #{names.map(&:inspect).join(", ")}"
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
shape, dtype = objective.output_signature(LOSS)
|
|
200
|
+
unless shape.empty?
|
|
201
|
+
raise ConfigError,
|
|
202
|
+
"the loss must be a scalar, and this one has shape #{shape.inspect}; " \
|
|
203
|
+
"reduce it (mean or sum) before declaring it"
|
|
204
|
+
end
|
|
205
|
+
# Read as an f32 at the boundary, which is the whole of why this is
|
|
206
|
+
# checked here rather than found out on the first step.
|
|
207
|
+
return if dtype == :f32
|
|
208
|
+
|
|
209
|
+
raise ConfigError,
|
|
210
|
+
"the loss must be f32, and this one is #{dtype}; a model held in " \
|
|
211
|
+
"another precision says where it comes back (g.cast(x, :f32))"
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# Without an objective, the single model's own single output is the
|
|
215
|
+
# loss, and the same demands apply to it.
|
|
216
|
+
#
|
|
217
|
+
# Only when something is trained. A config that trains nothing is not
|
|
218
|
+
# obliged to produce a number nobody will differentiate, and `train: []`
|
|
219
|
+
# is how a run is opened to be read rather than moved.
|
|
220
|
+
def check_single_loss(models)
|
|
221
|
+
unless models.size == 1
|
|
222
|
+
raise ConfigError,
|
|
223
|
+
"with more than one model an objective says which loss to train; " \
|
|
224
|
+
"this config has #{models.keys.map(&:inspect).join(", ")} and none"
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
name, graph = models.first
|
|
228
|
+
names = graph.outputs.keys
|
|
229
|
+
unless names.size == 1
|
|
230
|
+
raise ConfigError,
|
|
231
|
+
"without an objective, model #{name.inspect} must declare exactly one " \
|
|
232
|
+
"output to be the loss; it declares #{names.map(&:inspect).join(", ")}"
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
shape, dtype = graph.output_signature(names.first)
|
|
236
|
+
return if shape.empty? && dtype == :f32
|
|
237
|
+
|
|
238
|
+
raise ConfigError,
|
|
239
|
+
"without an objective, model #{name.inspect}'s output " \
|
|
240
|
+
"#{names.first.inspect} is the loss, so it must be an f32 scalar, " \
|
|
241
|
+
"and it is #{dtype}#{shape.inspect}. A config that trains nothing " \
|
|
242
|
+
"(train: []) needs no loss, and can be asked what it produces."
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# A packed weight (u32, `Torobi::Quantization`) has no gradient: MLX
|
|
246
|
+
# refuses to differentiate `quantized_matmul` by it, and it would come
|
|
247
|
+
# out of the first step as MLX's exception. The DSL cannot declare one
|
|
248
|
+
# trainable (`Quantization#apply` says `trainable: false`, and an
|
|
249
|
+
# adapter only ever lowers that), so this catches a graph written by
|
|
250
|
+
# hand, where it is written rather than where it runs.
|
|
251
|
+
def check_packed_are_frozen(name, graph)
|
|
252
|
+
packed = graph.parameters.select { |spec| spec.dtype == :u32 && spec.trainable }
|
|
253
|
+
return if packed.empty?
|
|
254
|
+
|
|
255
|
+
raise ConfigError,
|
|
256
|
+
"model #{name.inspect} declares #{packed.first.path.inspect} trainable, and it is " \
|
|
257
|
+
"u32: a packed quantized weight, which has no gradient. Declare it " \
|
|
258
|
+
"trainable: false (g.quantized does), and train an adapter (Torobi::LoRA) " \
|
|
259
|
+
"beside it instead."
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
# A model graph reads only from the batch. Reading another model's
|
|
263
|
+
# output is what an objective is for, and it is the objective that the
|
|
264
|
+
# wiring below holds to what the models declare; a model that read one
|
|
265
|
+
# would be wired by nothing.
|
|
266
|
+
def check_reads_batch(name, graph)
|
|
267
|
+
graph.inputs.each do |input|
|
|
268
|
+
next if input.from_batch?
|
|
269
|
+
|
|
270
|
+
raise ConfigError,
|
|
271
|
+
"model #{name.inspect} input #{input.name.inspect} reads " \
|
|
272
|
+
"#{input.source.model}.#{input.source.output}; a model reads only " \
|
|
273
|
+
"from the batch, and reading another model is an objective's to do"
|
|
274
|
+
end
|
|
275
|
+
end
|
|
276
|
+
|
|
277
|
+
# An objective may read a model output only if that model declares it,
|
|
278
|
+
# with the shape and dtype it declared. The two halves are written
|
|
279
|
+
# separately, so this is where they are held to each other.
|
|
280
|
+
def check_wiring(objective, models)
|
|
281
|
+
objective.inputs.each do |input|
|
|
282
|
+
next unless input.from_model?
|
|
283
|
+
|
|
284
|
+
model_name = input.source.model
|
|
285
|
+
output = input.source.output
|
|
286
|
+
where = "objective input #{input.name.inspect}"
|
|
287
|
+
graph = models[model_name] or
|
|
288
|
+
raise ConfigError,
|
|
289
|
+
"#{where} reads #{model_name}.#{output}, but there is no model " \
|
|
290
|
+
"named #{model_name.inspect} (#{models.keys.map(&:inspect).join(", ")})"
|
|
291
|
+
|
|
292
|
+
shape, dtype = graph.output_signature(output)
|
|
293
|
+
next if shape == input.shape && dtype == input.dtype
|
|
294
|
+
|
|
295
|
+
raise ConfigError,
|
|
296
|
+
"#{where} expects #{input.dtype}#{input.shape.inspect} from " \
|
|
297
|
+
"#{model_name}.#{output}, which is #{dtype}#{shape.inspect}"
|
|
298
|
+
end
|
|
299
|
+
end
|
|
300
|
+
end
|
|
301
|
+
end
|