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,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Base class for everything Torobi raises.
5
+ #
6
+ # StandardError
7
+ # └── Torobi::Error
8
+ # ├── ConfigError a description that is wrong, found at build time
9
+ # ├── StepError the engine refused; the session is still yours
10
+ # │ └── Busy it is serving another thread. Retry.
11
+ # ├── SessionPoisoned the engine panicked under this session
12
+ # ├── SessionClosed the session was closed
13
+ # ├── RuntimePoisoned it panicked holding MLX; no session here is usable
14
+ # └── EngineUnavailable MLX cannot run here at all
15
+ #
16
+ # Ctrl-C stays Ruby's own `Interrupt`, and `Timeout::Error` stays
17
+ # `Timeout::Error`. Neither is translated into anything above: turning an
18
+ # interrupt into a StandardError would have `rescue => e` swallow it, and
19
+ # a training loop that cannot be stopped by Ctrl-C is worse than one that
20
+ # fails (notes/SESSION_CONCURRENCY_SPEC.md section 7).
21
+ #
22
+ # The hierarchy is the error contract of docs/plan.md section 5A.4, and it
23
+ # is a contract about *when* a failure is found and *what survives it*:
24
+ #
25
+ # ConfigError found while building, before any engine exists.
26
+ # Nothing to recover: the description is wrong.
27
+ # StepError found while running. The engine reported it, the
28
+ # session survives, and another step may be tried.
29
+ # Busy the session is serving another thread. Nothing is
30
+ # wrong with it; the call may be retried.
31
+ # SessionPoisoned the engine panicked. The session is not usable.
32
+ # RuntimePoisoned the engine panicked while it held MLX. No session
33
+ # in this process is usable.
34
+ # SessionClosed the session was closed.
35
+ # EngineUnavailable the engine cannot run here at all. Raised before
36
+ # MLX is touched, because some of these failures
37
+ # would otherwise end the process (section 4.1).
38
+ #
39
+ # Why Busy sits under StepError and the last two do not: a caller that
40
+ # rescues StepError means "the engine refused, the session is still mine".
41
+ # That is true of Busy and false of the others, where the session is gone.
42
+ #
43
+ # There is no class for "interrupted". A pending interrupt can stop the
44
+ # engine's blocking region from starting, but the binding retries rather
45
+ # than reporting it (notes/SESSION_CONCURRENCY_SPEC.md section 5), because
46
+ # the flag it reads is also the scheduler's timer. Ruby raises what it was
47
+ # actually holding, at its own next checkpoint.
48
+ #
49
+ # A fourth kind exists and has no class, by necessity: a failure MLX
50
+ # raises as a C++ exception during initialization aborts the process.
51
+ # Preflight refuses the cases we can foresee; the rest is why the plan
52
+ # says to run under a supervisor.
53
+ class Error < StandardError; end
54
+
55
+ # A description that is wrong: bad references, duplicate names,
56
+ # unreachable nodes, shapes that cannot meet, an objective reading an
57
+ # output no model declares. Raised at construction time, so an invalid
58
+ # graph is never representable as a value.
59
+ class ConfigError < Error; end
60
+
61
+ # A step that could not be taken: a batch that does not match what the
62
+ # graph declared, a parameter that is missing, a shape only MLX could
63
+ # settle. The session is still usable.
64
+ class StepError < Error; end
65
+
66
+ # The session is serving another thread. It serves one at a time, so this
67
+ # is not a fault: wait and try again, or use one session per thread.
68
+ class Busy < StepError; end
69
+
70
+ # The engine panicked under this session. Whatever state it left behind
71
+ # cannot be trusted, so the session refuses everything afterwards. Open a
72
+ # new one, from a checkpoint if there is one.
73
+ class SessionPoisoned < Error; end
74
+
75
+ # An operation on a session that has been closed.
76
+ class SessionClosed < Error; end
77
+
78
+ # The engine panicked while it held MLX. MLX is process-global, so what
79
+ # that left behind is not knowable and nothing more is attempted in this
80
+ # process: every session refuses, not only the one that panicked. Start a
81
+ # new process, from a checkpoint if there is one
82
+ # (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md section 5.2).
83
+ class RuntimePoisoned < Error; end
84
+
85
+ # The engine cannot run here: the extension is missing, or something it
86
+ # needs at runtime is not in place.
87
+ class EngineUnavailable < Error; end
88
+ end
@@ -0,0 +1,534 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "fileutils"
5
+
6
+ module Torobi
7
+ # What a trained model needs around its weights to be a model somebody
8
+ # else can load (docs/plan.md section 14).
9
+ #
10
+ # The engine writes `model.safetensors`. A sentence-transformers
11
+ # checkpoint is that file plus a tokenizer, the transformer's config, and
12
+ # three small descriptions of how the pieces fit. Without the tokenizer
13
+ # there is nothing to turn text into ids, so a directory holding only
14
+ # weights and metadata does not load at all, however correct the
15
+ # metadata is.
16
+ #
17
+ # **So the source model is copied rather than reinvented.** Fine-tuning
18
+ # starts from a published checkpoint, and everything except the weights
19
+ # is still true of the result: the tokenizer, the vocabulary, the
20
+ # sequence length, and how the pooling was configured. Writing those from
21
+ # scratch means writing what this code happens to know, and what it
22
+ # happens to know is not everything: ruri-v3's pooling config carries
23
+ # `include_prompt`, which decides whether the task prefix is inside the
24
+ # average that becomes the vector.
25
+ #
26
+ # Export.new("out/ruri-ft", from: "ruri-v3-130m", pooling: :mean).publish
27
+ #
28
+ # One export is one directory the engine has already written its weights
29
+ # into, and one source to carry from. Held as that, so each step below
30
+ # asks the export rather than being handed its pieces.
31
+ class Export
32
+ # The files a sentence-transformers model is made of, apart from its
33
+ # weights. Named rather than "everything in the directory": a source
34
+ # may also hold `pytorch_model.bin`, which is the same weights before
35
+ # training and must not travel with the new ones, and a README that
36
+ # describes a model this is no longer.
37
+ CARRIED = %w[
38
+ config.json
39
+ sentence_bert_config.json
40
+ config_sentence_transformers.json
41
+ modules.json
42
+ tokenizer.json
43
+ tokenizer_config.json
44
+ tokenizer.model
45
+ special_tokens_map.json
46
+ vocab.txt
47
+ vocab.json
48
+ merges.txt
49
+ spiece.model
50
+ added_tokens.json
51
+ generation_config.json
52
+ chat_template.jinja
53
+ chat_template.json
54
+ ].freeze
55
+
56
+ # Where the pooling module's own configuration lives.
57
+ POOLING = File.join("1_Pooling", "config.json").freeze
58
+
59
+ # What the engine writes the weights as (`state.rs`). Named here
60
+ # because everything in this file is about what sits beside them.
61
+ WEIGHTS = "model.safetensors"
62
+
63
+ # How the pooled vector is made, when the caller says: `mode` (:cls or
64
+ # :mean) and `dim`, the width it pools. Either may be left out, and
65
+ # then what the source said stands.
66
+ class Pooling < Data.define(:mode, :dim)
67
+ MODES = { cls: "pooling_mode_cls_token", mean: "pooling_mode_mean_tokens" }.freeze
68
+
69
+ # A config nobody carried starts from every mode off.
70
+ BLANK = {
71
+ "pooling_mode_cls_token" => false,
72
+ "pooling_mode_mean_tokens" => false,
73
+ "pooling_mode_max_tokens" => false,
74
+ "pooling_mode_mean_sqrt_len_tokens" => false,
75
+ "pooling_mode_weightedmean_tokens" => false,
76
+ "pooling_mode_lasttoken" => false
77
+ }.freeze
78
+
79
+ def initialize(mode: nil, dim: nil)
80
+ if mode && !MODES.key?(mode)
81
+ raise ArgumentError, "pooling must be one of #{MODES.keys.inspect}, got #{mode.inspect}"
82
+ end
83
+
84
+ super
85
+ end
86
+
87
+ # Whether the caller said anything about pooling at all.
88
+ def given? = !(mode.nil? && dim.nil?)
89
+
90
+ # The pooling module's configuration, starting from whatever was
91
+ # carried so that keys this does not know about survive.
92
+ #
93
+ # `include_prompt` is the one that matters and the one most easily
94
+ # lost: it says whether the task prefix is part of the average, which
95
+ # is a property of how the source model was trained rather than a
96
+ # choice being made here.
97
+ def config(carried)
98
+ config = (carried || BLANK).dup
99
+ config["word_embedding_dimension"] = dim if dim
100
+ unless config["word_embedding_dimension"]
101
+ raise ArgumentError, "pooling_dim: is required when nothing carries one"
102
+ end
103
+
104
+ if mode
105
+ MODES.each_value { |flag| config[flag] = false }
106
+ config[MODES.fetch(mode)] = true
107
+ end
108
+ config
109
+ end
110
+ end
111
+
112
+ # The one model this run holds, or a refusal when it holds several.
113
+ def self.sole_model(paths)
114
+ names = paths.map { |path| path.split(".").first }.uniq
115
+ return names.first if names.size == 1
116
+
117
+ raise ArgumentError, "model: is required (this run has #{names.inspect})"
118
+ end
119
+
120
+ # LoRA leaves the weight alone and trains a pair of small matrices
121
+ # next to it, so an adapted run holds the base weights it started
122
+ # with and never moved. Exporting writes every parameter, which would
123
+ # be those weights plus `lora_A` and `lora_B` tensors nothing else
124
+ # knows: **a directory that looks trained and is not.** What makes one
125
+ # is merging (`export_model!(dir, merge: adapter)`, which folds
126
+ # `scale * BA` into each weight and drops the matrices) or writing the
127
+ # adapter by itself (`export_adapter!`). Asked for neither, this
128
+ # refuses rather than writes something misleading.
129
+ #
130
+ # Before the weights are written, so a refusal leaves the directory
131
+ # as it was.
132
+ def self.refuse_adapted!(model, paths)
133
+ adapted = paths.select do |path|
134
+ path.start_with?("#{model}.") && LoRA.adapted?(path)
135
+ end
136
+ return if adapted.empty?
137
+
138
+ raise ConfigError,
139
+ "#{model.inspect} was trained through an adapter (#{adapted.size} " \
140
+ "parameters like #{adapted.first.inspect}), and its base weights have " \
141
+ "not moved. Writing them would be a model that looks trained and is " \
142
+ "not. Say merge: with the adapter to fold it into the weights, or " \
143
+ "write the adapter alone with export_adapter!."
144
+ end
145
+
146
+ # The rows an adapter trains, where a session holds them: `[module, delta, table]` for each,
147
+ # as session paths ("m.model.embed_tokens", "m.model.embed_tokens.trainable_tokens_delta",
148
+ # "m.model.embed_tokens.weight").
149
+ def self.token_rows(paths, model)
150
+ suffix = ".#{LoRA.rows_name}"
151
+ paths.select { |path| path.start_with?("#{model}.") && path.end_with?(suffix) }.map do |delta|
152
+ owner = delta.delete_suffix(suffix)
153
+ [owner.delete_prefix("#{model}."), delta, "#{owner}.weight"]
154
+ end
155
+ end
156
+
157
+ # The rows of `table` (a TensorData of [vocab, dim]) that are `tokens`, as arrays of floats.
158
+ def self.rows_of(table, tokens)
159
+ dim = table.shape.last
160
+ tokens.map do |token|
161
+ offset = token * dim * 4
162
+ if offset + (dim * 4) > table.bytes.bytesize
163
+ raise ConfigError, "token #{token} is not in a table of #{table.shape.first} rows"
164
+ end
165
+
166
+ table.bytes.byteslice(offset, dim * 4).unpack("e*")
167
+ end
168
+ end
169
+
170
+ # `table` with its `tokens` rows made what they are plus `delta`'s rows.
171
+ def self.with_rows_added(table, tokens, delta)
172
+ dim = table.shape.last
173
+ bytes = table.bytes.dup
174
+ rows_of(table, tokens).each_with_index do |row, i|
175
+ added = delta.bytes.byteslice(i * dim * 4, dim * 4).unpack("e*")
176
+ bytes[tokens[i] * dim * 4, dim * 4] = row.zip(added).map { |a, b| a + b }.pack("e*")
177
+ end
178
+ TensorData.new(table.shape, bytes)
179
+ end
180
+
181
+ # The rows as PEFT saves them (`token_adapter.trainable_tokens_delta`): the rows themselves,
182
+ # as they are after training. Added to the file the engine wrote beside the matrices.
183
+ def self.add_token_rows_to_adapter(dir, rows)
184
+ path = File.join(dir, "adapter_model.safetensors")
185
+ tensors = read_safetensors(path)
186
+ rows.each do |name, shape, values|
187
+ tensors["base_model.model.#{name}.token_adapter.#{LoRA.rows_name}"] =
188
+ [shape, values.pack("e*")]
189
+ end
190
+ write_safetensors(path, tensors)
191
+ end
192
+
193
+ # Float32 tensors only, which is what the engine writes and what is written back:
194
+ # `{ name => [shape, bytes] }`.
195
+ def self.read_safetensors(path)
196
+ File.open(path, "rb") do |io|
197
+ header = JSON.parse(io.read(io.read(8).unpack1("Q<")))
198
+ base = io.pos
199
+ header.except("__metadata__").to_h do |name, entry|
200
+ unless entry["dtype"] == "F32"
201
+ raise ConfigError,
202
+ "#{path}: #{name} is #{entry["dtype"]}; an adapter the engine writes is F32"
203
+ end
204
+
205
+ from, to = entry["data_offsets"]
206
+ io.seek(base + from)
207
+ [name, [entry["shape"], io.read(to - from)]]
208
+ end
209
+ end
210
+ end
211
+
212
+ def self.write_safetensors(path, tensors)
213
+ offset = 0
214
+ header = tensors.to_h do |name, (shape, bytes)|
215
+ entry = { "dtype" => "F32", "shape" => shape,
216
+ "data_offsets" => [offset, offset + bytes.bytesize] }
217
+ offset += bytes.bytesize
218
+ [name, entry]
219
+ end
220
+ # (as PEFT writes it: the format named, which `safetensors` loaders for PyTorch read)
221
+ header = { "__metadata__" => { "format" => "pt" } }.merge(header)
222
+ json = JSON.generate(header)
223
+ json += " " * ((8 - (json.bytesize % 8)) % 8)
224
+ File.binwrite(path, [json.bytesize].pack("Q<") + json + tensors.values.map(&:last).join)
225
+ end
226
+
227
+ # That the adapter a run declared is the one a file holds: the rank,
228
+ # the alpha (which is the scale), and the linears. The graph has them
229
+ # built in, so a file that differs would be read as the wrong function.
230
+ def self.check_same_adapter!(declared, saved, dir)
231
+ differences = []
232
+ unless saved.rank == declared.rank
233
+ differences << "rank #{saved.rank} (declared #{declared.rank})"
234
+ end
235
+ unless saved.alpha == declared.alpha
236
+ differences << "lora_alpha #{saved.alpha} (declared #{declared.alpha})"
237
+ end
238
+ unless saved.on.sort == declared.on.sort
239
+ differences << "target_modules #{saved.on.sort.inspect} " \
240
+ "(declared #{declared.on.sort.inspect})"
241
+ end
242
+ unless saved.tokens.sort == declared.tokens.sort
243
+ differences << "trainable_token_indices #{saved.tokens.sort.inspect} " \
244
+ "(declared #{declared.tokens.sort.inspect})"
245
+ end
246
+ return if differences.empty?
247
+
248
+ raise ConfigError,
249
+ "the adapter in #{dir} is not the one this run declared: #{differences.join(", ")}. " \
250
+ "The scale alpha / rank is part of the graph, so it would load as another function."
251
+ end
252
+
253
+ # That the matrices a file holds are exactly the ones a run declared.
254
+ def self.check_same_matrices!(declared, saved, dir)
255
+ missing = declared - saved
256
+ extra = saved - declared
257
+ return if missing.empty? && extra.empty?
258
+
259
+ said = []
260
+ unless missing.empty?
261
+ said << "missing from the file: #{missing.first(3).join(", ")}#{" ..." if missing.size > 3}"
262
+ end
263
+ unless extra.empty?
264
+ said << "not in this run: #{extra.first(3).join(", ")}#{" ..." if extra.size > 3}"
265
+ end
266
+ raise ConfigError, "the matrices in #{dir} are not this run's (#{said.join("; ")})"
267
+ end
268
+
269
+ # What an adapter is multiplied by before it is added: a `LoRA`'s own
270
+ # scale, or a number for whoever has only that.
271
+ # How a model's weights are stored: f32 (what the engine computes in), or bf16 or f16, which
272
+ # is half the size and what a published checkpoint usually is.
273
+ def self.dtype_named(dtype)
274
+ name = dtype.to_s
275
+ return name if %w[f32 bf16 f16].include?(name)
276
+
277
+ raise ConfigError, "a model is exported as :f32, :bf16 or :f16, got #{dtype.inspect}"
278
+ end
279
+
280
+ def self.scale_of(merge)
281
+ return merge.scale if merge.respond_to?(:scale)
282
+ return Float(merge) if merge.is_a?(Numeric)
283
+
284
+ raise ArgumentError,
285
+ "merge: is the adapter (a Torobi::LoRA) or its scale, got #{merge.inspect}"
286
+ end
287
+
288
+ # The `adapter_config.json` PEFT reads beside `adapter_model.safetensors`
289
+ # (docs/qlora.md section 3.6): a `LoraConfig`, as PEFT writes one, with
290
+ # what the graph said. `r` and `lora_alpha` are the adapter's; the
291
+ # `target_modules` are the last segments it was built `on:`, which is
292
+ # how PEFT names them too. `base:` is the published model the adapter
293
+ # was trained on (`base_model_name_or_path`), and `task_type:` is
294
+ # PEFT's word for what the model does ("CAUSAL_LM" for a decoder).
295
+ # Both may be left out; PEFT then has to be told at load time.
296
+ #
297
+ # What is not here is as deliberate: no bias (the adapter trains
298
+ # none), plain initialization, and the matrices' own dtype left to the
299
+ # file. The dropout is the adapter's own, as PEFT's `lora_dropout`.
300
+ def self.adapter_config(adapter, base: nil, task_type: nil, token_modules: nil)
301
+ unless adapter.is_a?(LoRA)
302
+ raise ArgumentError, "adapter: is a Torobi::LoRA, got #{adapter.inspect}"
303
+ end
304
+
305
+ config = {
306
+ "peft_type" => "LORA",
307
+ "task_type" => task_type&.to_s,
308
+ "base_model_name_or_path" => base&.to_s,
309
+ "r" => adapter.rank,
310
+ "lora_alpha" => adapter.alpha,
311
+ "lora_dropout" => adapter.dropout,
312
+ "target_modules" => adapter.on.to_a,
313
+ "bias" => "none",
314
+ "fan_in_fan_out" => false,
315
+ "init_lora_weights" => true,
316
+ "inference_mode" => true,
317
+ "use_rslora" => false,
318
+ "use_dora" => false,
319
+ "rank_pattern" => {},
320
+ "alpha_pattern" => {},
321
+ "modules_to_save" => nil,
322
+ "layers_to_transform" => nil,
323
+ "layers_pattern" => nil,
324
+ "revision" => nil
325
+ }
326
+ return config unless adapter.tokens?
327
+
328
+ # PEFT's `trainable_token_indices`: the ids alone say them for the embedding table (and an
329
+ # output layer tied to it), and a hash of module name to ids when the output layer has rows
330
+ # of its own.
331
+ config["trainable_token_indices"] =
332
+ if token_modules && token_modules.size > 1
333
+ token_modules.to_h do |m|
334
+ [m, adapter.tokens]
335
+ end
336
+ else
337
+ adapter.tokens
338
+ end
339
+ config
340
+ end
341
+
342
+ # Writes that config into `dir`, beside what the engine wrote, and
343
+ # returns its path.
344
+ def self.write_adapter_config(dir, adapter, base: nil, task_type: nil, token_modules: nil)
345
+ config = adapter_config(adapter, base:, task_type:, token_modules:)
346
+ FileUtils.mkdir_p(dir)
347
+ path = File.join(dir, "adapter_config.json")
348
+ File.write(path, "#{JSON.pretty_generate(config)}\n")
349
+ path
350
+ end
351
+
352
+ def initialize(dir, from: nil, pooling: nil, pooling_dim: nil)
353
+ @dir = dir.to_s
354
+ @from = from&.to_s
355
+ @pooling = Pooling.new(mode: pooling, dim: pooling_dim)
356
+ end
357
+
358
+ attr_reader :dir, :from, :pooling
359
+
360
+ # Everything that goes beside the weights, in the order it has to
361
+ # happen. Returns what was carried from the source.
362
+ #
363
+ # **The order is why this is one call rather than three.** The widths
364
+ # have to be read before anything is written, because what they
365
+ # answer is whether the descriptions about to be written are about
366
+ # these weights; and carrying has to happen before the metadata,
367
+ # which starts from whatever pooling config the source had so that
368
+ # keys this code knows nothing about survive.
369
+ def publish
370
+ seen = widths
371
+ carried = carry
372
+ write_metadata(seen)
373
+ carried
374
+ end
375
+
376
+ private
377
+
378
+ def path(name) = File.join(@dir, name)
379
+
380
+ # Copies what the source holds beside the weights, and returns the
381
+ # names copied. No source copies nothing, which is what a model
382
+ # trained from nothing has to do.
383
+ def carry
384
+ return [] unless @from
385
+ raise ArgumentError, "from: #{@from.inspect} is not a directory" unless File.directory?(@from)
386
+
387
+ copied = CARRIED.select { |name| File.file?(File.join(@from, name)) }
388
+ copied.each { |name| FileUtils.cp(File.join(@from, name), path(name)) }
389
+ if File.file?(File.join(@from, POOLING))
390
+ FileUtils.mkdir_p(File.dirname(path(POOLING)))
391
+ FileUtils.cp(File.join(@from, POOLING), path(POOLING))
392
+ copied << POOLING
393
+ end
394
+ copied
395
+ end
396
+
397
+ # The pooling configuration already in the directory, or nil.
398
+ def carried_pooling
399
+ JSON.parse(File.read(path(POOLING)))
400
+ rescue SystemCallError, JSON::ParserError
401
+ nil
402
+ end
403
+
404
+ # Writes the descriptions that are not carried, and overrides the
405
+ # pooling when the caller asks for one.
406
+ #
407
+ # Everything is built and checked before anything is written. What is
408
+ # already there was carried from the source and is the source's to be
409
+ # right about; what this writes is this code's, and it should not write
410
+ # something it can see is wrong.
411
+ def write_metadata(widths)
412
+ carried = carried_pooling
413
+ # Before the pooling config, which refuses a missing dimension: a
414
+ # source that belongs to another model is worth saying so about,
415
+ # rather than reporting whatever else is wrong downstream of it.
416
+ check_widths(carried, widths)
417
+ return if decoder? && !@pooling.given?
418
+
419
+ modules = File.exist?(path("modules.json")) ? nil : modules_json
420
+ pooling = @pooling.config(carried) if @pooling.given? || carried.nil?
421
+ described = File.exist?(path("config_sentence_transformers.json"))
422
+
423
+ FileUtils.mkdir_p(@dir)
424
+ File.write(path("modules.json"), modules) if modules
425
+ if pooling
426
+ FileUtils.mkdir_p(File.dirname(path(POOLING)))
427
+ File.write(path(POOLING), JSON.pretty_generate(pooling))
428
+ end
429
+ return if described
430
+
431
+ File.write(path("config_sentence_transformers.json"),
432
+ sentence_transformers_json)
433
+ end
434
+
435
+ # That the descriptions in the directory are about its weights.
436
+ #
437
+ # Two ways to be wrong, and neither is an error anywhere else: a
438
+ # `pooling_dim` the model does not have makes a pooling layer of the
439
+ # wrong shape, and a source model that is not the one these weights
440
+ # came from carries a tokenizer for another vocabulary. Both are
441
+ # visible in one number, because the hidden state's width is a width
442
+ # the tensors have.
443
+ #
444
+ # Before anything is written, so that a refusal leaves the weights and
445
+ # whatever was carried, and nothing this code made up.
446
+ def check_widths(carried, widths)
447
+ return if widths.empty?
448
+
449
+ # The carried config only when nothing was given, because a given
450
+ # dimension is what overrides it: two complaints about a number the
451
+ # caller has already replaced is one complaint too many.
452
+ claims = { "the given pooling_dim" => @pooling.dim,
453
+ "the source's config.json" => hidden_size }
454
+ unless @pooling.dim
455
+ claims["the carried pooling config"] =
456
+ carried&.dig("word_embedding_dimension")
457
+ end
458
+
459
+ wrong = claims.reject { |_, dim| dim.nil? || widths.include?(dim) }
460
+ return if wrong.empty?
461
+
462
+ said = wrong.map { |what, dim| "#{what} says #{dim}" }.join(", ")
463
+ raise ArgumentError,
464
+ "#{said}, which is not a width these weights have " \
465
+ "(#{widths.to_a.sort.inspect}). The pooled vector is as wide as the " \
466
+ "model's hidden state, so this is either the wrong pooling_dim or the " \
467
+ "wrong `from:`. model.safetensors and anything carried are in #{@dir}; " \
468
+ "no pooling config was written."
469
+ end
470
+
471
+ # Whether what was carried is a language model that continues text
472
+ # (`Qwen2ForCausalLM`, ...) rather than one that embeds it. Nothing about
473
+ # pooling is true of one, so none is written for it: a `modules.json` and a
474
+ # `1_Pooling/` beside a decoder's weights would have sentence-transformers
475
+ # load a chat model as an embedder. Asking for a pooling says otherwise.
476
+ def decoder?
477
+ config = JSON.parse(File.read(path("config.json")))
478
+ Array(config["architectures"]).any? { |name| name.to_s.end_with?("ForCausalLM") }
479
+ rescue SystemCallError, JSON::ParserError
480
+ false
481
+ end
482
+
483
+ # What the transformer's own config calls its hidden state, under
484
+ # whichever of the three names its family uses.
485
+ def hidden_size
486
+ config = JSON.parse(File.read(path("config.json")))
487
+ config.values_at("hidden_size", "d_model", "n_embd").compact.first
488
+ rescue SystemCallError, JSON::ParserError
489
+ nil
490
+ end
491
+
492
+ # Every width the tensors in the weights have, as a Set of trailing
493
+ # dimensions.
494
+ #
495
+ # Enough to answer one question: is the pooled vector's width a width
496
+ # this model actually has? Reading the header is all it takes, and the
497
+ # header is the first thing in the file: eight bytes of length, then
498
+ # that many bytes of JSON.
499
+ #
500
+ # A file that cannot be read raises rather than answering "no widths".
501
+ # The engine reads an export back before returning (docs/plan.md
502
+ # section 15.27), so a file that gets here is one that loaded; an empty
503
+ # answer means every tensor is a scalar, which is a fact about the
504
+ # model rather than a failure to look.
505
+ def widths
506
+ header = File.open(path(WEIGHTS), "rb") do |io|
507
+ JSON.parse(io.read(io.read(8).unpack1("Q<")))
508
+ end
509
+ header.except("__metadata__")
510
+ .values.filter_map { |entry| Array(entry["shape"]).last }
511
+ .to_set
512
+ end
513
+
514
+ # The two modules a plain encoder is: the transformer, and the pooling
515
+ # that turns its tokens into one vector.
516
+ def modules_json
517
+ JSON.pretty_generate([
518
+ { "idx" => 0, "name" => "0", "path" => "",
519
+ "type" => "sentence_transformers.models.Transformer" },
520
+ { "idx" => 1, "name" => "1", "path" => "1_Pooling",
521
+ "type" => "sentence_transformers.models.Pooling" }
522
+ ])
523
+ end
524
+
525
+ def sentence_transformers_json
526
+ JSON.pretty_generate({
527
+ "__version__" => { "torobi" => Torobi::VERSION },
528
+ "prompts" => {},
529
+ "default_prompt_name" => nil,
530
+ "similarity_fn_name" => "cosine"
531
+ })
532
+ end
533
+ end
534
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Deep freezing for the IR values. GraphConfig is a serializable artifact
5
+ # with a digest; nothing may mutate it after construction, or the digest
6
+ # would lie.
7
+ module Freeze
8
+ module_function
9
+
10
+ # Freezes +value+ and everything reachable from it. Returns +value+.
11
+ def deep(value)
12
+ case value
13
+ when Hash
14
+ value.each do |k, v|
15
+ deep(k)
16
+ deep(v)
17
+ end
18
+ when Array
19
+ value.each { |v| deep(v) }
20
+ end
21
+ value.freeze
22
+ end
23
+ end
24
+ end